Files
magpie/internal/sessions/list_kept_test.go
T
yetone aef89edf10 sessions: a listing over unchanged files is the one made last
The Sessions page lists every session every 15 s. Between two polls the
files mostly haven't changed, yet each listing grouped, sorted and
assembled all of them again (byKey, the key sort, ccFamily, assemble with
subagents and resume commands).

listSessions now keeps what it made last (keptList, beside keptStats) and
gives a copy of it out when nothing it was made from has changed:
- every listed file's path, size, time and parse (keptFileOf, the same
  check the stats use, factored out as keptStill);
- the cache generation and the limit asked for;
- the prices, Codex thread names and Claude Desktop names the listing got,
  asked again;
- the command an agy row resumes with (AgyStart), when agy is listed.
What a row shows beside those (an agent to carry it to being installed, a
Claude Code subagent's meta, a Kimi wire file) is looked at again at most
a minute later (listKeptFor). refresh now runs before the grouping, which
it never read. Reset forgets the kept listing.

Measured with the real ~17k sessions (APFS clones of ~/.codex/sessions
and ~/.claude/projects in a sandbox HOME), 30 polls of /api/sessions,
/api/sessions/stats and /api/sessions/overview, X-Magpie-Had as the page
sends it:
- before (21882a68d): ~185 ms CPU a poll, /api/sessions median 89 ms,
  List 1.42 s of the handler's 1.93 s profiled;
- after: ~151 ms CPU a poll, median 70 ms, List 0.98 s of 1.39 s, no
  assemble in the profile. What is left of List is listing the folders
  (getattrlistbulk, ~26 ms a poll).
Measured before the agy check was added; that adds one AgyStart call a
poll when agy is listed.

Run on mote at the rebased head:
- go test ./internal/sessions: ok; -count=3 of TestListKept,
  TestAgySessions and TestStatsKept: ok.
- go test ./internal/cli ./internal/davsync ./internal/otlp ./internal/tui
  ./internal/tune: ok. ./internal/usage: ok (before the rebase).
- ./internal/gui: TestSettingsSaveKeepsWhatItDoesNotSend (#4739) and
  TestMainWindowCorners (#3949) red, the same on origin/main 788057340;
  everything else ok.

Broken by hand, each red:
- dropping the keptStill check: TestListKeptBetweenPolls "output 170
  after the file grew, 170 before";
- giving out the kept slice itself: "a caller's write reached the kept
  listing";
- never using the kept listing: "unchanged files listed again 1 times";
- dropping the AgyStart check: TestAgySessions "wired resume ... agy
  --conversation", the wired command wanted.

Not run: internal/agent and internal/gateway (they list sessions only
through the same List), the GUI browser suite (no page code changed).

Then rebased onto f2f75ee4a (provider: Volcengine Ark's System One API, in beta, as a dec); not rerun.
2026-11-01 14:18:44 +08:00

92 lines
3.1 KiB
Go

package sessions
import (
"fmt"
"os"
"path/filepath"
"reflect"
"testing"
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/settings"
)
func listingsMade() int {
mu.Lock()
defer mu.Unlock()
return keptList.made
}
func keptRow(t *testing.T, list []Session, key string) Session {
t.Helper()
for _, s := range list {
if s.Agent+":"+s.ID == key {
return s
}
}
t.Fatalf("%s not listed in %d sessions", key, len(list))
return Session{}
}
// TestListKeptBetweenPolls: a listing over files that haven't changed gives
// the one made last, not every session grouped and assembled again, and a
// file that changed, a price, Codex's name for a thread or the time it was
// kept makes it again. A caller writing a row writes its own copy.
func TestListKeptBetweenPolls(t *testing.T) {
claude, codex := setup(t)
const cc, cx = "claude:11111111-2222-3333-4444-555555555555", "codex:01a0bdc9-b5fd-7e63-9658-68bc8dce5ecd"
first := List(All)
made := listingsMade()
again := List(All)
if n := listingsMade() - made; n != 0 {
t.Fatalf("unchanged files listed again %d times", n)
}
if !reflect.DeepEqual(again, first) {
t.Fatalf("kept %+v\nlisted %+v", again, first)
}
again[0].Title = "written by a caller"
if List(All)[0].Title == "written by a caller" {
t.Fatal("a caller's write reached the kept listing")
}
out := keptRow(t, first, cc).Tokens.Output
f, err := os.OpenFile(filepath.Join(claude, "projects", "-work-app", "11111111-2222-3333-4444-555555555555.jsonl"), os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
_, err = f.WriteString(`{"parentUuid":"a1","isSidechain":false,"message":{"model":"claude-opus-5-5","id":"msg_kept","type":"message","role":"assistant","content":[{"type":"text","text":"more"}],"usage":{"input_tokens":1,"output_tokens":7000}},"requestId":"req_kept","type":"assistant","uuid":"a-kept","timestamp":"2026-09-20T10:30:00.000Z","cwd":"/work/app","sessionId":"11111111-2222-3333-4444-555555555555"}` + "\n")
f.Close()
if err != nil {
t.Fatal(err)
}
grown := List(All)
if n := keptRow(t, grown, cc).Tokens.Output; n != out+7000 {
t.Fatalf("output %d after the file grew, %d before", n, out)
}
cost := keptRow(t, grown, cc).Cost
PriceOf = func(_ settings.Settings, m string) (catalog.Price, bool) {
return catalog.Price{Input: 40, Output: 200, CacheRead: 2, CacheWrite: 50}, true
}
if c := keptRow(t, List(All), cc).Cost; c <= cost {
t.Fatalf("cost %v after the prices went up, %v before", c, cost)
}
line := fmt.Sprintf("{\"id\":\"01a0bdc9-b5fd-7e63-9658-68bc8dce5ecd\",\"thread_name\":\"Named in Codex\",\"updated_at\":%q}\n", time.Now().UTC().Format(time.RFC3339Nano))
if err := os.WriteFile(filepath.Join(codex, "session_index.jsonl"), []byte(line), 0600); err != nil {
t.Fatal(err)
}
if got := keptRow(t, List(All), cx).Title; got != "Named in Codex" {
t.Fatalf("title %q after Codex named the thread", got)
}
defer func(d time.Duration) { listKeptFor = d }(listKeptFor)
listKeptFor = 0
made = listingsMade()
List(All)
if n := listingsMade() - made; n != 1 {
t.Fatalf("a listing kept past listKeptFor was made %d times, want 1", n)
}
}