sessions: the Sessions poll makes its rows as the gateway's sessions merge

/api/sessions copied every one of ~17k sessions into MergeExternal's
merged list, and MergeExternal made a set of every native session's
keys again to leave natives out of the gateway's, though
GatewaySessions had already left them out by the same keys. The rows
were then copied from that list.

EachMerged hands each session to the caller in MergeExternal's order
(newest first, a native before an external of the same moment) from
the list as List gives it and the gateway's sessions sorted alone, so
the handler copies each session once, into its row. MergeExternal
keeps its own copy and dedupe for its other callers; both share
externalSessions.

TestEachMergedListsWhatMergeExternalDid: same rows, field for field, as
MergeExternal for a sorted list, an unsorted one (sorted in a copy, the
caller's left as it was) and none; with and without externals; ties;
stops at false. TestEachMergedCopiesNoList: 5000 natives merge in under
a twentieth of the list's bytes. Broken by hand, each red:
  EachMerged over MergeExternal's list: 5,437,624 bytes for a
    2,480,000-byte list
  EachMerged making the native key set again: 394,352 bytes

Measured on mote's build against the real ~17k sessions (sandbox HOME,
APFS clones), 30 polls, against v0.1.2554's build:
  heap diff alloc_space   726 MB -> 701 MB (MergeExternal's 107 MB
                          gone; externalSessions 51 MB left, the
                          gateway's own sessions)
  CPU over 30 polls       4.44s -> 4.24s
  /api/sessions median    73ms -> 71ms

Run on mote: go vet ./internal/sessions ./internal/gui ok;
go test ./internal/sessions ok; ./internal/gui red only in
TestSettingsSaveKeepsWhatItDoesNotSend (#4739) and
TestMainWindowCorners (#3949), both red on origin/main 788057340.
Not run: the full suite, the GUI suite (the answer's rows are the same).
Then rebased onto 1e6a27d4f (gui: an icon's image URL; none of the four commits touch sessions or the Sessions handler); not rerun.
Then rebased onto 994cd4fb6 (gui: Rex switches to the tab magpie opens, through the app's); not rerun.
This commit is contained in:
yetone
2026-11-01 14:39:38 +08:00
parent 994cd4fb68
commit f506638690
3 changed files with 165 additions and 31 deletions
+23 -19
View File
@@ -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"`
+88
View File
@@ -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
}
+54 -12
View File
@@ -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
}