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}