Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
sessions: the manage page reads its agents' files once, and only the agents it shows (#2776)
yetone38f6bee23e27
diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.mdindex 812e620dc..e26c7672b 100644--- a/docs/subsystems/gateway-sessions.md+++ b/docs/subsystems/gateway-sessions.md@@ -40,7 +40,12 @@ by its prompt. `passOnCaller` sends the mark on to a remote magpie besidethe session, and no vendor is sent either (`TestDshMarksSessionAndCompaction`).When the same identity is present in a native session, the native session wins-and the gateway projection is omitted. Gateway projections have no path,+and the gateway projection is omitted. On `/api/sessions/manage`, in its+counts as in its list, and on `/api/sessions/delete`, a native session is any+session file the agent keeps, one nothing was said in too, with no limit+(`sessions.NativeIDs`); one pass over the agents' files (`sessions.Manage`)+reads only the agent shown and the agents with gateway sessions (#2776).+Gateway projections have no path,resume command or terminal action: the agent's own files of them are not onthis computer. Their rows carry `gateway: true`; the Sessions page groups themunder "Seen through the gateway" rather than "No folder", and their size is thediff --git a/internal/gui/sessions_manage.go b/internal/gui/sessions_manage.goindex 7b6cd6b0e..f56017237 100644--- a/internal/gui/sessions_manage.go+++ b/internal/gui/sessions_manage.go@@ -130,55 +130,58 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) {Trash: trashJSON(looks), TrashDir: tilde(sessions.TrashDir()), Recording: settings.Load().GatewayConversations,Recorded: sessions.HasGatewayConversations()}want := r.URL.Query().Get("agent")- counts := map[string]*manageAgentJSON{}- for _, a := range sessions.Agents() {- j := manageAgentJSON{AgentCount: a, Name: a.Agent, Icon: "generic"}- if l := looks[a.Agent]; l != nil {- j.Name, j.Icon = l.SharedName(), l.Icon- }- counts[a.Agent] = &j- }gateway := listedGateway(usage.GatewaySessions(time.Time{}, nil))- nativeCounts := map[string]map[string]bool{}- for _, s := range sessions.List(sessions.All) {- if nativeCounts[s.Agent] == nil {- nativeCounts[s.Agent] = map[string]bool{}+ // 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{}+ for _, g := range gateway {+ of[g.Agent] = true+ }+ view := sessions.Manage(of, func(agents []sessions.AgentCount, native map[string]map[string]bool) string {+ counts := map[string]*manageAgentJSON{}+ for _, a := range agents {+ j := manageAgentJSON{AgentCount: a, Name: a.Agent, Icon: "generic"}+ if l := looks[a.Agent]; l != nil {+ j.Name, j.Icon = l.SharedName(), l.Icon+ }+ counts[a.Agent] = &j}- nativeCounts[s.Agent][s.ID] = true- }- for _, s := range gateway {- if nativeCounts[s.Agent][s.ID] {- continue+ for _, s := range gateway {+ if native[s.Agent][s.ID] {+ continue+ }+ j := counts[s.Agent]+ if j == nil {+ j = &manageAgentJSON{AgentCount: sessions.AgentCount{Agent: s.Agent}, Name: s.Agent, Icon: "generic"}+ if l := looks[s.Agent]; l != nil {+ j.Name, j.Icon = l.SharedName(), l.Icon+ }+ counts[s.Agent] = j+ }+ j.Count+++ // what magpie keeps of it can be deleted, whatever the agent+ j.Deletable = true}- j := counts[s.Agent]- if j == nil {- j = &manageAgentJSON{AgentCount: sessions.AgentCount{Agent: s.Agent}, Name: s.Agent, Icon: "generic"}- if l := looks[s.Agent]; l != nil {- j.Name, j.Icon = l.SharedName(), l.Icon+ for _, j := range counts {+ out.Agents = append(out.Agents, *j)+ }+ sort.Slice(out.Agents, func(i, j int) bool {+ if out.Agents[i].Count != out.Agents[j].Count {+ return out.Agents[i].Count > out.Agents[j].Count}- counts[s.Agent] = j+ return out.Agents[i].Agent < out.Agents[j].Agent+ })+ if _, ok := counts[want]; ok {+ return want}- j.Count++- // what magpie keeps of it can be deleted, whatever the agent- j.Deletable = true- }- for _, j := range counts {- out.Agents = append(out.Agents, *j)- }- sort.Slice(out.Agents, func(i, j int) bool {- if out.Agents[i].Count != out.Agents[j].Count {- return out.Agents[i].Count > out.Agents[j].Count+ if len(out.Agents) > 0 {+ return out.Agents[0].Agent}- return out.Agents[i].Agent < out.Agents[j].Agent+ return ""})- if _, ok := counts[want]; ok {- out.Agent = want- }- if out.Agent == "" && len(out.Agents) > 0 {- out.Agent = out.Agents[0].Agent- }+ out.Agent = view.Agentif out.Agent != "" {- list := sessions.ListAgent(out.Agent)+ list := view.Sessionsvar modelEffort map[string][]sessions.ModelEffortif out.Agent == "codex" {modelEffort = usage.CodexModelEffort(usage.All)@@ -243,12 +246,7 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) {return}// the gateway sessions as listed: those with no native session- native := map[string]bool{}- for _, s := range sessions.List(sessions.All) {- if s.Agent == in.Agent {- native[s.ID] = true- }- }+ native := sessions.NativeIDs(map[string]bool{in.Agent: true})[in.Agent]listed := map[string]usage.GatewaySession{}for _, g := range listedGateway(usage.GatewaySessions(time.Time{}, nil)) {if g.Agent == in.Agent && !native[g.ID] {diff --git a/internal/gui/sessions_manage_native_test.go b/internal/gui/sessions_manage_native_test.gonew file mode 100644index 000000000..5d2a76934--- /dev/null+++ b/internal/gui/sessions_manage_native_test.go@@ -0,0 +1,61 @@+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 whose agent keeps it too is one session, in the count+// as in the list, though nothing was said in the agent's own file: the+// count told them apart through List, which leaves such a file out (and+// stops at 5000), while the list kept every one (#2776).+func TestManageCountsAGatewaySessionTheAgentKeepsOnce(t *testing.T) {+ h := sandboxHome(t)+ sessions.Reset()+ t.Cleanup(sessions.Reset)+ const id = "3c9e1f2a-5b6d-4e7f-8a9b-0c1d2e3f4a5b"+ dir := filepath.Join(h, ".claude", "projects", "-work-app")+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ line := `{"type":"file-history-snapshot","messageId":"m","snapshot":{"messageId":"m","trackedFileBackups":{},"timestamp":"2026-09-19T08:00:00.000Z"},"isSnapshotUpdate":false}` + "\n"+ if err := os.WriteFile(filepath.Join(dir, id+".jsonl"), []byte(line), 0o644); err != nil {+ t.Fatal(err)+ }+ usage.Append(usage.Record{Time: time.Now().Add(-2 * time.Hour), Agent: "claude", Session: id, Provider: "deepseek", Model: "deepseek-flash", Input: 40, Output: 9, Status: 200})+ mux := http.NewServeMux()+ sessionManageRoutes(mux, folderOnly{})+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/sessions/manage?agent=claude", nil))+ if w.Code != 200 {+ t.Fatalf("%d %s", w.Code, w.Body)+ }+ var m struct {+ Agents []struct {+ Agent string `json:"agent"`+ Count int `json:"count"`+ } `json:"agents"`+ Agent string `json:"agent"`+ Sessions []struct {+ ID string `json:"id"`+ Gateway bool `json:"gateway"`+ } `json:"sessions"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil {+ t.Fatal(err)+ }+ if m.Agent != "claude" || len(m.Sessions) != 1 || m.Sessions[0].ID != id || m.Sessions[0].Gateway {+ t.Fatalf("listed %q: %+v", m.Agent, m.Sessions)+ }+ if len(m.Agents) != 1 || m.Agents[0].Count != 1 {+ t.Fatalf("one session listed, counted %+v", m.Agents)+ }+}diff --git a/internal/sessions/manage.go b/internal/sessions/manage.goindex 46c3bc6fc..da52f5cd2 100644--- a/internal/sessions/manage.go+++ b/internal/sessions/manage.go@@ -78,8 +78,12 @@ func Agents() []AgentCount {mu.Lock()defer mu.Unlock()defer closeDBs()+ return agentCounts(allFiles())+}++func agentCounts(all []file) []AgentCount {n := map[string]map[string]bool{}- for _, f := range allFiles() {+ for _, f := range all {if n[f.agent] == nil {n[f.agent] = map[string]bool{}}@@ -101,6 +105,47 @@ func Agents() []AgentCount {// ListAgent is every session of one agent, the most recently active first,// with no limit; one nothing was said in is listed too, to be cleared away.func ListAgent(agent string) []Managed {+ dbReadMu.Lock()+ defer dbReadMu.Unlock()+ mu.Lock()+ defer mu.Unlock()+ loadCache()+ defer closeDBs()+ return listAgent(agent, allFiles())+}++// NativeIDs are the ids of every session the agents named keep themselves,+// by agent: one nothing was said in too, as ListAgent lists it. It tells a+// gateway session an agent keeps from one only magpie saw. Only the named+// agents' files are looked at, and of those only the ones whose session id+// is inside the file are read when they changed.+func NativeIDs(agents map[string]bool) map[string]map[string]bool {+ dbReadMu.Lock()+ defer dbReadMu.Unlock()+ mu.Lock()+ defer mu.Unlock()+ loadCache()+ defer closeDBs()+ return nativeIDs(agents, allFiles())+}++// ManageView is the session management page, read in one pass over every+// agent's files: the agents with sessions, the ids of the sessions of those+// asked for (as NativeIDs), and the agent shown with its sessions (as+// ListAgent).+type ManageView struct {+ Agents []AgentCount+ Native map[string]map[string]bool+ Agent string+ Sessions []Managed+}++// Manage reads the management page. pick, given the counts and the native+// ids of the agents in native, names the agent to list ("" for none); it+// runs under the sessions lock and must not call back into this package.+// Only native's agents and the one picked are read: a change to another+// agent's sessions waits for a page that shows it (#2776).+func Manage(native map[string]bool, pick func([]AgentCount, map[string]map[string]bool) string) ManageView {dbReadMu.Lock()defer dbReadMu.Unlock()mu.Lock()@@ -108,6 +153,48 @@ func ListAgent(agent string) []Managed {loadCache()defer closeDBs()all := allFiles()+ v := ManageView{Agents: agentCounts(all), Native: nativeIDs(native, all)}+ v.Agent = pick(v.Agents, v.Native)+ if v.Agent != "" {+ v.Sessions = listAgent(v.Agent, all)+ }+ return v+}++// idInFile says which agents' session ids are read from inside the+// session's file, not taken from its name (as assemble does).+func idInFile(agent string) bool {+ switch agent {+ case "codex", "pi", "omp", "dsh", "grok", "droid":+ return true+ }+ return false+}++func nativeIDs(agents map[string]bool, all []file) map[string]map[string]bool {+ groups := map[string][]file{}+ var want []file+ for _, f := range all {+ if !agents[f.agent] {+ continue+ }+ groups[f.key] = append(groups[f.key], f)+ if idInFile(f.agent) {+ want = append(want, f)+ }+ }+ refresh(want, all)+ out := map[string]map[string]bool{}+ for a := range agents {+ out[a] = map[string]bool{}+ }+ for _, fs := range groups {+ out[fs[0].agent][sessionID(fs)] = true+ }+ return out+}++func listAgent(agent string, all []file) []Managed {groups := map[string][]file{}var mine []filefor _, f := range all {diff --git a/internal/sessions/manage_read_test.go b/internal/sessions/manage_read_test.gonew file mode 100644index 000000000..076ed4a77--- /dev/null+++ b/internal/sessions/manage_read_test.go@@ -0,0 +1,77 @@+package sessions++import (+ "os"+ "path/filepath"+ "sort"+ "testing"+ "time"+)++// The management page of one agent reads that agent's changed files, and+// those of the agents whose gateway sessions it tells apart, not every+// agent's (#2776): it read them all to build that set, through List(All).+func TestManageReadsOnlyTheAgentsItShows(t *testing.T) {+ _, codex := setup(t)+ claude := func([]AgentCount, map[string]map[string]bool) string { return "claude" }+ Manage(map[string]bool{}, claude)+ now := time.Now()+ err := filepath.WalkDir(filepath.Join(codex, "sessions"), func(p string, d os.DirEntry, err error) error {+ if err == nil && !d.IsDir() {+ now = now.Add(time.Second)+ return os.Chtimes(p, now, now)+ }+ return err+ })+ if err != nil {+ t.Fatal(err)+ }+ parsed := 0+ parseHook = func() { parsed++ }+ t.Cleanup(func() { parseHook = nil })++ v := Manage(map[string]bool{}, claude)+ if parsed != 0 {+ t.Fatalf("Codex's files changed and Claude Code's page read %d of them", parsed)+ }+ if v.Agent != "claude" || len(v.Sessions) == 0 {+ t.Fatalf("listed %q with %d sessions", v.Agent, len(v.Sessions))+ }+ counted := false+ for _, a := range v.Agents {+ counted = counted || a.Agent == "codex" && a.Count == 1+ }+ if !counted {+ t.Fatalf("codex not counted: %+v", v.Agents)+ }++ // asked for Codex's ids: its changed files are read, as the id is in them+ v = Manage(map[string]bool{"codex": true, "claude": true}, claude)+ if parsed == 0 {+ t.Fatal("Codex's ids were asked for and its changed files not read")+ }+ if !v.Native["codex"]["01a0bdc9-b5fd-7e63-9658-68bc8dce5ecd"] {+ t.Fatalf("codex ids %v", v.Native["codex"])+ }+ // the same ids as the agent's list: one nothing was said in too+ var listed, native []string+ for _, m := range v.Sessions {+ listed = append(listed, m.ID)+ }+ for id := range v.Native["claude"] {+ native = append(native, id)+ }+ sort.Strings(listed)+ sort.Strings(native)+ if len(listed) < 2 || len(listed) != len(native) {+ t.Fatalf("claude list %v, native ids %v", listed, native)+ }+ for i := range listed {+ if listed[i] != native[i] {+ t.Fatalf("claude list %v, native ids %v", listed, native)+ }+ }+ if got := NativeIDs(map[string]bool{"codex": true}); len(got) != 1 || len(got["codex"]) != 1 {+ t.Fatalf("NativeIDs: %v", got)+ }+}diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.goindex 474dd2461..e59b449c5 100644--- a/internal/sessions/sessions.go+++ b/internal/sessions/sessions.go@@ -1041,20 +1041,38 @@ func List(limit int) []Session {return out}-// assemble puts a session together from its files' parses.-func assemble(fs []file, price func(string) *catalog.Price) (Session, bool) {- // the session's own file first; for Codex the earliest segment+// sortSessionFiles puts a session's own file first; for Codex the earliest+// segment.+func sortSessionFiles(fs []file) {sort.SliceStable(fs, func(i, j int) bool {if fs[i].main != fs[j].main {return fs[i].main}return filepath.Base(fs[i].path) < filepath.Base(fs[j].path)})+}++// sessionID is a session's id: its key's, or for an agent that writes it+// inside the file (idInFile), what its own file's parse read.+func sessionID(fs []file) string {+ sortSessionFiles(fs)+ id := strings.TrimPrefix(fs[0].key, fs[0].agent+":")+ if idInFile(fs[0].agent) && fs[0].main {+ if st := cache[fs[0].path]; st != nil && st.ID != "" {+ id = st.ID+ }+ }+ return id+}++// assemble puts a session together from its files' parses.+func assemble(fs []file, price func(string) *catalog.Price) (Session, bool) {+ sortSessionFiles(fs)s := Session{Agent: fs[0].agent, Path: fs[0].path, Models: []Model{}, WSL: fs[0].wsl}for _, f := range fs {s.ReadOnly = s.ReadOnly || f.readOnly}- s.ID = strings.TrimPrefix(fs[0].key, s.Agent+":")+ s.ID = sessionID(fs)var custom, named, first stringmodels := map[string]*Model{}for _, f := range fs {@@ -1078,9 +1096,6 @@ func assemble(fs []file, price func(string) *catalog.Price) (Session, bool) {if first == "" {first = st.First}- if (s.Agent == "codex" || s.Agent == "pi" || s.Agent == "omp" || s.Agent == "dsh" || s.Agent == "grok" || s.Agent == "droid") && st.ID != "" && f.path == fs[0].path {- s.ID = st.ID- }}if s.Agent == "codex" && st.CodexNickname != "" {s.Nickname = st.CodexNickname