sessions: a tab's count is the rows it lists, and a Pi subagent's calls are no row delete can't find (lurx98 on X)
lurx98 on X (tweet 2122972281534402597): on the Sessions page the tabs said Codex 6 and Pi 8. Codex, opened, said 0 and "no sessions yet"; Pi said 6 from any other tab. Deleting a row titled "Task: 只读事实核对…" toasted "no such session". Two causes, both about one count path and the list disagreeing: - Codex: agentCounts counted every rollout, while the list drops a subagent thread whose parent thread is gone (keptSubagents,82f09e324: Codex App leaves them behind when a thread is deleted). Both now ask orphanSubagents; agentCounts reads the identities from the parses kept (codexIdentitySnapshot), so a rollout never parsed yet still counts until something reads it (Usage, the Codex tab). - Pi: a pi-subagents scout runs as a Pi of its own and names its own session id to the gateway. The lead's row covers it (NativeIDs, its subIDs), and a tab not shown skips it, but the shown tab deduplicated gateway sessions only by its rows' own ids, so the scout's calls were a row of their own, titled by its "Task: …" prompt. Its count (rows) went up by those. Delete sent that id to the lead's files (the delete handler's NativeIDs path), where no session has it: "no such session". The shown tab now skips the same native ids as the counts and delete. Test: TestSessionTabCountsAreTheirRows (internal/gui), built on the real pi-subagents fixture (Pi 1.4.0, pi-subagents 0.88.1) with the scout's calls through the gateway, and Codex App rollouts whose parent thread is gone. It checks each tab lists the rows it counts, from every tab, and that each listed Pi row deletes. Run: - Old code red: with both files reverted, 5 failures (scout listed as a row, codex 4 vs 2, pi 3 vs 2, delete "no such session"). Reverting only internal/sessions/manage.go: codex 4 vs 2. Reverting only internal/gui/sessions_manage.go: the Pi failures and "no such session". - At 41b4edf87 (on origin/main03314b25a), through mote-run: gofmt -l clean, go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build, then go test ./... -count=1 -timeout 45m: 103 packages ok, no FAIL (gui 203s, sessions 163s, gateway 1045s). - Rebased onto54117164c(gateway files only, none of these): go test ./internal/gui ./internal/sessions -count=1 ok again at the pushed head. - No GUI script changed (client.js untouched), so no GUI suite run. Not tried: the reporter's own files. The Codex fix needs the rollouts parsed once (as above); and agents whose rows can be hidden (GatewayHidden, uninstalled agents' Forget) still count hidden rows on another tab, which the reporter's agents don't have.
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"maps"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
@@ -236,7 +237,17 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) {
|
||||
for i := range list {
|
||||
addCodexModelEffort(&list[i].Session, modelEffort)
|
||||
}
|
||||
native := map[string]bool{}
|
||||
// a gateway session the agent keeps is one of its rows already:
|
||||
// by a row's id, or by any other id a request names it by, a
|
||||
// subagent's included (sessions.NativeIDs). Counted the same
|
||||
// way as the tab of an agent not shown, and as delete tells
|
||||
// them apart, so a Pi subagent's calls are no row of their own
|
||||
// that delete can't find (lurx98 on X: Pi 8 here, 6 on another
|
||||
// tab, and "no such session")
|
||||
native := maps.Clone(view.Native[out.Agent])
|
||||
if native == nil {
|
||||
native = map[string]bool{}
|
||||
}
|
||||
for _, s := range list {
|
||||
native[s.ID] = true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// lurx98 on X: the Sessions page's tabs said Codex 6 and Pi 8; Codex's
|
||||
// tab, opened, said 0 and "no sessions yet", and Pi's said 6 from any
|
||||
// other tab. Deleting a Pi row titled "Task: …" said "no such session".
|
||||
// The Codex rollouts were subagent threads whose parent thread was gone,
|
||||
// listed as no row (keptSubagents) but counted. The Pi ones were a
|
||||
// pi-subagents scout's calls through the gateway, named by the scout's
|
||||
// own session id: the lead's row counts them (NativeIDs), yet the Pi
|
||||
// tab listed them again as a gateway session of their own, which delete
|
||||
// sent to the lead's files, where no session has that id. Each tab's
|
||||
// count is the rows it lists, whichever tab is open, and every row a
|
||||
// tab lists can be deleted.
|
||||
func TestSessionTabCountsAreTheirRows(t *testing.T) {
|
||||
home := sandboxHome(t)
|
||||
// Pi 1.4.0 with pi-subagents 0.88.1: the lead and its scout's run
|
||||
pi := filepath.Join(home, ".pi", "agent")
|
||||
copyTree(t, filepath.Join("..", "sessions", "testdata", "pi-subagents"), pi)
|
||||
const scout = "01a1d480-2447-77e7-b4d4-1747dc3bd17c"
|
||||
// not written to a moment ago, so it can be deleted
|
||||
old := time.Now().Add(-2 * time.Hour)
|
||||
filepath.WalkDir(pi, func(p string, d os.DirEntry, err error) error {
|
||||
if err == nil && !d.IsDir() {
|
||||
err = os.Chtimes(p, old, old)
|
||||
}
|
||||
return err
|
||||
})
|
||||
|
||||
// Codex App: a thread with a subagent of its own, and two subagent
|
||||
// threads (one of the other) whose parent thread was deleted
|
||||
codex := filepath.Join(home, ".codex")
|
||||
t.Setenv("CODEX_HOME", codex)
|
||||
at := time.Now().Add(-2 * time.Hour).UTC()
|
||||
rollout := func(id, parent string, n int) {
|
||||
t.Helper()
|
||||
source := `"vscode"`
|
||||
if parent != "" {
|
||||
source = fmt.Sprintf(`{"subagent":{"thread_spawn":{"parent_thread_id":%q,"depth":1}}}`, parent)
|
||||
}
|
||||
start := at.Add(time.Duration(n) * time.Minute)
|
||||
ts := start.Format(time.RFC3339Nano)
|
||||
lines := []string{
|
||||
fmt.Sprintf(`{"timestamp":%q,"type":"session_meta","payload":{"id":%q,"session_id":%q,"source":%s,"cwd":"/work"}}`, ts, id, id, source),
|
||||
fmt.Sprintf(`{"timestamp":%q,"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"check %s"}]}}`, ts, id),
|
||||
fmt.Sprintf(`{"timestamp":%q,"type":"token_usage_record","payload":{"response_id":"r-%s","session_id":%q,"thread_id":%q,"turn_id":"t","usage":{"input_tokens":100,"cached_input_tokens":0,"output_tokens":10,"reasoning_output_tokens":0,"total_tokens":110}}}`, ts, id, id, id),
|
||||
}
|
||||
p := filepath.Join(codex, "sessions", start.Format("2006/01/02"), "rollout-"+start.Format("2006-01-02T15-04-05")+"-"+id+".jsonl")
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var b bytes.Buffer
|
||||
for _, l := range lines {
|
||||
b.WriteString(l + "\n")
|
||||
}
|
||||
if err := os.WriteFile(p, b.Bytes(), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rollout("01a1e000-0000-7000-8000-000000000001", "", 0)
|
||||
rollout("01a1e000-0000-7000-8000-000000000002", "01a1e000-0000-7000-8000-000000000001", 1)
|
||||
rollout("01a1e000-0000-7000-8000-000000000003", "01a1e000-0000-7000-8000-0000000000ff", 2)
|
||||
rollout("01a1e000-0000-7000-8000-000000000004", "01a1e000-0000-7000-8000-000000000003", 3)
|
||||
|
||||
// the scout's calls through the gateway, and a session of Pi's seen
|
||||
// only through it
|
||||
if err := os.MkdirAll(filepath.Dir(usage.Path()), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := os.Create(usage.Path())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
enc := json.NewEncoder(f)
|
||||
enc.Encode(usage.Record{Time: at, Agent: "pi", Provider: "fake", Model: "m", Session: scout, Input: 10, Status: 200})
|
||||
enc.Encode(usage.Record{Time: at, Agent: "pi", Provider: "fake", Model: "m", Session: "elsewhere", Input: 10, Status: 200})
|
||||
f.Close()
|
||||
sessions.Reset()
|
||||
t.Cleanup(sessions.Reset)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
sessionRoutes(mux, folderOnly{})
|
||||
sessionManageRoutes(mux, folderOnly{})
|
||||
type view struct {
|
||||
Agent string `json:"agent"`
|
||||
Agents []struct {
|
||||
Agent string `json:"agent"`
|
||||
Count int `json:"count"`
|
||||
} `json:"agents"`
|
||||
Sessions []sessions.Managed `json:"sessions"`
|
||||
}
|
||||
get := func(agent string) view {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/sessions/manage?agent="+agent, nil))
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("%s: %d %s", agent, w.Code, w.Body)
|
||||
}
|
||||
var v view
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v.Agent != agent {
|
||||
t.Fatalf("asked for %s, shown %s", agent, v.Agent)
|
||||
}
|
||||
return v
|
||||
}
|
||||
// the rows each tab lists
|
||||
want := map[string]int{"codex": 2, "pi": 2}
|
||||
rows := map[string][]sessions.Managed{}
|
||||
for _, a := range []string{"codex", "pi"} {
|
||||
v := get(a)
|
||||
rows[a] = v.Sessions
|
||||
var ids []string
|
||||
for _, s := range v.Sessions {
|
||||
ids = append(ids, s.ID)
|
||||
}
|
||||
if len(v.Sessions) != want[a] {
|
||||
t.Errorf("%s lists %v, want %d rows", a, ids, want[a])
|
||||
}
|
||||
for _, s := range v.Sessions {
|
||||
if s.ID == scout {
|
||||
t.Errorf("%s lists the scout's calls as a row of their own", a)
|
||||
}
|
||||
}
|
||||
}
|
||||
// every tab's count, whichever tab is open
|
||||
for _, open := range []string{"codex", "pi", "codex"} {
|
||||
for _, a := range get(open).Agents {
|
||||
if n, ok := want[a.Agent]; ok && a.Count != n {
|
||||
t.Errorf("with %s open, the %s tab says %d, its list %d", open, a.Agent, a.Count, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
// every Pi row can be deleted
|
||||
var ids []string
|
||||
for _, s := range rows["pi"] {
|
||||
ids = append(ids, s.ID)
|
||||
}
|
||||
body, _ := json.Marshal(map[string]any{"agent": "pi", "ids": ids})
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/sessions/delete", bytes.NewReader(body)))
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("delete: %d %s", w.Code, w.Body)
|
||||
}
|
||||
var out struct {
|
||||
Deleted []string `json:"deleted"`
|
||||
Refused []json.RawMessage `json:"refused"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(out.Refused) != 0 || len(out.Deleted) != len(ids) {
|
||||
t.Errorf("deleting the Pi rows %v: %s", ids, w.Body)
|
||||
}
|
||||
}
|
||||
+51
-10
@@ -7,6 +7,7 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -133,10 +134,34 @@ func agentCounts(all []file) []AgentCount {
|
||||
// as listAgent lists them, from the parses kept: a copy of a
|
||||
// conversation is not a session of its own (ccCopies)
|
||||
copies := ccCopies(all)
|
||||
// a Codex subagent thread whose parent is gone is no row
|
||||
// (keptSubagents), from the parses kept
|
||||
var codex []file
|
||||
for _, f := range all {
|
||||
if f.agent == "codex" {
|
||||
codex = append(codex, f)
|
||||
}
|
||||
}
|
||||
var orphans map[string]bool
|
||||
if len(codex) > 0 {
|
||||
identities := codexIdentitySnapshot(codex)
|
||||
parents := map[string]string{}
|
||||
for _, f := range codex {
|
||||
id := strings.TrimPrefix(f.key, "codex:")
|
||||
parents[id] = ""
|
||||
if i, ok := identities[id]; ok && i.Role == codexRoleSubagent {
|
||||
parents[id] = i.ParentSession
|
||||
}
|
||||
}
|
||||
orphans = orphanSubagents(parents)
|
||||
}
|
||||
for _, f := range all {
|
||||
if copies[f.key] != "" {
|
||||
continue
|
||||
}
|
||||
if f.agent == "codex" && orphans[strings.TrimPrefix(f.key, "codex:")] {
|
||||
continue
|
||||
}
|
||||
if n[f.agent] == nil {
|
||||
n[f.agent] = map[string]bool{}
|
||||
}
|
||||
@@ -354,24 +379,40 @@ func listAgentWith(agent string, all []file, quick bool) []Managed {
|
||||
// history whose request action you are assessing…", flandern). Their calls
|
||||
// are still counted by Usage.
|
||||
func keptSubagents(out []Managed) []Managed {
|
||||
ids := make(map[string]bool, len(out))
|
||||
parents := make(map[string]string, len(out))
|
||||
for _, m := range out {
|
||||
ids[m.ID] = true
|
||||
parents[m.ID] = ""
|
||||
if m.Role == codexRoleSubagent {
|
||||
parents[m.ID] = m.ParentSession
|
||||
}
|
||||
}
|
||||
gone := orphanSubagents(parents)
|
||||
if len(gone) == 0 {
|
||||
return out
|
||||
}
|
||||
return slices.DeleteFunc(out, func(m Managed) bool { return gone[m.ID] })
|
||||
}
|
||||
|
||||
// orphanSubagents are the Codex subagent threads keptSubagents takes off
|
||||
// the list: parents holds every thread by id, with the thread it is a
|
||||
// subagent of ("" for none). One whose parent is not there, or is such a
|
||||
// thread itself, goes. The list and its tab's count both ask it, so the
|
||||
// count is the rows the tab shows (lurx98 on X: Codex 6, then 0 rows).
|
||||
func orphanSubagents(parents map[string]string) map[string]bool {
|
||||
gone := map[string]bool{}
|
||||
for {
|
||||
kept := make([]Managed, 0, len(out))
|
||||
dropped := false
|
||||
for _, m := range out {
|
||||
if m.Role == codexRoleSubagent && !ids[m.ParentSession] {
|
||||
delete(ids, m.ID)
|
||||
dropped = true
|
||||
for id, parent := range parents {
|
||||
if gone[id] || parent == "" {
|
||||
continue
|
||||
}
|
||||
kept = append(kept, m)
|
||||
if _, ok := parents[parent]; !ok || gone[parent] {
|
||||
gone[id] = true
|
||||
dropped = true
|
||||
}
|
||||
}
|
||||
out = kept
|
||||
if !dropped {
|
||||
return out
|
||||
return gone
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user