diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index 30d66cd35..e5bd02180 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -122,40 +122,44 @@ func sessionRoutes(mux *http.ServeMux, w Windows) { for _, g := range gateway { ext = append(ext, gatewayListed(g, title)) } - list = sessions.MergeExternal(list, ext) - if len(list) > n { - list = list[:n] - } - var modelEffort map[string][]sessions.ModelEffort - for _, s := range list { - if s.Agent == "codex" { - modelEffort = usage.CodexModelEffort(usage.All) - break + // made to size: up to sessions.All rows, grown by append each poll + // was copied through every size on the way, ~140 MB of eight (#2278). + // The rows are made from the list and the gateway's sessions as + // they merge, not from a merged copy of the list. + out.Sessions = make([]sessionJSON, 0, min(n, len(list)+len(ext))) + codex := false + sessions.EachMerged(list, ext, func(s *sessions.Session) bool { + if len(out.Sessions) == n { + return false } - } - for i := range list { - addCodexModelEffort(&list[i], modelEffort) + codex = codex || s.Agent == "codex" + out.Sessions = append(out.Sessions, sessionJSON{Session: *s}) + return true + }) + var modelEffort map[string][]sessions.ModelEffort + if codex { + modelEffort = usage.CodexModelEffort(usage.All) } since := time.Now() - for _, s := range list { + for i := range out.Sessions { + s := &out.Sessions[i].Session + addCodexModelEffort(s, modelEffort) if !s.Start.IsZero() && s.Start.Before(since) { since = s.Start } } vias := usage.Vias(since.Add(-time.Minute)) - // made to size: up to sessions.All rows, grown by append each poll - // was copied through every size on the way, ~140 MB of eight (#2278) - out.Sessions = make([]sessionJSON, 0, len(list)) - for _, s := range list { + for i := range out.Sessions { + j := &out.Sessions[i] + s := j.Session // drawn as the agent it ran in: Claude Desktop's Code tab's // sessions are in Claude Code's folder (Session.App) - j := sessionJSON{Session: s, Name: s.Agent, Icon: "generic", Via: viaOf(vias, s)} + j.Name, j.Icon, j.Via = s.Agent, "generic", viaOf(vias, s) if a := agents[cmp.Or(s.App, s.Agent)]; a != nil { j.Name, j.Icon = a.SharedName(), a.Icon } j.Name = wslName(j.Name, s) j.Path = tilde(j.Path) - out.Sessions = append(out.Sessions, j) } writeJSONRows(rw, r, "sessions", out.Sessions, struct { Terminal bool `json:"terminal"` diff --git a/internal/sessions/each_merged_test.go b/internal/sessions/each_merged_test.go new file mode 100644 index 000000000..16a4ae667 --- /dev/null +++ b/internal/sessions/each_merged_test.go @@ -0,0 +1,88 @@ +package sessions + +import ( + "fmt" + "reflect" + "runtime" + "testing" + "time" + "unsafe" +) + +// TestEachMergedListsWhatMergeExternalDid: the Sessions page makes its rows +// as the list and the gateway's sessions merge, in MergeExternal's order: +// newest first, a native before an external of the same moment, and a list +// not newest first sorted before. Its external are the gateway's sessions +// native doesn't hold (GatewaySessions), so a native's id isn't among them. +func TestEachMergedListsWhatMergeExternalDid(t *testing.T) { + at := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC) + native := []Session{ + {Agent: "claude", ID: "c1", Last: at.Add(5 * time.Minute), Copies: []string{"c1-copy"}}, + {Agent: "codex", ID: "x1", Last: at.Add(3 * time.Minute)}, + {Agent: "claude", ID: "c2", Last: at.Add(3 * time.Minute)}, + {Agent: "pi", ID: "p1", Last: at}, + } + external := []ExternalSession{ + {Agent: "opencode", ID: "g-old", Last: at.Add(-time.Hour)}, + {Agent: "opencode", ID: "g-tie", Last: at.Add(3 * time.Minute)}, + {Agent: "opencode", ID: "g-new", Last: at.Add(time.Hour)}, + {Agent: "", ID: "nobody", Last: at}, + {Agent: "opencode", ID: "g-tie2", Last: at.Add(3 * time.Minute)}, + } + unsorted := []Session{native[2], native[0], native[3], native[1]} + for _, in := range [][]Session{native, unsorted, nil} { + for _, ext := range [][]ExternalSession{external, nil} { + want := MergeExternal(in, ext) + var got []Session + EachMerged(in, ext, func(s *Session) bool { got = append(got, *s); return true }) + if !reflect.DeepEqual(mergedIDs(got), mergedIDs(want)) || len(got) != len(want) { + t.Fatalf("merged\n got %v\nwant %v", mergedIDs(got), mergedIDs(want)) + } + for i := range want { + if !reflect.DeepEqual(got[i], want[i]) { + t.Fatalf("row %d\n got %+v\nwant %+v", i, got[i], want[i]) + } + } + if len(want) > 2 { + n := 0 + EachMerged(in, ext, func(*Session) bool { n++; return n < 2 }) + if n != 2 { + t.Fatalf("went on after false: %d calls", n) + } + } + } + } + if fmt.Sprint(mergedIDs(unsorted)) != "[claude:c2 claude:c1 pi:p1 codex:x1]" { + t.Fatalf("the caller's list was sorted in place: %v", mergedIDs(unsorted)) + } +} + +// TestEachMergedCopiesNoList: a poll's merge was a copy of every session. +func TestEachMergedCopiesNoList(t *testing.T) { + native := make([]Session, 5000) + at := time.Now() + for i := range native { + native[i] = Session{Agent: "claude", ID: fmt.Sprint("s", i), Last: at.Add(-time.Duration(i) * time.Second)} + } + ext := []ExternalSession{{Agent: "opencode", ID: "g", Last: at.Add(-time.Hour)}} + list := uint64(len(native)) * uint64(unsafe.Sizeof(Session{})) + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + n := 0 + EachMerged(native, ext, func(*Session) bool { n++; return true }) + runtime.ReadMemStats(&after) + if n != len(native)+1 { + t.Fatalf("%d sessions, want %d", n, len(native)+1) + } + if got := after.TotalAlloc - before.TotalAlloc; got > list/20 { + t.Fatalf("merging a %d-byte list allocated %d bytes", list, got) + } +} + +func mergedIDs(list []Session) []string { + var out []string + for _, s := range list { + out = append(out, s.Agent+":"+s.ID) + } + return out +} diff --git a/internal/sessions/external.go b/internal/sessions/external.go index 40a1cea8a..526ddbab7 100644 --- a/internal/sessions/external.go +++ b/internal/sessions/external.go @@ -33,7 +33,48 @@ type ExternalSession struct { // read-only (no file of the agent's to resume or open) with a gateway transcript // reader; magpie's own record of one is deleted by DeleteGateway. func MergeExternal(native []Session, external []ExternalSession) []Session { - names := desktopExternalTitles(external) + added := externalAdded(native, external) + out := make([]Session, len(native), len(native)+len(added)) + copy(out, native) + out = append(out, added...) + sort.SliceStable(out, func(i, j int) bool { return out[i].Last.After(out[j].Last) }) + return out +} + +// EachMerged calls each with every session MergeExternal(native, external) +// lists, in its order, until each returns false, without making that list: +// the Sessions page's poll copied all ~17k sessions into it, then into its +// own rows. external holds none of native's sessions, as GatewaySessions +// gives them for native's GatewayKeys: the set of native's keys made again +// to look was ~2 MB a poll. native is written by neither; when it isn't +// newest first, as List gives it, it is sorted in a copy first. +func EachMerged(native []Session, external []ExternalSession, each func(*Session) bool) { + newest := func(a, b Session) int { return b.Last.Compare(a.Last) } + if !slices.IsSortedFunc(native, newest) { + native = slices.Clone(native) + slices.SortStableFunc(native, newest) + } + added := externalSessions(external) + slices.SortStableFunc(added, newest) + // a merge of the two, natives first among equals, as SliceStable over + // native then added gives + i, j := 0, 0 + for i < len(native) || j < len(added) { + var s *Session + if j < len(added) && (i == len(native) || added[j].Last.After(native[i].Last)) { + s, j = &added[j], j+1 + } else { + s, i = &native[i], i+1 + } + if !each(s) { + return + } + } +} + +// externalAdded are the external sessions MergeExternal adds to native, in +// external's order. +func externalAdded(native []Session, external []ExternalSession) []Session { // keyed by the pair, not "agent|id": a string made for each of ~5000 // sessions on each of a poll's listings, and the set and the list grown // an append at a time, were ~200 MB in 80s of polls (#2278) @@ -55,20 +96,22 @@ func MergeExternal(native []Session, external []ExternalSession) []Session { seen[agentID{s.Agent, id}] = struct{}{} } } - added := func(e ExternalSession) bool { - _, dup := seen[agentID{e.Agent, e.ID}] - return e.Agent != "" && e.ID != "" && !dup - } - n := len(native) + var not []ExternalSession for _, e := range external { - if added(e) { - n++ + if _, dup := seen[agentID{e.Agent, e.ID}]; !dup { + not = append(not, e) } } - out := make([]Session, len(native), n) - copy(out, native) + return externalSessions(not) +} + +// externalSessions are external's sessions as a list shows them, those +// with an agent and an id, in external's order. +func externalSessions(external []ExternalSession) []Session { + names := desktopExternalTitles(external) + var out []Session for _, e := range external { - if !added(e) { + if e.Agent == "" || e.ID == "" { continue } s := Session{ReadOnly: true, Gateway: true, Transcript: true, Agent: e.Agent, ID: e.ID, Title: cmp.Or(names[e.Agent+"|"+e.ID], e.Title, e.ID), Start: e.Start, Last: e.Last, Models: []Model{}, Unpriced: e.Unpriced} @@ -79,7 +122,6 @@ func MergeExternal(native []Session, external []ExternalSession) []Session { s.Cost = e.Cost out = append(out, s) } - sort.SliceStable(out, func(i, j int) bool { return out[i].Last.After(out[j].Last) }) return out }