sessions: a poll while a session grows makes only the rows it shows
VeryBTC on X (tweet 2117104179454091396) reported RSS that rises and
stays up while the window is open and a long-context session is active.
In that case every Sessions poll sees a changed file and rebuilds the
list. That rebuild copied every gateway-only session three times
(GatewaySessions, listedGateway, gatewayListed) and made each one a
Session row before EachMerged stopped at its 5000-row limit. It also
made every Claude Code file's path and key again.
- usage.EachGatewaySession walks the projection without copying it.
gui's listedExternal stops at the list's limit and skips hidden
sessions and sessions without an agent or id, as listedGateway did.
- sessions.EachMerged sorts indexes and makes a row only when the merge
reaches it. The order is unchanged: newest first, stable on ties.
- listCCFiles reuses the last listing's path and key strings while a
folder lists the same names. One file new or gone is stepped over.
This holds ~32 B per file (~480 KB at 15k files), and the strings are
shared with the listing it already held.
- page_memory.go's ~330 MB comment now has current numbers.
gateway-sessions.md describes the lazy rows.
Per poll, on mote (go test probe through the real /api/sessions
handler, TotalAlloc):
15k sessions x 10 turns, 400k ledger rows
after a session file grows 150.6 MB, 201 ms -> 109.9 MB, 170 ms
unchanged (warm) 17.2 MB -> 12.0 MB
3k sessions x 40 turns, 150k rows (no gateway-only rows past the cap)
after a session file grows 31.3 MB -> 29.6 MB
unchanged (warm) 4.5 MB -> 3.4 MB
/api/usage is unchanged at 0.4 MB.
Tests:
- TestSessionsListMakesOnlyTheGatewayRowsItShows (gui) uses 3 natives,
6000 gateway sessions in tied pairs, one hidden and one carrying a
native's id. At limits 5, 40 and 6010, and with no limit, the rows
equal the old pipeline's (listedGateway + gatewayListed +
MergeExternal) after the JSON round trip. A grown native comes first
with its new Last. The poll's allocation stays under 6000 rows' size.
- TestEachMergedMakesOnlyTheRowsItReaches (sessions): 15000 externals
and 20 rows give MergeExternal's first 20, with allocation under a
tenth of the rows.
- TestCCListingKeepsItsNames (sessions): a second listing of 3000 files
is equal to the first, in at most 3n mallocs. A file added, files
removed, and a folder gone with another new each list as a fresh
listing does. Another agent's keys keep their own prefix.
Broken by hand, each red:
- EachMerged building every row first: 8.8 MB, the sessions test fails.
- The GUI handler back on the listedGateway(GatewaySessions) loop, with
the lazy merge kept: 13.7 MB, the gui test fails.
- The gui test on origin/main's code: 23 MB, fails.
- The ccNames reuse turned off: 12197 mallocs, the listing test fails.
Run on mote (mote-run) at 73a1b8769, rebased on origin/main 07f4d46c5:
gofmt -l internal (empty), go vet ./..., GOOS=linux go vet -tags nogui
./..., GOOS=windows go vet ./... all clean. go test -count=1 -timeout
45m ./internal/sessions ./internal/usage ./internal/gui: sessions ok,
usage ok. gui is ok except TestMainWindowCorners/macOS_26_SDK, which is
#3949 (red on mote's macOS 27, an AppKit title bar test this change
doesn't reach). It was red the same way in the run before the rebase.
Not tried:
- A real app window with RSS measured over time. The numbers are
allocation per poll from a probe.
- The rest of a changed poll: statsKept re-sums every session (~26 MB at
15k), listing (~24 MB) and byKey (~9 MB). None was a cheap, safe
change.
- Windows and Linux test runs (vet only).
- A gateway title store in the fixture. GatewayTitler's ReadDirs now run
only for the rows shown.
This commit is contained in:
@@ -106,7 +106,15 @@ is some. The overview's top summaries (`MergeExternalStats`) carry
|
||||
where a folder would be, with "(prompt not recorded)" when no text was kept,
|
||||
so it doesn't read as a native session with an empty prompt (#2285: a Pi
|
||||
subagent whose session file is in a temp folder). Verification:
|
||||
`TestTopSessionsMarkWhatOnlyTheGatewaySaw`, `sessions-overview.test.cjs`. Their
|
||||
`TestTopSessionsMarkWhatOnlyTheGatewaySaw`, `sessions-overview.test.cjs`.
|
||||
`/api/sessions` makes a row only of the gateway sessions its limit can
|
||||
show: `usage.EachGatewaySession` walks the projection newest first without
|
||||
a copy, `listedExternal` stops at the limit, and `sessions.EachMerged`
|
||||
makes each row when the merge reaches it. Every one of ~10k gateway
|
||||
sessions past the natives' cap was copied three times and made a row on
|
||||
each poll while a session grew. Verification:
|
||||
`TestSessionsListMakesOnlyTheGatewayRowsItShows`,
|
||||
`TestEachMergedMakesOnlyTheRowsItReaches`. Their
|
||||
models, token totals, start/last timestamps and effective prices come from the
|
||||
same usage records used by Usage and stats endpoints.
|
||||
|
||||
|
||||
@@ -9,8 +9,11 @@ import (
|
||||
)
|
||||
|
||||
// A Sessions or Usage page's poll reads every session file's listing and
|
||||
// the request ledger again: ~330 MB allocated every 15 s to keep ~105 MB.
|
||||
// Go keeps the pages that freed, and its scavenger hands them back only
|
||||
// the request ledger again. That was ~330 MB allocated every 15 s to keep
|
||||
// ~105 MB; over 15k sessions and 400k calls (11-02) an unchanged poll is
|
||||
// ~12 MB of Sessions' and ~0.4 MB of Usage's, and one while a session
|
||||
// grows, which re-sums every session's stats, ~110 MB. Go keeps the pages
|
||||
// that freed, and its scavenger hands them back only
|
||||
// slowly, never while the next collection's goal covers them, so an open
|
||||
// window sat at ~340 MB in Activity Monitor between polls. The gateway
|
||||
// hands its requests' pages back once it rests (#3472), but the window's
|
||||
|
||||
@@ -80,6 +80,31 @@ func gatewayListed(g usage.GatewaySession, title func(agent, id string) string)
|
||||
return e
|
||||
}
|
||||
|
||||
// listedExternal are the gateway's sessions a list of n rows can show:
|
||||
// those native doesn't hold (nativeKeys), as listedGateway keeps them and
|
||||
// gatewayListed makes them, newest first as EachGatewaySession gives them,
|
||||
// and no more than n, as a merge with the natives shows the newest n at
|
||||
// most. Each of ~10k gateway sessions past the natives' cap was copied
|
||||
// three times on every poll while a session grew, ~20 MB of a poll's
|
||||
// ~150 MB, and each was looked for in the store of what was asked
|
||||
// (GatewayTitler).
|
||||
func listedExternal(nativeKeys map[string]bool, n int) []sessions.ExternalSession {
|
||||
hidden := sessions.GatewayHidden()
|
||||
title := sessions.GatewayTitler()
|
||||
var ext []sessions.ExternalSession
|
||||
usage.EachGatewaySession(nativeKeys, func(g usage.GatewaySession) bool {
|
||||
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) {
|
||||
ext = append(ext, gatewayListed(g, title))
|
||||
}
|
||||
return true
|
||||
})
|
||||
return ext
|
||||
}
|
||||
|
||||
func gatewaySession(g usage.GatewaySession) sessions.Session {
|
||||
return sessions.MergeExternal(nil, []sessions.ExternalSession{gatewayListed(g, sessions.GatewayTitle)})[0]
|
||||
}
|
||||
@@ -140,12 +165,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) {
|
||||
nativeKeys[k] = true
|
||||
}
|
||||
}
|
||||
gateway := listedGateway(usage.GatewaySessions(time.Time{}, nativeKeys))
|
||||
ext := make([]sessions.ExternalSession, 0, len(gateway))
|
||||
title := sessions.GatewayTitler()
|
||||
for _, g := range gateway {
|
||||
ext = append(ext, gatewayListed(g, title))
|
||||
}
|
||||
ext := listedExternal(nativeKeys, n)
|
||||
// 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
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// TestSessionsListMakesOnlyTheGatewayRowsItShows: while a session grew,
|
||||
// each Sessions poll copied every gateway session the natives don't hold
|
||||
// three times and made each a row, ~60 MB of a poll's ~150 MB over ~10k
|
||||
// of them, though the list shows its limit at most. The rows are still
|
||||
// the ones the whole merge gave, in its order, a hidden one left out and
|
||||
// a native's id never doubled; and a grown session file is read.
|
||||
func TestSessionsListMakesOnlyTheGatewayRowsItShows(t *testing.T) {
|
||||
h := sandboxHome(t)
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(h, ".claude"))
|
||||
proj := filepath.Join(h, ".claude", "projects", "-work")
|
||||
if err := os.MkdirAll(proj, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().Add(-2 * time.Hour).Truncate(time.Second)
|
||||
line := func(id string, at time.Time, text string) string {
|
||||
ts := at.UTC().Format("2006-01-02T15:04:05.000Z")
|
||||
return `{"parentUuid":null,"isSidechain":false,"type":"user","message":{"role":"user","content":"` + text + `"},"uuid":"u` + text + `","timestamp":"` + ts + `","cwd":"/work","sessionId":"` + id + `"}` + "\n" +
|
||||
`{"parentUuid":"u` + text + `","isSidechain":false,"message":{"model":"claude-sonnet-5","id":"msg_` + id + text + `","type":"message","role":"assistant","content":[{"type":"text","text":"done"}],"usage":{"input_tokens":10,"output_tokens":2}},"requestId":"req_` + text + `","type":"assistant","uuid":"a` + text + `","timestamp":"` + ts + `","cwd":"/work","sessionId":"` + id + `"}` + "\n"
|
||||
}
|
||||
for i, mins := range []int{1, 7, 30} {
|
||||
id := fmt.Sprintf("%08d-1111-2222-3333-444444444444", i)
|
||||
at := now.Add(-time.Duration(mins) * time.Minute)
|
||||
p := filepath.Join(proj, id+".jsonl")
|
||||
if err := os.WriteFile(p, []byte(line(id, at, "hi")), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.Chtimes(p, at, at)
|
||||
}
|
||||
const gateway = 6000
|
||||
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)
|
||||
for i := range gateway {
|
||||
// pairs at one moment, so a tie's order is the merge's to keep
|
||||
at := now.Add(-time.Duration(i/2) * time.Minute)
|
||||
enc.Encode(usage.Record{Time: at, Agent: "opencode", Provider: "fake", Model: "m", Session: fmt.Sprint("g", i), Input: 10, Status: 200})
|
||||
}
|
||||
// a native's own id, which is the native's row only
|
||||
enc.Encode(usage.Record{Time: now, Agent: "claude", Provider: "fake", Model: "m", Session: "00000001-1111-2222-3333-444444444444", Input: 10, Status: 200})
|
||||
f.Close()
|
||||
sessions.Reset()
|
||||
t.Cleanup(sessions.Reset)
|
||||
if _, err := sessions.DeleteGateway("opencode", "g3", "", now.Add(-time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
sessionRoutes(mux, folderOnly{})
|
||||
ask := func(path string) ([]sessions.Session, uint64) {
|
||||
t.Helper()
|
||||
var before, after runtime.MemStats
|
||||
runtime.ReadMemStats(&before)
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
|
||||
runtime.ReadMemStats(&after)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
|
||||
}
|
||||
var out struct{ Sessions []sessions.Session }
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out.Sessions, after.TotalAlloc - before.TotalAlloc
|
||||
}
|
||||
// what the whole merge gives, as the list made it before
|
||||
want := func(n int) []sessions.Session {
|
||||
list := sessions.List(sessions.All)
|
||||
keys := map[string]bool{}
|
||||
for _, s := range list {
|
||||
for _, k := range sessions.GatewayKeys(s) {
|
||||
keys[k] = true
|
||||
}
|
||||
}
|
||||
var ext []sessions.ExternalSession
|
||||
title := sessions.GatewayTitler()
|
||||
for _, g := range listedGateway(usage.GatewaySessions(time.Time{}, keys)) {
|
||||
ext = append(ext, gatewayListed(g, title))
|
||||
}
|
||||
all := sessions.MergeExternal(list, ext)
|
||||
all = all[:min(n, len(all))]
|
||||
// as the answer has them
|
||||
b, _ := json.Marshal(all)
|
||||
var out []sessions.Session
|
||||
json.Unmarshal(b, &out)
|
||||
for i := range out {
|
||||
out[i].Path = tilde(out[i].Path)
|
||||
}
|
||||
return out
|
||||
}
|
||||
same := func(what string, got, want []sessions.Session) {
|
||||
t.Helper()
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("%s: %d rows, want %d", what, len(got), len(want))
|
||||
}
|
||||
for i := range want {
|
||||
if !reflect.DeepEqual(got[i], want[i]) {
|
||||
t.Fatalf("%s: row %d\n got %+v\nwant %+v", what, i, got[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, n := range []int{5, 40, gateway + 10} {
|
||||
got, _ := ask(fmt.Sprint("/api/sessions?limit=", n))
|
||||
same(fmt.Sprint("limit ", n), got, want(n))
|
||||
}
|
||||
got, _ := ask("/api/sessions")
|
||||
same("no limit", got, want(sessions.All))
|
||||
for _, s := range got {
|
||||
if s.Gateway && (s.ID == "g3" || s.ID == "00000001-1111-2222-3333-444444444444") {
|
||||
t.Fatalf("listed %s|%s from the gateway", s.Agent, s.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// a session grows, as one being worked in does
|
||||
id := "00000002-1111-2222-3333-444444444444"
|
||||
p := filepath.Join(proj, id+".jsonl")
|
||||
grown := time.Now().Add(-time.Second).Truncate(time.Second)
|
||||
fh, err := os.OpenFile(p, os.O_APPEND|os.O_WRONLY, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fh.WriteString(line(id, grown, "more"))
|
||||
fh.Close()
|
||||
os.Chtimes(p, grown, grown)
|
||||
got, alloc := ask("/api/sessions?limit=20")
|
||||
same("after a session grew", got, want(20))
|
||||
if got[0].ID != id || !got[0].Last.Equal(grown) {
|
||||
t.Fatalf("the grown session isn't first at %v: %+v", grown, got[0])
|
||||
}
|
||||
// a row of each gateway session is ~3 MB here, and it was ~20 MB;
|
||||
// what doesn't grow with them is ~1 MB
|
||||
rows := uint64(gateway) * uint64(unsafe.Sizeof(sessions.Session{}))
|
||||
if alloc > rows {
|
||||
t.Fatalf("a poll of 20 rows after a session grew allocated %d bytes; %d gateway sessions' rows are %d", alloc, gateway, rows)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestCCListingKeepsItsNames: each Sessions poll made every Claude Code
|
||||
// file's path and key again, ~10 MB of a poll over ~15k sessions, though
|
||||
// the listing is the same but for a file or two. A listing like the last
|
||||
// makes none of them; a file new, gone or moved since is listed as a
|
||||
// fresh listing lists it.
|
||||
func TestCCListingKeepsItsNames(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
write := func(rel string) {
|
||||
t.Helper()
|
||||
p := filepath.Join(dir, "projects", rel)
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte("{}\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
const n = 3000
|
||||
for i := range n {
|
||||
write(fmt.Sprintf("-Users-someone-work-a-project-p%d/%08d-1111-2222-3333-444444444444.jsonl", i%3, i))
|
||||
}
|
||||
// a session's folder, sorted between files, with its subagents
|
||||
write("-Users-someone-work-a-project-p1/00000500-aaaa/subagents/agent-1.jsonl")
|
||||
write("-Users-someone-work-a-project-p1/00000500-aaaa/subagents/workflows/run-1/agent-2.jsonl")
|
||||
write("-Users-someone-work-a-project-p1/00000500-aaaa/subagents/workflows/run-1/note.jsonl")
|
||||
ccListed.Clear()
|
||||
t.Cleanup(func() { ccListed.Clear() })
|
||||
fresh := func() []file {
|
||||
ccListed.Clear()
|
||||
return listCCFiles("claude", dir)
|
||||
}
|
||||
same := func(what string, got []file) {
|
||||
t.Helper()
|
||||
want := fresh()
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("%s: %d files, a fresh listing %d", what, len(got), len(want))
|
||||
}
|
||||
}
|
||||
|
||||
first := listCCFiles("claude", dir)
|
||||
if len(first) != n+2 {
|
||||
t.Fatalf("listed %d files, want %d", len(first), n+2)
|
||||
}
|
||||
runtime.GC()
|
||||
var before, after runtime.MemStats
|
||||
runtime.ReadMemStats(&before)
|
||||
again := listCCFiles("claude", dir)
|
||||
runtime.ReadMemStats(&after)
|
||||
if !reflect.DeepEqual(again, first) {
|
||||
t.Fatal("an unchanged folder listed otherwise")
|
||||
}
|
||||
// a path and a key a file made again are 2n more
|
||||
if m := after.Mallocs - before.Mallocs; m > 3*n {
|
||||
t.Fatalf("listing %d unchanged files took %d allocations", n, m)
|
||||
}
|
||||
|
||||
write("-p0/00000001-new.jsonl")
|
||||
same("a file new", listCCFiles("claude", dir))
|
||||
listCCFiles("claude", dir)
|
||||
os.Remove(filepath.Join(dir, "projects", "-Users-someone-work-a-project-p0", "00000003-1111-2222-3333-444444444444.jsonl"))
|
||||
os.Remove(filepath.Join(dir, "projects", "-Users-someone-work-a-project-p2", "00000005-1111-2222-3333-444444444444.jsonl"))
|
||||
os.Remove(filepath.Join(dir, "projects", "-Users-someone-work-a-project-p2", "00000008-1111-2222-3333-444444444444.jsonl"))
|
||||
same("files gone", listCCFiles("claude", dir))
|
||||
listCCFiles("claude", dir)
|
||||
os.RemoveAll(filepath.Join(dir, "projects", "-Users-someone-work-a-project-p1"))
|
||||
write("-p9/00000500-aaaa/subagents/agent-1.jsonl")
|
||||
same("a folder gone and one new", listCCFiles("claude", dir))
|
||||
listCCFiles("claude", dir)
|
||||
// the same names under another agent's key
|
||||
got := listCCFiles("qoder", dir)
|
||||
for _, f := range got {
|
||||
if f.key[:6] != "qoder:" {
|
||||
t.Fatalf("key %q under qoder", f.key)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,3 +86,29 @@ func mergedIDs(list []Session) []string {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TestEachMergedMakesOnlyTheRowsItReaches: every gateway session was made
|
||||
// into a row before the merge, ~22 MB of each poll over ~15k sessions
|
||||
// while one of them grew, though the page stops at sessions.All rows.
|
||||
func TestEachMergedMakesOnlyTheRowsItReaches(t *testing.T) {
|
||||
at := time.Now()
|
||||
ext := make([]ExternalSession, 15000)
|
||||
for i := range ext {
|
||||
// oldest first, so the order is the merge's to make
|
||||
ext[i] = ExternalSession{Agent: "opencode", ID: fmt.Sprint("g", i), Last: at.Add(time.Duration(i-len(ext)) * time.Second),
|
||||
Models: []ExternalModel{{Model: "m"}}}
|
||||
}
|
||||
native := []Session{{Agent: "claude", ID: "c", Last: at.Add(-10 * time.Second)}}
|
||||
var before, after runtime.MemStats
|
||||
runtime.ReadMemStats(&before)
|
||||
var got []Session
|
||||
EachMerged(native, ext, func(s *Session) bool { got = append(got, *s); return len(got) < 20 })
|
||||
runtime.ReadMemStats(&after)
|
||||
if want := MergeExternal(native, ext)[:20]; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("rows\n got %v\nwant %v", mergedIDs(got), mergedIDs(want))
|
||||
}
|
||||
rows := uint64(len(ext)) * uint64(unsafe.Sizeof(Session{}))
|
||||
if a := after.TotalAlloc - before.TotalAlloc; a > rows/10 {
|
||||
t.Fatalf("20 rows of %d gateway sessions allocated %d bytes; every row is %d", len(ext), a, rows)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,15 +54,27 @@ func EachMerged(native []Session, external []ExternalSession, each func(*Session
|
||||
native = slices.Clone(native)
|
||||
slices.SortStableFunc(native, newest)
|
||||
}
|
||||
added := externalSessions(external)
|
||||
slices.SortStableFunc(added, newest)
|
||||
// external's sessions in the order externalSessions then a stable
|
||||
// sort by Last give them, as indexes: a row is made only when it is
|
||||
// reached. Every gateway session past what native lists was made into
|
||||
// a row on each poll, ~22 MB of a poll over ~15k sessions while one
|
||||
// grew, though the page stops at sessions.All rows.
|
||||
added := make([]int, 0, len(external))
|
||||
for k, e := range external {
|
||||
if e.Agent != "" && e.ID != "" {
|
||||
added = append(added, k)
|
||||
}
|
||||
}
|
||||
slices.SortStableFunc(added, func(a, b int) int { return external[b].Last.Compare(external[a].Last) })
|
||||
names := desktopExternalTitles(external)
|
||||
// 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
|
||||
if j < len(added) && (i == len(native) || external[added[j]].Last.After(native[i].Last)) {
|
||||
row := externalSession(external[added[j]], names)
|
||||
s, j = &row, j+1
|
||||
} else {
|
||||
s, i = &native[i], i+1
|
||||
}
|
||||
@@ -114,17 +126,27 @@ func externalSessions(external []ExternalSession) []Session {
|
||||
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}
|
||||
for _, m := range e.Models {
|
||||
s.Models = append(s.Models, Model{Model: m.Model, Tokens: m.Tokens, Cost: m.Cost, Priced: m.Priced})
|
||||
s.Tokens.add(m.Tokens)
|
||||
}
|
||||
s.Cost = e.Cost
|
||||
out = append(out, s)
|
||||
out = append(out, externalSession(e, names))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// externalSession is e as a list shows it; names are
|
||||
// desktopExternalTitles'.
|
||||
func externalSession(e ExternalSession, names map[string]string) Session {
|
||||
name := ""
|
||||
if len(names) > 0 {
|
||||
name = names[e.Agent+"|"+e.ID]
|
||||
}
|
||||
s := Session{ReadOnly: true, Gateway: true, Transcript: true, Agent: e.Agent, ID: e.ID, Title: cmp.Or(name, e.Title, e.ID), Start: e.Start, Last: e.Last, Models: []Model{}, Unpriced: e.Unpriced}
|
||||
for _, m := range e.Models {
|
||||
s.Models = append(s.Models, Model{Model: m.Model, Tokens: m.Tokens, Cost: m.Cost, Priced: m.Priced})
|
||||
s.Tokens.add(m.Tokens)
|
||||
}
|
||||
s.Cost = e.Cost
|
||||
return s
|
||||
}
|
||||
|
||||
// desktopExternalTitles are the names an app saved for its sessions among
|
||||
// external, by Agent|ID: Claude Desktop's (DesktopTitles), PI-Desktop's
|
||||
// (PIDesktopTitles, #1967). They come before the gateway's recorded first
|
||||
|
||||
@@ -594,34 +594,75 @@ func ccFiles(agent, dir string) []file {
|
||||
return heldFiles("cc\x00"+agent+"\x00"+dir, func() []file { return listCCFiles(agent, dir) })
|
||||
}
|
||||
|
||||
// ccListed is how many files each folder's last listCCFiles found: its
|
||||
// listing grown from none, a file at a time, was ~35 MB of a minute of the
|
||||
// page's polls over 13 GB of Claude Code history (#2278).
|
||||
var ccListed sync.Map // dir → int
|
||||
// ccListed is each folder's last listCCFiles' paths and keys, in its
|
||||
// order: its listing grown from none, a file at a time, was ~35 MB of a
|
||||
// minute of the page's polls over 13 GB of Claude Code history (#2278),
|
||||
// and making each file's path and key again was ~10 MB of every poll
|
||||
// over ~15k sessions, while the listing is the same but for a file or
|
||||
// two.
|
||||
var ccListed sync.Map // dir → []ccName
|
||||
|
||||
type ccName struct{ path, key string }
|
||||
|
||||
// ccNames gives a file's path and key, the last listing's strings when
|
||||
// they are the same, as they are for all but a file or two.
|
||||
type ccNames struct {
|
||||
last []ccName
|
||||
at int // where the last listing is read up to
|
||||
now []ccName
|
||||
}
|
||||
|
||||
// of is filepath.Join(dir, name) and agent+":"+id, as last listed.
|
||||
func (c *ccNames) of(dir, name, agent, id string) (string, string) {
|
||||
// one file new or gone since is stepped over
|
||||
for i := c.at; i < min(c.at+2, len(c.last)); i++ {
|
||||
if l := c.last[i]; joinedIs(l.path, dir, name) && joinedIs(l.key, agent, id, ':') {
|
||||
c.at = i + 1
|
||||
c.now = append(c.now, l)
|
||||
return l.path, l.key
|
||||
}
|
||||
}
|
||||
n := ccName{filepath.Join(dir, name), agent + ":" + id}
|
||||
c.now = append(c.now, n)
|
||||
return n.path, n.key
|
||||
}
|
||||
|
||||
// joinedIs is whether s is a, sep, b: filepath.Join(a, b) for a clean a
|
||||
// and a b without a separator, as a folder's entries are.
|
||||
func joinedIs(s, a, b string, sep ...byte) bool {
|
||||
c := byte(filepath.Separator)
|
||||
if len(sep) > 0 {
|
||||
c = sep[0]
|
||||
}
|
||||
return len(s) == len(a)+1+len(b) && s[len(a)] == c && s[:len(a)] == a && s[len(a)+1:] == b
|
||||
}
|
||||
|
||||
func listCCFiles(agent, dir string) []file {
|
||||
projects := filepath.Join(dir, "projects")
|
||||
n, _ := ccListed.Load(dir)
|
||||
last, _ := n.(int)
|
||||
out := make([]file, 0, last+last/8)
|
||||
defer func() { ccListed.Store(dir, len(out)) }()
|
||||
last, _ := ccListed.Load(dir)
|
||||
names := ccNames{last: func() []ccName { l, _ := last.([]ccName); return l }()}
|
||||
names.now = make([]ccName, 0, len(names.last)+len(names.last)/8)
|
||||
out := make([]file, 0, cap(names.now))
|
||||
defer func() { ccListed.Store(dir, slices.Clip(names.now)) }()
|
||||
for _, project := range readDirectory(projects) {
|
||||
if !dirent.IsFolder(projects, project) {
|
||||
continue
|
||||
}
|
||||
root := filepath.Join(projects, project.Name())
|
||||
for _, e := range readDirectory(root) {
|
||||
path := filepath.Join(root, e.Name())
|
||||
if !e.IsDir() && strings.HasSuffix(e.Name(), ".jsonl") {
|
||||
f := file{agent: agent, key: agent + ":" + strings.TrimSuffix(e.Name(), ".jsonl"), path: path, main: true}
|
||||
path, key := names.of(root, e.Name(), agent, strings.TrimSuffix(e.Name(), ".jsonl"))
|
||||
f := file{agent: agent, key: key, path: path, main: true}
|
||||
out = append(out, f)
|
||||
} else if dirent.IsFolder(root, e) {
|
||||
path := filepath.Join(root, e.Name())
|
||||
subs := filepath.Join(path, "subagents")
|
||||
for _, sub := range readDirectory(subs) {
|
||||
if sub.IsDir() || !strings.HasSuffix(sub.Name(), ".jsonl") {
|
||||
continue
|
||||
}
|
||||
f := file{agent: agent, key: agent + ":" + e.Name(), path: filepath.Join(subs, sub.Name())}
|
||||
path, key := names.of(subs, sub.Name(), agent, e.Name())
|
||||
f := file{agent: agent, key: key, path: path}
|
||||
out = append(out, f)
|
||||
}
|
||||
for _, run := range readDirectory(filepath.Join(subs, "workflows")) {
|
||||
@@ -633,7 +674,8 @@ func listCCFiles(agent, dir string) []file {
|
||||
if sub.IsDir() || !strings.HasPrefix(sub.Name(), "agent-") || !strings.HasSuffix(sub.Name(), ".jsonl") {
|
||||
continue
|
||||
}
|
||||
f := file{agent: agent, key: agent + ":" + e.Name(), path: filepath.Join(dir, sub.Name())}
|
||||
path, key := names.of(dir, sub.Name(), agent, e.Name())
|
||||
f := file{agent: agent, key: key, path: path}
|
||||
out = append(out, f)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,6 +98,20 @@ func GatewaySessions(since time.Time, nativeKeys map[string]bool) []GatewaySessi
|
||||
return out
|
||||
}
|
||||
|
||||
// EachGatewaySession calls each with every session
|
||||
// GatewaySessions(time.Time{}, nativeKeys) gives, in its order (newest
|
||||
// first, then by agent and id), until each returns false, without a copy
|
||||
// of them all: the Sessions list shows sessions.All rows at most, and each
|
||||
// of its polls while a session grew copied every one of ~10k more. A
|
||||
// session's Models and Daily are the projection's own, as there.
|
||||
func EachGatewaySession(nativeKeys map[string]bool, each func(GatewaySession) bool) {
|
||||
for _, s := range gatewayProjection().sessions {
|
||||
if !nativeKeys[s.Agent+"|"+s.ID] && !each(s) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// localMidnight is since's local date when since is that date's start.
|
||||
func localMidnight(since time.Time) (string, bool) {
|
||||
date := since.In(time.Local).Format(time.DateOnly)
|
||||
|
||||
Reference in New Issue
Block a user