From 82f09e3248e72f621debdd6cfb15006fbf0151da Mon Sep 17 00:00:00 2001 From: Flandern1211 <163982805+Flandern1211@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:51:30 +0800 Subject: [PATCH] sessions: Codex's leftover review threads are no rows, and its one-session folders are one group MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Deleting a thread in Codex leaves its subagent rollouts behind: the guardian's review threads, titled by the prompt it asks ("The following is the Codex agent history whose request action you are assessing…"), and the title threads it opens. magpie reads every rollout, so each was a session of its own, and one whose thread was gone had nothing to hang under. On this computer 642 Codex sessions held 422 subagent threads, 86 of them with their parent thread's file gone (and 2 more under one of those): they filled folders of their own (Documents\Codex\2026-08-17\ shan, wang, wei…), and the bar counted 531 sessions made with another provider, 371 of them review threads no one ever opened. Codex Desktop also makes a folder for every chat started without a project (~/Documents/Codex//, its outputs/ and work/ in it, named from the prompt): 36 of them here were 36 folders of one session each. listAgentWith now drops a Codex subagent thread whose parent is not listed, to a fixed point, so a chain of them goes too; the agent's tab counts the rows it lists. The "Scratch sessions" group that commit e373adddf gave ZCode's draft folders now holds Codex's own per-session folders as well (that one, Documents\Codex\, a probe in a temp folder, worktrees, another app's hidden folder). The provider bar counts Codex's own threads only (role main or unknown): 531 became 160 here. And a gateway session no call of which was answered and which spent nothing is no row either (usage.GatewaySession.SpentNothing): the three empty rows under "Seen through the gateway" were Codex's failed title calls (kind thread_title, 400/499, 0 tokens), their ids ones no file of Codex's has. Rows: 642 Codex sessions to 554 (88 review threads gone), 422 subagent threads to 334; 36 folders (51 sessions) folded into Scratch sessions; 3 gateway rows to 0, so "Seen through the gateway" is empty here. Usage still counts every one of those calls, and nothing was deleted. Run: - go test ./internal/sessions -run 'TestCodexSubagentWhoseParentIsGone|TestZCode' -count=1: ok. - go test ./internal/gui -run 'Session|Gateway|Manage' -count=1: ok. - go build ./...; go vet ./internal/gui ./internal/usage ./internal/sessions; gofmt -l; git diff --check; node --check client.js: clean. - go test ./internal/sessions -count=1: the same failures as without this change (TestAgySessions, TestAgyRowOnly, TestAntigravityAppFolder, TestCCListingKeepsItsNames: path separators and allocation counts on this Windows box). - go test ./internal/usage -count=1: TestDesktopSessionAccountMetadata fails without this change too. Broken by hand: - without keptSubagents the 86 rows come back (TestCodexSubagentWhoseParentIsGoneIsNoRow fails); - hiding a gateway session on "spent nothing" alone breaks TestSessionsSameWithoutRows and TestGatewayConversationAPI: a call answered with no tokens is still a session, so SpentNothing also asks that none of its calls was answered; - counting subagent threads in the provider bar says 531 here, 371 of them review threads. Not changed: the review threads' calls are still counted by Usage and by the Sessions page's stats; their rollouts stay on disk (Deleting the parent does not delete them); the scratch grouping is worked out on the page (client.js), so Usage's folder filter still lists those folders by their paths. --- .../gui/assets/plugins/sessions/client.js | 12 +++- internal/gui/sessions.go | 5 +- internal/gui/sessions_gateway_empty_test.go | 65 +++++++++++++++++++ internal/gui/sessions_manage.go | 11 ++++ .../sessions/codex_orphan_subagents_test.go | 39 +++++++++++ internal/sessions/manage.go | 30 +++++++++ internal/usage/gateway_sessions.go | 19 +++++- 7 files changed, 176 insertions(+), 5 deletions(-) create mode 100644 internal/gui/sessions_gateway_empty_test.go create mode 100644 internal/sessions/codex_orphan_subagents_test.go diff --git a/internal/gui/assets/plugins/sessions/client.js b/internal/gui/assets/plugins/sessions/client.js index 0d5841326..b27c0ac69 100644 --- a/internal/gui/assets/plugins/sessions/client.js +++ b/internal/gui/assets/plugins/sessions/client.js @@ -106,8 +106,13 @@ magpie.plugin("sessions", (ctx) => { const DRAFTS = "\x00drafts"; const zcodeDraft = (s) => { const home = (data?.home || "").replace(/\\/g, "/").replace(/\/+$/, ""); - if (!home || s.agent !== "zcode" || !s.cwd) return false; + if (!s.cwd) return false; const c = s.cwd.replace(/\\/g, "/"); + // Codex Desktop makes ~/Documents/Codex// for every chat + // started without a project (its outputs/ and work/), and Codex also + // runs in temp folders and worktrees + if (s.agent === "codex") return /\/Documents\/Codex\/\d{4}-\d{2}-\d{2}\//i.test(c) || scratch(s.cwd); + if (!home || s.agent !== "zcode") return false; return c === home + "/.zcode/workspace" || c.startsWith(home + "/.zcode/workspace/"); }; const groupOf = (s) => zcodeDraft(s) ? DRAFTS : s.cwd || (s.gateway ? GW : ""); @@ -600,7 +605,10 @@ magpie.plugin("sessions", (ctx) => { function providerBar() { if (data.agent !== "codex") return null; - const hidden = data.sessions.filter(otherProvider); + // Codex's own threads only: its review and title threads (role + // subagent) never show in its history, so they are no conversations + // to move + const hidden = data.sessions.filter((s) => otherProvider(s) && s.role !== "subagent"); const undo = lastMove?.agent === data.agent && lastMove.moved.length ? lastMove : null; if (!hidden.length && !undo) return null; const bar = el("div", "row sm-provider"); diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index b62f9515c..574387099 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -97,8 +97,9 @@ func listedExternal(nativeKeys map[string]bool, n int) []sessions.ExternalSessio if len(ext) == n { return false } - // one a list leaves out (externalSessions) takes no room - if g.Agent != "" && g.ID != "" && !hidden(g.Agent, g.ID, g.Last) { + // one a list leaves out (externalSessions) takes no room; nor does + // one that spent nothing, with no file behind it (SpentNothing) + if g.Agent != "" && g.ID != "" && !hidden(g.Agent, g.ID, g.Last) && !g.SpentNothing() { ext = append(ext, gatewayListed(g, title)) } return true diff --git a/internal/gui/sessions_gateway_empty_test.go b/internal/gui/sessions_gateway_empty_test.go new file mode 100644 index 000000000..faaab0f7e --- /dev/null +++ b/internal/gui/sessions_gateway_empty_test.go @@ -0,0 +1,65 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "github.com/yetone/magpie/internal/sessions" + "github.com/yetone/magpie/internal/usage" +) + +// A gateway session that spent nothing at all — Codex's failed title and +// review calls carry an id no file of its own has — has nothing to show and +// is no row on either list (usage.GatewaySession.SpentNothing; flandern: +// three empty rows under "Seen through the gateway"). +func TestGatewaySessionThatSpentNothingIsNoRow(t *testing.T) { + sandboxHome(t) + now := time.Now().Add(-time.Hour).Truncate(time.Second) + 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: now, Agent: "codex", Provider: "fake", Model: "m", Session: "spent", Input: 10, Status: 200}) + enc.Encode(usage.Record{Time: now, Agent: "codex", Provider: "fake", Model: "m", Session: "empty", Status: 400}) + f.Close() + sessions.Reset() + t.Cleanup(sessions.Reset) + + mux := http.NewServeMux() + sessionRoutes(mux, folderOnly{}) + sessionManageRoutes(mux, folderOnly{}) + ids := func(path string) []string { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", path, nil)) + if w.Code != 200 { + t.Fatalf("%s: %d %s", path, w.Code, w.Body) + } + var out struct { + Sessions []sessions.Session `json:"sessions"` + } + if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + var got []string + for _, s := range out.Sessions { + got = append(got, s.ID) + } + return got + } + for _, path := range []string{"/api/sessions", "/api/sessions/manage?agent=codex"} { + got := ids(path) + if len(got) != 1 || got[0] != "spent" { + t.Errorf("%s lists %v, want the session that spent something only", path, got) + } + } +} diff --git a/internal/gui/sessions_manage.go b/internal/gui/sessions_manage.go index 44a87206d..9babb570e 100644 --- a/internal/gui/sessions_manage.go +++ b/internal/gui/sessions_manage.go @@ -8,6 +8,7 @@ import ( "net/http" "os" "runtime" + "slices" "sort" "strings" "sync" @@ -168,6 +169,9 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) { out.Home, _ = os.UserHomeDir() want := r.URL.Query().Get("agent") gateway := listedGateway(usage.GatewaySessions(time.Time{}, nil)) + // one that spent nothing, with no file of the agent's here either, + // has nothing to show (SpentNothing) + gateway = slices.DeleteFunc(gateway, usage.GatewaySession.SpentNothing) // a gateway session its agent keeps too is counted once; only the // agents with gateway sessions, and the one shown, are read (#2776) of := map[string]bool{} @@ -260,6 +264,13 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) { sort.SliceStable(out.Sessions, func(i, j int) bool { return out.Sessions[i].Last.After(out.Sessions[j].Last) }) + // the agent's tab counts the rows it lists: a Codex subagent + // thread whose parent is gone is no row (keptSubagents) + for i := range out.Agents { + if out.Agents[i].Agent == out.Agent { + out.Agents[i].Count = len(out.Sessions) + } + } } writeJSON(rw, out) }) diff --git a/internal/sessions/codex_orphan_subagents_test.go b/internal/sessions/codex_orphan_subagents_test.go new file mode 100644 index 000000000..ccc209cce --- /dev/null +++ b/internal/sessions/codex_orphan_subagents_test.go @@ -0,0 +1,39 @@ +package sessions + +import "testing" + +// Deleting a thread in Codex leaves its subagent rollouts behind: a review +// thread whose parent thread is gone was a row of its own, titled by the +// prompt Codex asked it (flandern). One whose parent is here is listed, to +// sit under it (keptSubagents). +func TestCodexSubagentWhoseParentIsGoneIsNoRow(t *testing.T) { + d := setupCalls(t) + spawn := func(parent string) string { + return `{"subagent":{"thread_spawn":{"parent_thread_id":"` + parent + `"}}}` + } + codexIdentityRollout(t, d.codex, "main", + codexIdentityMeta(t, "main", "main", `"vscode"`, "", ""), + codexIdentityUsage(1, "response-main", "main", "")) + codexIdentityRollout(t, d.codex, "child", + codexIdentityMeta(t, "child", "main", spawn("main"), "", ""), + codexIdentityUsage(2, "response-child", "main", "")) + codexIdentityRollout(t, d.codex, "orphan", + codexIdentityMeta(t, "orphan", "gone", spawn("gone"), "", ""), + codexIdentityUsage(3, "response-orphan", "gone", "")) + + got := map[string]Managed{} + for _, m := range ListAgent("codex") { + got[m.ID] = m + } + if _, ok := got["orphan"]; ok { + t.Error("the subagent thread of a deleted parent is listed as a session of its own") + } + main, ok := got["main"] + if !ok || main.Role != codexRoleMain { + t.Fatalf("the parent thread is not listed: %+v", main) + } + child, ok := got["child"] + if !ok || child.Role != codexRoleSubagent || child.ParentSession != "main" { + t.Fatalf("the subagent thread under a listed parent is not listed: %+v", child) + } +} diff --git a/internal/sessions/manage.go b/internal/sessions/manage.go index fb1e3f479..c2e2ff8e6 100644 --- a/internal/sessions/manage.go +++ b/internal/sessions/manage.go @@ -332,6 +332,7 @@ func listAgentWith(agent string, all []file, quick bool) []Managed { } if agent == "codex" { codexProviders(out, groups) + out = keptSubagents(out) } sort.SliceStable(out, func(i, j int) bool { if !out[i].Last.Equal(out[j].Last) { @@ -342,6 +343,35 @@ func listAgentWith(agent string, all []file, quick bool) []Managed { return out } +// keptSubagents drops a Codex subagent thread whose parent thread is not +// listed: deleting a thread in Codex leaves its review, title and other +// subagent rollouts behind, and each was a row of its own, titled by the +// prompt Codex asked it (the guardian's "The following is the Codex agent +// 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)) + for _, m := range out { + ids[m.ID] = true + } + 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 + continue + } + kept = append(kept, m) + } + out = kept + if !dropped { + return out + } + } +} + // listed fills in what assemble leaves out of a session nothing was said // in, as ListAgent lists it and Find finds it: how to resume it, and // whether its conversation can be read. diff --git a/internal/usage/gateway_sessions.go b/internal/usage/gateway_sessions.go index 20261a5f6..de7446c69 100644 --- a/internal/usage/gateway_sessions.go +++ b/internal/usage/gateway_sessions.go @@ -48,6 +48,20 @@ type GatewaySession struct { sessions.Tokens Cost float64 `json:"cost"` Unpriced int `json:"unpriced"` + // Answered: calls of it the provider answered (a 2xx or 3xx). A + // session with none that spent nothing is no conversation of the + // reader's (SpentNothing). + Answered int `json:"-"` +} + +// SpentNothing reports whether a gateway session has nothing to show: no +// call of it was answered and none spent a token. Codex's title and review +// threads do that when they fail — their ids are the thread's, no file of +// the agent's has them — and such a session was a row with nothing in it +// (flandern: three empty rows under "Seen through the gateway"). +func (s GatewaySession) SpentNothing() bool { + return s.Answered == 0 && s.Cost == 0 && + s.Input == 0 && s.Output == 0 && s.CacheRead == 0 && s.CacheWrite == 0 } type GatewayModel struct { @@ -129,7 +143,7 @@ func gatewaySessionFrom(s GatewaySession, date string) (GatewaySession, bool) { if i == 0 { return s, true } - w := GatewaySession{Agent: s.Agent, ID: s.ID, Models: []GatewayModel{}, Daily: s.Daily[i:]} + w := GatewaySession{Agent: s.Agent, ID: s.ID, Models: []GatewayModel{}, Daily: s.Daily[i:], Answered: s.Answered} models := map[string]int{} // index in w.Models, which grows for _, d := range w.Daily { if w.Start.IsZero() || d.first.Before(w.Start) { @@ -510,6 +524,9 @@ func countGateway(blocks []*rowChunk, since time.Time, nativeKeys map[string]boo s.CacheRead += r.CacheRead s.CacheWrite += r.CacheWrite s.CacheWrite1h += r.CacheWrite1h + if r.Status >= 200 && r.Status < 400 { + s.Answered++ + } m := acc.models[model] if m == nil { m = &GatewayModel{Model: model, Priced: true}