Commit Graph
243 Commits
Author SHA1 Message Date
yetone b78b1de003 library: magpie-image is behind the MCP hub, saving into the calling agent's project
magpie-image was the one MCP server the hub left out, because it saves
what it makes on disk and needs to know whose project that is. The hub
now serves its tools like any other server's and tells it where the
caller works:

1. the hub answers a tools/call as SSE and asks the agent roots/list on
   that stream (3s), as Claude Code answers;
2. else Codex's _meta x-codex-turn-metadata.workspaces (git repos only);
3. else the Codex thread's cwd from its session file
   (sessions.CodexThreadCwd), only with session consent;
4. else none, and the image goes to ~/Pictures/Magpie as before.

The hub passes `magpie/roots` and `magpie/client` in the call's _meta;
imagemcp saves into the first root and names the agent on its usage
row. Its result carries `magpie/model`, which the hub's own usage row
takes, so the row says which image model drew it. A WSL agent keeps
magpie-image as its own entry (the hub can't reach a path inside the
distro). docs/subsystems/mcp-hub.md (mcp-router.md after the next commit), gateway-routing.md and
gateway-sessions.md say so.

It is rebased on #4382 (b889ffe81), which lets the user keep a server
out of the hub (Server.Hub = direct). inHub now asks both: a server
kept direct is out, and magpie-image is in unless the agent is in WSL,
so the user can keep magpie-image direct too; the editor's switch
shows for it like any server, and the hub's line counts it with the
others (mcp-hub-direct.test.cjs follows).

Run at e2583df31 (this stack on 86fef947e), on mote: gofmt -l clean;
go vet for darwin, linux (-tags nogui) and windows; go build ./...;
go test -tags nogui ./... -timeout 45m, 81 packages ok, 0 FAIL;
library, gateway, imagemcp, sessions, cli and gui again alone, ok;
site's node --test, 49 of 49. GUI on xiaomi-gpu (Windows; mote's
browsers crashed under other sessions' suites): library-*, image*,
mcp-hub-direct, i18n-keys, list-sort and plugin-tools, both engines and
every language, 1055 of 1056: i18n-keys found "{name} is given to each
agent directly" dropped from the library's strings in the rebase. Put
back in the first commit; at the pushed head i18n-keys, mcp-hub-direct
and library-mcp-hub are 48 of 48. That is the only difference from
e2583df31.
Broken by hand at e2583df31: imagemcp ignoring magpie/roots fails
TestHubCallSavesInTheCallersProject; the router asking anything but
roots/list fails TestHubAsksTheAgentItsRoots and TestHubRootsUnasked;
inHub leaving magpie-image out fails TestHubGivesMagpieImage.
Real use, sandbox HOME and gateway, at 62421e570 (before the rebase): Claude Code saved into its project
via roots/list; Codex in a git repo via its workspaces _meta; Codex
outside a repo with session consent via the thread's cwd.
At 62421e570 the whole GUI suite ran on WSL magpie-desktop at load 116 to 135 from other
runs: 504 of 15757 red in 118 files, WebKit timeouts, none in a file
this change touches; filed as #4471 with the list.

Rebased once more onto 2570efb5f, which changed library-mcp-hub,
list-sort, mcp-hub-direct and gateway-routing.md. Run at the pushed
head: go build; gateway, library, cli and imagemcp tests ok; the GUI
budget tests ok; on xiaomi-gpu i18n-keys, mcp-hub-direct,
library-mcp-hub and list-sort, 51 of 54. The three reds were WebKit
420px library-mcp-hub cases with no Connect sheet after a reload.
origin/main d77da5bff goes red the same way (de 420px, 9 of 11). In a
second run of library-mcp-hub on WebKit at this head, 11 of 11 passed.
Filed as #4483.
Not tried: Codex outside a git repo without consent (it saves to
~/Pictures/Magpie, #4435); agents on Windows and in WSL with real use.
2026-10-31 02:49:08 +08:00
yetone 1334934881 sessions: a listing's gateway titles ask once whether anything was recorded, not once a session (#2278)
Each poll of the Sessions list and of every stats range titled each of
~5000 gateway sessions with GatewayTitle, which made the recordings
folder's name and Stat-ed it each time. With nothing recorded, as for
most users, that was the whole cost: os.Stat 62 MB and gatewayDir 18 MB
of 90 s of polls while an agent worked.

GatewayTitler makes the folder's name and asks once, and gives "" with
no work when nothing is recorded; gatewayListed takes it. GatewayTitle
is GatewayTitler()(agent, id), for one session.

Bench (mote, ~/r2278/full, hmw.sh second runs), e14 = bed604efb, e15 =
this: GatewayTitle 81 MB -> gone, gatewayListed 100 -> 19 MB, polls 170
x 200 in both; total 2308 -> 2350 MB is the run-to-run band.

TestGatewayTitlerAsksOnce: with nothing recorded a title makes 0
allocations; after a turn is recorded a titler made then finds what
GatewayTitle finds. Broken by hand (Stat and the folder's name again per
session): red.

At 825db07aa on bed604efb (mote): gofmt clean; go vet -tags nogui
./internal/gui/ ./internal/sessions/ for linux, windows, darwin ok;
go test ./internal/sessions/ ok; go test ./internal/gui/ -run
'Gateway|Sessions|Stats' ok.
2026-10-30 19:12:35 +08:00
yetoneandYangHonghang 9e73f69af4 providers: rate windows bill a provider's hours at its own rate (#2463)
A provider can have up to 8 rate windows: days, a span that may cross
midnight (on this computer's clock), and a rate. Inside a window a call
costs the base price times the rate. The base is the user's model price
as set, or the list price times PriceRate with the vendor's own peak
(DeepSeek, Command Code, OpenCode Go) already in it. The author gave
this order as the spec: a 0.8 window on a shared DeepSeek key takes 0.8
off the peak price at peak. The editor's hint says not to set the
official peak hours again as a window, in every language.

Each call is priced at its own time on the Usage page and its CSV, in
the Requests tab's rows, and against a gateway key's cost limit. The
Sessions page, group templates and the model list written into an
agent's own config use the base price. /v1/models prices at now.

Ported from YangHonghang's 2c9d459ff (rate-windows-2463-v2). The Go
pricing, its tests and the translations are theirs. Changed here:
- No budget raised. Their commit raised appScriptBudget and
  coreScriptBudget; core_budget_test.go is main's again. The editor's
  window rows, time menus, validation and hint moved to ratewindows.js,
  which app.js imports when the field is drawn (as signsheets.js is).
  The sliding-thumb and modalDepth comments were cut down to make room.
  The core is 1,535,528 of 1,536,586 and app.js 1,312,242 of 1,315,316.
  Until the script has loaded, a save leaves rateWindows out, and the
  server keeps the saved ones.
- Their unrelated TestAssetsHaveNoConflictMarkers is dropped (one
  commit, one goal).
- The row badge shows only for a provider with windows. Before, every
  provider with a price rate alone got a new ×badge. Its title is
  shorter, and so are its translations.
- AgentPricer (agent model files: Pi, omp, OpenCode cost) uses the base
  price. Nothing rewrites those files when a window opens or closes, so
  a price taken at Sync stayed on outside the window.
- internal/budget gets a TestMain through testenv, so the new test
  runs in a home of its own.
- old-webkit's list of lazily loaded scripts names ratewindows.js.
- The draft keeps each window as a shallow copy, and a day chip
  replaces its days array, so the saved provider is never changed.
- The GUI test waits for the lazy script's hint, not a fixed 300ms.
  It also checks the peak note in each language.

Run first on 2f5a3f1c0, then again after rebasing on 70d9996c5,
8acb0d3a7 and d609729cf. The rebase onto 70d9996c5 met main's ruleedit.js in
old-webkit's list, and both are listed.
- gofmt -l internal: clean at 8acb0d3a7 (129578c3d gofmt'd main's
  pi_api_test.go).
- mote, on 8acb0d3a7: go vet on usage, provider and gui
  ok; GOOS=linux and GOOS=windows go vet -tags nogui ./... ok.
  go test -tags nogui for internal/usage, provider, gui, budget and
  sessions: ok. The five internal/agent tests that are red on WSL
  (below) pass on mote there. On d609729cf (a one-line mover min in
  internal/provider), internal/provider again: ok.
- On 2f5a3f1c0: internal/provider, usage, budget and sessions, and the
  gui RateNow|PriceRate|CoreScript|Budget tests, each under TZ=UTC,
  Asia/Shanghai and America/Los_Angeles: all ok.
- wsl-run (magpie-desktop, Playwright chromium and webkit) on
  70d9996c5: provider-rate-windows, old-webkit, i18n-keys,
  provider-price-rate, provider-advanced-fold, agent-hides-editor,
  key-box-once, provider-many-keys, nokey-editor and
  editor-short-window: 200/200. On 2f5a3f1c0 the first five and
  model-price-edit: 132/132. On mote the same files hit WebKit launch
  timeouts (180s) under another session's full GUI suite (load 30), and
  that run was stopped.
- Full suite, wsl-run (mote was running another session's full suite),
  go test -tags nogui -count=1 -timeout 45m ./... at 6e534f546 (this
  change on 70d9996c5): every package ok except internal/agent.
  internal/agent fails TestInstalledVersion, TestGrokInstalled,
  TestCursorFolderFromTheEditorIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath. This change doesn't touch internal/agent. At
  origin/main 8acb0d3a7 on the same box, TestInstalledVersion,
  TestGrokInstalled and TestOmpDetectedWithPiDir fail too: a fake CLI
  in /tmp exec'd with "Invalid argument". That is #4033 and #3548
  (WSL2 binfmt interop).
- Broken by hand, red each time:
  - Pricer without the window: TestPricerRateWindows,
    TestBlockRowsTakeTheirRateWindow, TestCostLimitCountsTheRateWindow.
  - Block rows without atWindow: TestBlockRowsTakeTheirRateWindow.
  - AgentPricer at now: TestAgentPricerLeavesTheRateWindowOut.
  - Badge for a price rate alone: TestRateNowOf.
  - Peak note removed: provider-rate-windows, 10 of 10 chromium
    layouts.
  - ratewindows.js not in old-webkit's list: old-webkit.

Not tried:
- A real relay billed by the hour.
- The real desktop app (WebKitGTK, WKWebView).
- The full GUI suite (mote was running another session's).
Known limits:
- No rate is stored per record, so changing the windows reprices
  history, as a changed PriceRate does.
- Windows follow this computer's zone, with no zone of their own.
- The Sessions page uses the base price.

Co-authored-by: YangHonghang <honghang.yang@qq.com>
2026-10-30 18:55:51 +08:00
yetone bcf0cfa232 sessions: usage counts a session Claude Desktop's Code tab ran under Desktop
CyberCaius on Discord: Usage's Claude Code filter listed Claude Desktop's
sessions. Desktop's Code tab runs Claude Code, which keeps the session in
~/.claude/projects like a terminal one; only each line's `entrypoint`
(claude-desktop, claude-desktop-3p) tells them apart. The calls were
counted under Desktop already (desktopEntrypoint), but the session, its
stats rows and its summary were Claude Code's, and the gateway's own
record of the session ("claude-desktop|<id>") wasn't matched with it, so
it could be listed twice.

The parse now keeps the entrypoint (state.Entry, on both the ccWhere fast
path and the full parse; cacheVersion 29) and a Code tab session gets
Session.App "claude-desktop". Its Agent, key claude:<id>, resume and
transcript stay Claude Code's. Stats rows and the summary use the app,
GatewayKeys and MergeExternal know the claude-desktop|<id> pair, the GUI
names it Claude Desktop, and Usage › Sessions filters by app || agent.

Run at the pushed tip (the AnySearch commit after this one, on
e8d42c02d): go test ./internal/sessions ./internal/library ok (mote);
go vet darwin, linux -tags nogui, windows over ./internal/... VET-OK;
i18n-keys ok; usage-sessions-desktop-app.test.cjs (new) 4/4 chromium +
webkit, en + zh, on the Linux box (on mote its webkit.launch timed out at
load ~40, before any page code).
This commit alone, before the last rebase (8bd8f50d5 on 1534474c8):
go test ./internal/sessions ok and the new GUI test 4/4 (mote).
Run at 7ec95b5dd (both commits on 1534474c8):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  (mote): VET-OK.
- Full go test -tags nogui ./... -timeout 45m on the Linux box (wsl-run).
  Red only where origin/main eadeb89c4 is red on the same box, each filed:
  internal/agent install detection (#4033, #3548), internal/gateway
  Antigravity turned-away and TestCodexSpentGrokFailingIsTold (#4362);
  internal/cli TestAgentFieldNameShowsIt and
  TestEveryAgentFieldNameWritesNothing red in the full run, ok alone at
  this tip (#4247).
- GUI: i18n-keys and gui-de/ja/zh-tw ok on mote; the other sessions-*
  and usage-* files hadn't finished on mote when pushed.
- The whole GUI suite has not finished: a WSL run at the tip was about
  half way (2226 ok) when this was pushed, with reds only in files these
  changes don't reach (routing key models, panel name width, LAN
  addresses, Codex composer, Copilot GHE, gateway key limits, ...);
  they'll be checked against origin/main and filed on their own.
Earlier, before the rebase (da5f1e5bd on ffa07395e): full go test
-tags nogui ./... on mote, 80 packages ok.

Broken by hand, each red: stats not using appsOf (usage agent stays
claude); the Entry in claudeFull; the Entry in ccWhere (the test's first
line is an attachment so the fast path is taken); MergeExternal without
the App pair (3 sessions become 4); page.js's byAgent on agent only (GUI
test times out).

Not tried: a real Code tab transcript (none on this machine; fixtures are
written from the field names only). A Code tab that sends the plain
magpie key through settings.json env would be recorded by the gateway as
claude, not looked at. NativeIDs for claude-desktop doesn't read Claude
Code's files yet: #4333.
2026-10-30 14:38:22 +08:00
yetone eadeb89c48 sessions, dirent: a poll's listings are kept across collections (#2278)
A full history's page polls listed the same folders every few seconds
into a fresh slice, map and set each time: the sync.Pools meant to keep
them were emptied by the collector, which runs about twice a second at
this size, before the next poll took them.

- sessions: listingBufs and pathSets are shelves (shelf.go), which keep
  up to four across collections. listCCFiles makes its slice with the
  room of the folder's last listing.
- dirent: Stats keeps each folder's last listing (Listing.Done(dir)) and
  the room of the one before, up to 1<<17 entries in all. A name already
  in the folder's last listing is taken from it, not copied again. 1<<16
  kept too little of ~23k session files and their folders: the first
  bench of this change (budget 1<<16) took dirent.entry from 67-102 to
  80-100 MB a minute, no gain.

Bench, mote, the real full history (52G Codex in 12,495 files, 13G
Claude Code in 10,186), fullallogh.sh, alloc_space between the 50s and
110s heap profiles, MB per minute, before (v0.1.2132 equivalent) -> after:
  distinctOf      59      -> 22
  listCCFiles     42      -> 17
  dirent.entry    67-102  -> 55
  dirent.nameOf   24      -> 5
Totals swing 400-1200 MB with mote's load (other sessions), so these are
per function.

Run at this head (rebased on 3bebc3839), on mote:
- go build ./... ok
- go test -race -count=1 ./internal/dirent ok, ./internal/sessions ok
  (109.7s; one earlier run had TestLongReadKeepsWhatItRead red with a
  data race in testenv.Zone, red on 3bebc3839 too, 1 of 80 at -count=40
  -cpu 1,4: #4360)
- ./internal/gui: TestMainWindowCorners red, #3949 (mote is macOS 27);
  gui is not touched here
- GOOS=linux, windows, darwin go vet -tags nogui ./internal/dirent
  ./internal/sessions ok; gofmt -l clean

Broken by hand:
- TestListingKeptAcrossCollections (dirent) and
  TestListingPoolsKeptAcrossCollections (sessions) are red on the
  sync.Pool code: "a listing given back was let go by a garbage
  collection".
- name reuse turned off: "a name listed before was copied again".

Not tried: the Windows and Linux listers (stats_other.go returns no
listing there, as before).
2026-10-30 12:25:23 +08:00
yetone 37527c7ad3 sessions: omp's subagents and advisor are their session's to the gateway, not counted again (Jumy on Discord)
omp's task subagent (Kid.jsonl) and advisor (__advisor.jsonl) each have
a header id of their own, and omp sends that id, not the main
session's, in x-session-affinity (seen in a real omp 18.9.1 run through
a fake upstream: the main session's requests carried 01a18ae4-555c-…,
the subagent's 01a18ae4-5671-…). magpie counts those files in the main
session, but the gateway's native keys held only omp|<main id>, so the
gateway's records of the subagent's and advisor's calls were added
again as sessions of their own: in Usage › Sessions' totals
(MergeExternalStats), in the Sessions list (MergeExternal) and in
NativeIDs.

Session.Subs (subIDs) now holds those ids, and GatewayKeys,
MergeExternal and nativeIDsWith take them as the session's own.
GatewayKeys takes Claude Code's Copies too, which the GUI list added
by hand beside it; the stats' native map already had each copy's own
group, so nothing counts differently there.

This is at most a second count of the subagent's and advisor's share,
not a ~1000x: it may not explain the whole ~900M Jumy saw. Not found
in the reader: omp's usage is per call (assistant messages only;
toolResult and compaction carry none), re-reads continue from the
offset only when the head and sampled prefix hashes match.

Tests: TestOmpSubagentsAreTheSessionsToTheGateway (sessions, the
existing omp fixture, whose sub headers match omp 18.9.1's) and
TestOmpSubagentCountedOnceWithTheGateway (gui, /api/sessions/overview
and /api/sessions, from omp 18.9.1's own lines). Broken by hand
(subIDs returning nil): both red, the overview showing the Kid id as a
second gateway session with 5000 input beside the native one.

Run on mote: go test ./internal/sessions -run 'TestOmp|TestRaft',
./internal/gui -run 'TestOmpSubagent|TestTopSessions'; gofmt -l;
go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet on the two
packages; go build for darwin, linux (nogui), windows.
go test -timeout 45m ./internal/sessions ./internal/gui ./internal/usage:
sessions and usage ok; gui red only in TestMainWindowCorners/macOS_26_SDK,
#3949 (mote's macOS 27, titlebar code this change doesn't reach). The
full ./... was not run before the push: mote had other sessions' full
suites running at load ~180.

Not tried: Jumy's own session files or ledger (not available), so the
rest of the 900M is unexplained; Kimi Code's subagents (it sends no
session header magpie knows, so its gateway rows aren't sessions);
the GUI Playwright suite (no asset changed).
2026-10-30 11:54:46 +08:00
yetone accb951ab7 sessions: OpenCode 2, Cline and dsh count tool calls and skills; every agent says its skills
MaxMooreMy on X also asked whether every agent is checked ("感觉很多遗漏
的"). Going through Found()'s agents, three with sessions counted no tool
calls or skills at all:

- OpenCode 2 (v2 session_message): an assistant's content[] tool parts
  ({type:"tool", name, state.input}; the skill tool's input is {id}), a
  user row's skills[] (picked with @ in the TUI) and a 'skill' row
  (activated through the API).
- Cline: Anthropic tool_use blocks; the "skills" tool's input.skill.
- dsh: tool/call events (arguments a JSON string; the skill tool's
  {"name"}), and a /skill typed by the user (a user/message whose
  source is {kind:"skill-invocation", name}).

cacheVersion 28 reparses old sessions.

skills_every_agent_test.go: TestEveryAgentSaysItsSkills reads Found()'s
agents from access.go and fails when one has no entry. Each entry names
the test that proves its skills count (which must exist), the agent
whose parser it shares (compared by pointer), or why it has none:
zcode (OpenCode 1 tables, tool parts not read), kimi, workbuddy,
codebuddy, hermes, cursor, agy, minimax-code and gemini.

Fixtures are real captures in a sandbox HOME through magpie's gateway:
opencode 2.0.25 (a sqlite .dump of session_v2 and session_message),
cline 3.0.70 and dsh 0.2.1-rc.2 (zstd session.v4.jsonl), byte for byte.

Run on mote (mote-run): go test ./internal/sessions/ ok (76.9s), go vet
for darwin, linux and windows ok, ./internal/tui/... ok, ./internal/gui/
red only in TestMainWindowCorners/macOS_26_SDK, the same at base
(#3949). The sessions-overview GUI files passed in chromium and webkit.
Broken by hand: on the old parsers the three agent tests fail ("tools 0
[]"); the guard fails with an entry removed, a wrong parser, or a named
test missing.

Not tried: OpenCode's TUI typed by hand (prompts sent through its API,
as the TUI does), OpenCode 1's tables, Kimi Code (only the retired
Python kimi-cli was captured), hermes, cursor, agy, workbuddy; Windows
and Linux runs; a full ./... suite (mote busy with two other sessions'
suites). During the Cline capture, Cline's own auto-updater removed the
global /opt/homebrew/lib/node_modules/cline; cline@3.0.70 was installed
again (cline --version 3.0.70).
2026-10-30 11:28:49 +08:00
yetone 23e63f1a36 sessions: Factory Droid's skill calls count in the overview
MaxMooreMy on X ("droid 也能帮忙修复下吗") showed the Sessions overview's
Skills card empty for Droid. Droid's parser counted no tools by skill:
it never read the Skill tool's input.skill, and a typed /<name> prompt,
which droid sends with a <system-notification> holding
<skill filePath=…><name>X</name>, counted nothing.

Now the Skill tool counts its input.skill, and each <name> in a
skill-selection notification of a user message counts once (HTML
entities unescaped, a name cut short counted as nothing). cacheVersion
27 reparses old sessions.

Fixtures are four real droid 0.231.0 sessions (droid exec through
magpie's gateway, sandbox HOME), byte for byte: a Skill tool call,
/greet-user, /greet-user /wave-hand, and /nonexistentzz (no skill).

Run on mote (mote-run): go test ./internal/sessions/ ok (76.9s, with
the next commit), go vet for darwin, linux and windows ok,
./internal/tui/... ok, ./internal/gui/ red only in
TestMainWindowCorners/macOS_26_SDK, the same at base (#3949). Broken
by hand: the old droid.go fails TestDroidToolsAndSkills.

Not tried: Droid's TUI, a subagent's skills, Windows and Linux runs,
a full ./... suite (mote busy with two other sessions' suites).
2026-10-30 11:28:49 +08:00
yetone 7fd65aad56 sessions: a Codex listing reuses the last one's names, and dirent its room (#2278)
Each Codex listing (several a minute of the page's polls over a long
history) made every rollout's path and key again, grew a new
dirent.Listing an entry at a time for every day folder, and gave each
rollout name a slice of its own in distinctCodexFiles: ~230 MB of a
minute of polls, from 20k unchanged rollouts.

- listedRollouts keeps each day folder's rollouts as its last listing
  found them; a rollout listed before keeps its path and key (made
  only from its folder and name) and takes its size and time now.
  A folder is kept again only when a rollout came or went.
- dirent.Stats takes its listing from a pool and its callers
  (listedRollouts, statFiles) give it back with Done once read; Done
  clears it. getattrlistbulk's 64 KB buffer is pooled too.
- distinctCodexFiles keeps a name's first file in a map of ints, and
  a slice only for names with more files.

New tests: TestListedRolloutsKeepTheirNames (a grown, a removed and a
new rollout; reused strings) and TestStatsAfterDone.

Run on mote. Written on 7037cd980 (v0.1.2126), rebased on 6db21d869
(no sessions or dirent change between); at the pushed head again:
go test -race ./internal/dirent/ ./internal/sessions/ ok, and the
three vets below clean.
At the tree before the rebase:
- go vet -tags nogui ./internal/sessions/ ./internal/dirent/ for
  linux, windows and darwin: clean.
- go test -race ./internal/dirent/ ./internal/sessions/: ok, at this
  tree. Before the dirent pool was added: also ./internal/usage/ ok
  and ./internal/gui/ ok but TestMainWindowCorners (#3949, known).
- Broken by hand: listedRollouts not reading its last listing turns
  TestListedRolloutsKeepTheirNames red ("had its path and key made
  again"); Done not clearing turns TestStatsAfterDone red.
- Full-history bench (10 endpoints every 5s, heap profiles at 50s and
  110s, alloc_space diff), two rounds each, v0.1.2126 against this:
  listCodexFiles 229 / 238 MB -> 72 / 92 MB;
  dirent.Stats 115 / 130 MB -> 62 / 72 MB;
  distinctCodexFiles 40 / 51 MB -> 7 / 12 MB;
  readRequestState 318 / 390 MB -> 225 / 222 MB.
  The totals (1186 / 694 against 477 / 960 MB) swing with mote's load
  more than the change moves them.

Not changed: dirent's names are still copied for each entry (~30 MB),
and Linux and Windows list without dirent.Stats (walkLinked, statFiles'
lstat), so only the distinctCodexFiles part reaches them.
2026-10-30 11:17:19 +08:00
yetone 7037cd9801 sessions: the reads under a hold share one listing, and a pass's path set is reused (#2278)
A minute of the page's polls over a long history (52G Codex, 13G
Claude) allocated ~70 MB copying the held Codex listing for every
reader, ~35 MB on pruneCalls' and refresh's path maps, and ~40 MB more
on distinctOf's set and the Requests/effort listing made for each ask.
Allocation is what drives the collector's ~33% of CPU.

- heldFiles and the warm-up's listing hand every reader the same
  slice, clipped so an append is made elsewhere. Every caller only
  reads it or copies it (distinctOf, appends into their own); the one
  that sorted it, traceLineFiles, now concatenates into its own slice.
- distinctOf, pruneCalls and refresh take their path sets from a pool
  and clear them after the pass.
- CallSourcesAndCodexIdentities builds its listing in a pooled buffer
  given back once its sources are taken.

TestWarmUpListsRolloutsOnce checked that a caller could write over
the kept listing; it now checks the listing is shared and clipped.
TestHeldListingShared and TestListingPoolsGiveBackEmpty are new.

Run on mote at this tree, rebased onto e863f520c (gateway only) and
rerun after; then onto 7632e1be1 (internal/redact only):
- go vet -tags nogui ./internal/sessions/ ./internal/gui/
  ./internal/usage/ for linux, windows and darwin: clean.
- go test -race ./internal/sessions/ ./internal/usage/: ok.
  ./internal/gui/: ok but TestMainWindowCorners (#3949, known).
- Broken by hand: heldFiles' waiter returning slices.Clone again
  turns TestHeldListingShared red ("each read under the hold got a
  copy of the listing").
- The full-history bench (10 endpoints every 5s, heap profiles at 50s
  and 110s, alloc_space diff), two rounds each, v0.1.2121 against
  this:
  slices.Clone of the listing 69 / 30 MB -> gone;
  pruneCalls 36 / 25 MB -> 5 / 0.5 MB;
  distinctOf 122 / 81 MB -> 83 / 84 MB (its make and distinctInto).
  The totals per minute (1216 / 649 MB against 598 / 675 MB) swing
  with mote's load (~100 from other sessions) more than the change
  moves them, so they say nothing either way.

Not changed: the Codex listing itself (codexFilesIn, ~160-230 MB a
minute) is still made new for each hold, and readRequestState
(~310-390 MB) still reads every source per ask. Those are next.
2026-10-30 10:28:30 +08:00
yetone 7db0810b03 sessions: stats asked again unchanged are not encoded again; lists made at their size (#2278)
The Sessions page asks for /api/sessions/stats (7, 30 and every day) and
the list every poll. On a full history (52G Codex + 13G Claude) the
stats for every day are ~6 MB of JSON, encoded and hashed again on each
ask even when the page already had them, because the read behind every
10s replaced the kept stats with an equal copy.

- statsKept has a gen, kept when the read behind finds the same stats
  (sameStats: From, To, Keys, Days, what is sent). The handler keeps the
  tag last sent per ?days with its gen and agent names, and an ask with
  that tag is answered X-Magpie-Same without encoding. Only the 32-char
  tag is kept, no body.
- MergeExternalStats grows Sessions once for every external session; a
  Clip and then an append a session copied the whole list over and over.
- listSessions makes its page and its latest map at their size.

Run on mote at this head (rebased on 484bdca7c, run again after):
- go test ./internal/gui/ ./internal/sessions/: sessions ok; gui ok but
  TestMainWindowCorners/macOS_26_SDK, red on mote's macOS 27 the same
  without this change (#3949).
- GOOS=linux/windows/darwin go vet -tags nogui on both packages, gofmt.
- Broken by hand: the read behind always taking a new gen makes
  TestStatsTagKeptWhileTheSame red ("gen 2, want 1 kept").
- Real full history on mote, magpie web polled with the page's
  X-Magpie-Had, 10 endpoints every 5s, cur = cdf8151a2:
  alloc in 60s 1755 MB -> 1342 MB; bytes.growSlice 393 -> 105 MB;
  CPU in 60s 4.25s -> 3.60s, GC mark 1.28s -> 0.88s.
Not tried: the Windows and Linux apps; the encoding is the same code.
2026-10-30 08:32:57 +08:00
yetone 68b31ce236 sessions: a poll's file lists, merges and copy groups are made once (#2278)
Each Sessions or Usage poll listed every agent's files several times and
copied the Claude Code and Codex lists twice: callFilesWith made a
deduplicated slice and set, then callSourcesWith and allFiles appended to
it and deduplicated it again. Now callFileLists hands out the lists, and
distinctOf builds one slice and one set at their combined size.

More cuts on the same poll path:
- allowed (the read-consent gate, af8f3a939) gives back its list as it is
  when every file's agent may be read. Before, it copied every file on
  each of the poll's passes.
- MergeExternal keys its set by an {agent, id} pair, not a string built
  for each of ~5000 sessions, and sizes the output once. It keeps the
  pairs GatewayKeys names, Raft's Pi id included.
- codexSubagentTaskTitles skips the four parent maps for a thread that
  spawns no agent, which is most of them.
- ccFamily holds each file by its index instead of copying ~200 bytes,
  and builds groups only for roots with two or more files. A singleton's
  uuid memo is still let go, as before.

Allocation on mote's bench (ab19, 80s of polls over ~34k sessions):
before this, callFilesWith was 250 MB, MergeExternal 200 MB, ccCopies
180 MB and codexSubagentTaskTitles 145 MB.

A/B on idle mote (ab21; polls every 5s over 10 endpoints while the ledger
and a Codex rollout are written; v0.1.1981 / the two commits before this
/ all three #2278 commits):
- mean poll 0.35s / 0.25s / 0.25s
- /api/sessions 0.87s / 0.73s / 0.47s
- /api/sessions/stats 0.33s / 0.26s / 0.15s
- /api/usage/heatmap 0.94s / 0.79s / 0.54s
- CPU 27.9% / 26.9% / 24.3%
ab20, run under load ~30 from other runs, showed the stats endpoints
slower in the order g25-last. Its CPU profile had less sessions work,
and run idle the gap goes the other way, so ab20's latency was load.
RSS stays the same (1014 / 1036 / 1045 MiB average, footprint peak 871
/ 884 / 869M). GOGC 25 still sets the GC share (~22-26%).

Rebased onto origin/main f982e46f2. calls.go, sessions.go, external.go
and cc_copies.go conflicted with the read-consent gate (af8f3a939),
Raft's sessions (9474eaf9c) and ccFamily's branches (f594b452e). Each
cut was made again on main's code.

Run at this head, on mote:
- GOOS=linux, windows and darwin go vet -tags nogui ./internal/sessions/
  ./internal/usage/ ./internal/gui/: ok.
- go test -timeout 45m ./internal/sessions/ ./internal/usage/
  ./internal/gui/: sessions and usage ok. gui red only on
  TestMainWindowCorners/macOS_26_SDK (#3949, open, red on macOS 27); this
  touches no GUI file.
2026-10-30 06:00:55 +08:00
yetone 45fce0495d sessions: a poll's session list is sorted and gathered in slices made for it (#2278)
listSessions kept each group's latest time in a map and sorted a key
slice that looked it up; the /api/sessions handler grew its native-key
map and its output slice by appending. Under 80s of polls while a
session was written (ab17, v0.1.1978 with stats kept) those were 72 MB
(latest map), 129 MB (listSessions out) and 139 MB (gui out.Sessions)
of 5.4 GB allocated. The groups are now one slice of key and latest,
sorted once, and every output is made at its size.

Run at this head (mote, Go 1.26.8):
- GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions/
  ./internal/gui/ ./internal/usage/: clean.
- go test -timeout 45m ./internal/sessions/ ./internal/gui/: sessions
  ok; gui red only on TestCoreScriptBudget (#4133, red on main since
  a4e929212) and TestMainWindowCorners/macOS_26_SDK (#3949, red on
  macOS 27), neither touched here.

Rebased onto origin/main f982e46f2 after the run above; the three #2278
commits were run again together there (see the last commit's body).
2026-10-30 05:57:11 +08:00
yetone af8f3a9399 sessions: a new install reads no agent's session history until the user allows it (RustCats on X)
RustCats on X: a fresh magpie showed every agent's session history on
the Sessions page before anyone agreed to it, and asked for a per-agent
choice instead.

- sessions.Reads(agent) (internal/sessions/access.go) is the one gate,
  from settings.SessionReads {Asked, All, Agents}. Every lister asks it,
  the aggregators (allFiles, callFilesWith, callSourcesWith,
  traceLineFiles, wslFiles, DesktopDataDirs) filter by it again, and
  readers of an already-listed session (TranscriptOf, ContentOf,
  SearchSession, SubagentTranscript, CarryOver, ReadCallSource) return
  ErrNotRead, so a cache from before a switch was turned off goes no
  further. The Sessions list, stats, /api/sessions/overview, the call and
  trace indexes, Usage's agent-file calls and the Codex/Pi title readers
  all pass it.
- SettleReads decides once and saves: an install with sessions.json or
  a calls-v* cache read sessions before and keeps all on; a fresh one
  reads none, not asked. A saved value is never replaced; save, sync and
  restore keep it (KeepOwn); only SetSessionReads writes it. An
  unwritable settings.json reads nothing this run.
- GUI: GET/POST /api/sessions/reads. While not asked, the Sessions page
  shows a consent card: each agent found (by a stat of its folder only)
  with a switch, Allow selected and Allow all. Settings > Privacy >
  Agents' session history has "Agents found later" and a row per agent.
  Strings in en, zh, zh-TW, ja, de.
- CLI: magpie sessions read [on|off all|<agent>...]; magpie sessions
  says on stderr when nothing is allowed yet; the TUI's empty Sessions
  page says how.

Read either way, because none of it lists or shows a session: the
gateway's own usage ledger, its projections and the conversations it
recorded (magpie's own records, so usage and cost keep working); the
agents' config and sign-in files; Claude Code's and Codex's
history.jsonl last-used time and a session file's mtime for a quota's
first use; Codex's newest rollout's last line before magpie restarts
Codex (codexTurnOpen).

Tests: TestFreshInstallReadsNoAgentUntilAllowed,
TestSettleReadsKeepsWhatWasThere, TestSessionReadsRoutes,
TestSessionsRead, TestSessionsNotAskedSaysHow, sessions-reads.test.cjs
(26 cases: consent and Settings in 5 languages, Chromium and WebKit,
390 to 900 wide).

Run on mote:
- full Go suite (gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui,
  GOOS=windows go vet, go build, go test -timeout 45m ./...) at this
  change on 8c63c5b78: 79 packages ok; internal/gui red on
  TestSettingsSaveKeepsWhatItDoesNotSend (mine: SessionReads is written
  by SetSessionReads only, the test now sets it so; green after) and
  TestMainWindowCorners (the same on origin/main c1da9ccda, #3949).
- whole GUI suite (make test-ui, concurrency 2) at this change on
  8c63c5b78: 14985 tests, 276 failed in 44 files. Mine: i18n-keys
  (comments named "Allow all"/"Allow selected"; lowercased) and
  account-discovery (read the last Privacy heading; now the one above
  its list); both green after. The 44 files again on origin/main
  c1da9ccda: 36 red there too (#4304, with #3218, #3412, #3414, #3795,
  #4120, #4125). stays-strict green alone; gateway-key-models webkit red
  1 of 3 alone on main too; plugin-github de 440 red on main (#3218).
- at the pushed head (rebased on cd10dfbe6): go build ./...; go test
  internal/sessions, settings, cli, tui ok; internal/gui
  TestSettingsSave*, TestSessionReads*, TestSessions* ok; i18n-keys,
  account-discovery, sessions-reads: 62 pass, 0 fail.

Broken by hand:
- the aggregator filter off with the leaf gates on: green (the leaf
  gates hold); both off: TestFreshInstall red on List, Agents, Calls,
  CallSources, traces, stats, TranscriptOf and Search.
- consentApplies=false and Settings' old save({all}) without the rows:
  all 13 Chromium cases of sessions-reads red.
- sessNothing's hint removed: TestSessionsNotAskedSaysHow red.

Real binary in a sandbox HOME on mote (removed after): a fresh
`magpie sessions` is empty with the hint on stderr; `sessions read`
says not asked, claude off; `read --help` prints usage and saves
nothing; `read on claude` lists the one session; `read off all`
empties it again.

Not tried: the GUI and real app on Windows and Linux; WSL agents in the
consent list (WSL distros are not looked into; Allow all covers them);
a fresh install of a signed release build.
2026-10-29 23:56:05 +08:00
yetone 168dcf455d sessions: a hold counts holds, not times (#4114, #4177)
heldFiles reused a listing taken after the latest hold began, judged by
time.Now(). On Windows two time.Now() a moment apart can be equal, so a
hold begun in the tick a listing was taken in read that older listing
as its own: TestOneListing red. Its t.Fatalf came before done(), so
the package-global hold stayed set and every later test read a stale
listing: TestPurgeOne, TestPurgeAll and TestUnchangedPackedNotReadAgain
red, and TestShareListing / TestReadNotHeldByAnotherRead waited forever
(the 45m package timeout in #4114 and #4177).

- held.gen counts holds begun; a listing carries the gen it was taken
  under and is reused only under the same gen. No clock is read.
- holdsEnd(t) ends any hold a test left, so one red names itself and
  doesn't take the package down with it.
- TestShareListing, TestReadNotHeldByAnotherRead and
  TestReadWaitsForAFirstReadUnderWay select on the other channel too,
  so a missed listing fails at once instead of hanging.

Run (Windows: win-run on xiaomi-gpu; macOS: mote-run; Linux: wsl-run):
- Windows, old one_listing.go: TestOneListing red alone. Fixed:
  TestOneListing and TestShareListing -count=500 green.
- Windows, fix without holdsEnd: the cascade comes back with each test
  red and named, no hang. With it: internal/sessions green but for
  TestAgySessions/TestAgyRowOnly (#4115, red at main too).
- macOS and Linux: internal/sessions ok, at the rebased head too.
- GOOS=windows go vet ./..., GOOS=linux go vet -tags nogui ./..., go vet
  ./... on mote: ok. gofmt -l clean.

Broken by hand: the time comparison put back (red on Windows, above);
holdsEnd removed (cascade, above).

Not tried: the full go test ./... on mote (six other suites were
running there; owner rule: don't wait behind it).

At the rebased head (on origin/main 033b17baf): Windows internal/sessions
red only in TestAgySessions/TestAgyRowOnly (#4115), internal/testenv ok,
gui TestGatewaySessionHistoryAndCalendar + TestUsageLedger*Routes ok;
macOS and Linux internal/sessions and internal/testenv ok.
2026-10-29 15:31:36 +08:00
yetone 9474eaf9cb sessions: Raft's Pi agents' sessions are listed as Raft's, with their prompts, calls and delete
Raft (slock's raft-computer) runs its agents on Pi and keeps each one's
Pi SDK session files in that agent's folder: <slock>/agents/<id>/
.pi-sessions/<ts>_<id>.jsonl, or .builtin-sessions/ for its built-in
runtime. <slock> is $SLOCK_HOME or ~/.slock (%USERPROFILE%\.slock on
Windows, the distro's ~/.slock under WSL). Read from raft-computer
1.0.14's PiDriver (buildPiSessionDir), BuiltInDriver and
resolveSlockHome, and a read-only listing of ~/.slock here.
runtime-sessions/ holds handoff notes, no sessions, and is not read.

- The Sessions page lists them as Raft's (agent "raft", in agent.Clients'
  others), titled and opened with their prompts as Pi's are.
- Their calls count on the Usage page as Raft's; calls through magpie
  stay the gateway's, as Pi's do.
- Raft's Pi uses the user's own ~/.pi/agent, so a request it sends
  through magpie reaches the gateway as Pi's under the same session id.
  sessions.GatewayKeys gives a Raft session both "raft|ID" and "pi|ID",
  so the gateway's copy is not listed twice nor counted twice (Merge,
  stats, NativeIDs, the GUI's Via).
- Delete and restore work as Pi's: the one file goes to the trash, and a
  folder beside it is left (the agent's workspace is not the session's).
  A session written in the last minutes is refused as active.
- No resume command, no carry and no trace export: Raft starts its own
  agents, and nothing outside it can resume one.
- SLOCK_HOME is passed through agentenv like the other agents' homes.

Run (at 958ad9f10 on e61e10535):
- mote (macOS): -run 'Raft|TestPi|TestDirs|TestVars|TestFolderVars' in
  sessions and agentenv: ok, and red for each break below. A full
  go test ./... was started there; at load ~300 from other sessions'
  suites it printed only magpie and internal/access (ok) before mote
  stopped answering (host down), so no full macOS record exists.
- mote (macOS), rebased on 5d24bc6cc: go test -count=1 ./internal/sessions/
  ./internal/agentenv/: ok (sessions 495s, agentenv 1.1s). agent and gui
  were not run in full on macOS.
- mote: GOOS=windows go vet of sessions, agent, agentenv, gui; GOOS=linux
  go vet of sessions, agent, agentenv: ok.
- Windows (win-run): agentenv ok; -run 'Raft|TestPi|TestDirs' in
  sessions ok. The full sessions package hit its 30m timeout after
  TestOneListing's red (#4114) and the Agy reds (#4115, #4177). agent
  and gui reds (Hermes, WorkBuddy, Lody, Qoder/Copilot plugin folders,
  Codex keychain, ClaudeDesktop language, Aside, InstallWithoutNode,
  DesktopExec, AionUi, ImportStatus, UpdateThatWontStart,
  GatewayHeldByAContainer, GatewaySessionHistoryAndCalendar): each run
  again at origin/main c1660481c on Windows and red there too, except
  TestHermesProfilesFollowMagpieModel which passed there alone; it is
  #1388's Hermes model rewrite, which this change does not reach.
- Linux (wsl-run): sessions ok, agentenv ok. agent's TestInstalledVersion,
  TestGrokInstalled, TestCursorFolderFromTheEditorIsNotTheCLI and
  TestOmpDetectedWithPiDir are red at origin/main c1660481c too (#4033,
  #3548). gui does not build there (no gtk4/webkitgtk-6.0 in the distro).

Broken by hand, each red, then restored: Raft's listing removed; the
"pi|ID" key dropped from GatewayKeys; the folder-beside check reverted to
Pi's absence; $SLOCK_HOME ignored; Raft's calls left out of piCallFiles;
NativeIDs without Raft; stats' native keys without "pi|ID".

Not tried: with real Raft. No agent on this machine has run on Pi, so
the fixtures are Pi 1.1.0's own files (testdata/pi-calls, testdata/pi)
placed in Raft's folders. The GUI was not run in a browser: no JS
changed, Raft's name and icon come from agent.Clients. Raft's icon is the
generic one.
2026-10-29 15:29:30 +08:00
yetone f594b452e3 sessions: a Claude fork after a compaction is a branch under its session, read from the start
neo_o11 (Discord, after v0.1.1809): one conversation still showed as ~9
rows with the same title, and opening one showed "Session start" and a
single turn.

Cause, reproduced with real Claude Code 2.1.312 in a sandbox
CLAUDE_CONFIG_DIR: the reporter's session was compacted, then forked
several times (headless --fork-session per task, or /branch). Each fork
starts at the compact boundary and summary, and copies the session's
last reply under the same uuid. So every fork holds the original's
Leaf, and ccCopies hid the original as a fork's copy, though it alone
holds the conversation before the compaction. Each fork had a Leaf of
its own and stayed a row, with the copied title. Opening a fork read
its own file: the summary and one turn.

Fix:
- cc_copies.go: ccFamily returns copies and branches. A file is a
  copy of another only when that one holds its Leaf and its Root too,
  so a file with what came before the other's start is never hidden.
  The members of a family left visible pick a head (holds the other's
  Root, then named in the other's forkedFrom, then the earlier start,
  then the lower key); the rest are branches of it.
- sessions.go, manage.go: a branch has role "branch" and
  parent_session = its head, in List, Find/get and ListAgent.
- transcript.go: a branch's transcript is its head up to the fork
  point (the last line of the head holding one of the branch's
  uuids), then the branch's own lines. Search still reads its file.
- stats.go: a branch counts only its own lines, so tokens are not
  counted twice.
- GUI sessions plugin: the fold under a session names branches apart
  ("2 branches · 1 subagent"), in en/zh/zh-TW/ja/de.
- Fixtures in testdata/claude-forks/tasks*.jsonl are trimmed from real
  2.1.312 output: a session compacted once, two --fork-session task
  forks and a /branch copy with forkedFrom.
- docs/subsystems/gateway-sessions.md: copies and branches.

Run:
- go test ./internal/sessions -run 'TestClaude|TestQoder|TestMergeExternal'
  on mote, at e15b2277c before the rebase: ok. Red on the old code (cc_copies/sessions/transcript/stats
  restored from HEAD~): 5 tests failed (the original hidden, only forks
  as rows; a branch's prompts starting at the summary).
- Broken by hand, each red: dropping the Root rule (3 compacted-fork
  tests), ignoring forkedFrom (TestClaudeBranchNamesItsSession),
  turning branchTranscript off (3 tests), counting a branch whole in
  stats (90 tokens, not 80).
- GOOS=linux (-tags nogui), windows and darwin go vet, at e15b2277c: ok.
- Full go test ./... -timeout 45m at this head (71124a2d7 on c1660481c),
  on the Linux box (mote was at load 300 with six suites): every
  package ok, sessions 144s, gateway 987s, except: ., internal/cli and
  internal/gui didn't build (no gtk4 there), ok again with -tags nogui;
  internal/agent's TestInstalledVersion, TestGrokInstalled,
  TestOmpDetectedWithPiDir and TestCursorFolderFromTheEditorIsNotTheCLI,
  the first three red the same at origin/main c1660481c there, all four
  in #4033 (#3548, #3141). Nothing here touches internal/agent.
- GUI on the Windows box, both engines, every language:
  sessions-subagents + i18n-keys 40/44, the 4 reds 5s nav-click and
  goto timeouts in WebKit; WebKit alone again 20/20. Every
  session*.test.cjs file (32): 381/399. Its six red files run again at
  origin/main c1660481c and here, one at a time: calendar-fill zh red
  on both (#1314), sessions-today WebKit zh red here only, the
  reads.n race of #1315; the rest green on both.

Not tried: get()'s path for a session beyond the listing's 200 has no
test of its own; the TUI and CLI lists show a branch as a row of its
own, not nested; an uncompacted fork that went on has no real
forkedFrom fixture (TestClaudeBranchNamesItsSession injects one).
2026-10-29 15:03:18 +08:00
yetone d5eac64f23 sessions: a deleted Codex session leaves the Codex app's list too
zhuddan (Discord, Codex app 26.1023): a Codex conversation deleted in
magpie went on showing in the Codex app. The app lists threads from its
own catalog, <CODEX_HOME>/sqlite/codex.db (codex-dev.db for a non-prod
build), table local_thread_catalog, and drops a row only on the
app-server's thread/deleted or thread/archived. After its first full
sweep it takes in only threads newer than its watermark, so a row of a
thread whose rollout magpie moved to its trash stayed.

Delete now does what the app does on thread/deleted: the local host's
rows of threads whose rollout is gone from that Codex folder's sessions
and archived_sessions (as Codex's state database names them; neither
the file nor its packed twin there, and a file that can't be looked at
counts as there) are deleted and catalog_revision raised, in one
BEGIN IMMEDIATE transaction that waits for the app's own. The rows go
into the trash note (codex_catalog) and Restore puts them back, since
the app wouldn't take in a thread that old by itself.
/api/sessions/manage does the same once a run (TidyCodexCatalog) for
threads deleted before this release.

Run (Windows, win-run, go1.26.8):
- go test -count=1 -v -timeout 25m ./internal/sessions/: 339 PASS,
  including TestDeleteForgetsCodexAppCatalog,
  TestTidyCodexCatalogForgetsEarlierDeletes and
  TestTidyCodexCatalogKeepsWhatItCantJudge. Red: TestAgySessions,
  TestAgyRowOnly (#4115), TestOneListing and TestShareListing hanging
  the package (#4114). The same four are red at origin/main bc247a8cc
  on the same box, run alone. A second run also had TestPurgeOne,
  TestPurgeAll, TestUnchangedPackedNotReadAgain red and
  TestReadNotHeldByAnotherRead hanging, and internal/gui
  TestGatewaySessionHistoryAndCalendar red; all the same at
  bc247a8cc (#4177).
After the rebase onto origin/main (mote, go test -count=1 ./internal/sessions/ ./internal/gui/): sessions ok; gui red only in ten AppKit window tests killed at 30s (TestPanelCloseHidesIt, TestMainWindowCorners and others), mote's pboard being down (#4125).
Broken by hand: forgetCodexCatalog returning nothing turns
TestDeleteForgetsCodexAppCatalog and
TestTidyCodexCatalogForgetsEarlierDeletes red.
Not tried: the real Codex app (its catalog is in the owner's live
~/.codex, which sessions never touch); the schemas in testdata are
Codex 26.1023's.
2026-10-29 13:17:17 +08:00
yetone a54e336e44 sessions: Desktop's Code tab in its 3p mode is Claude Desktop's, not Claude Code's
cybercaius (Discord #help) runs Claude Desktop through magpie's gateway
and saw Desktop's work listed under another agent. Desktop set to a
gateway is in its third-party inference mode, and Desktop 2.7032 then
starts its Code tab's Claude Code with CLAUDE_CODE_ENTRYPOINT
"claude-desktop-3p" (its nK: type "3p" -> "claude-desktop-3p", else
"claude-desktop"; the value is in Claude Code's own entrypoint enum).
The calls reader (calls.go) and the trace reader (traces_claude.go)
only took "claude-desktop", so every call from such a session was
counted as Claude Code's. Both now ask one desktopEntrypoint.

This is what Desktop's transcripts say. The gateway's own attribution
of a live request (agentOf, by key then User-Agent) is not changed:
with Desktop's own key magpie-claude-desktop it already names Desktop,
and the reporter's misattributed title request was not reproduced.

Run on mote: go test ./internal/sessions -run
'TestCallsDesktop3pCodeTab|TestClaudeTraceSubagentsShareSessionWithoutIDCollisions|TestCalls'
ok. Broken by hand: both readers back on == "claude-desktop" ->
TestCallsDesktop3pCodeTab and the trace test's claude-desktop-3p case
fail. Rebased on origin/main bc247a8cc: go test -tags nogui
./internal/sessions on the Linux box (WSL magpie-desktop), the whole
package, ok; go vet for Linux and Windows ok.
Not tried: a real Desktop 3p session's transcript (the value is read
from Desktop's asar, not captured from a file).
2026-10-29 12:42:52 +08:00
yetone bc247a8cc4 sessions: the Sessions page answers before a first read of a long history
hey_boyce on X: "会话tab等的时间有点长", the page standing on its
skeleton rows on its first open. /api/sessions/manage read every file it
had no usable parse of whole before answering: the agent shown, and every
agent with a gateway session for its ids (Codex's 52 GB too while Claude
Code's page was shown). That is every file after a first start, a
cacheVersion bump, or a Claude Code or Codex file whose kept parse can't
be read on after a restart. 536a98316, 936bdccfa, 926ef769f, f193c3865
and efd1b697e made polls and warm reads cheap; this is the cold one.

Now Manage reads at once only what is cheap (a parse that has only grown).
Once more than 32 MB (quickBytes) would be read whole, those files are read
behind the answer, as Stats and List read them, and their rows stand on the
parse kept or on a glance: the file's first 256 KB with its agent's own line
parser (id, folder, first prompt, start) and, for Claude Code, the titles in
its last 64 KB, with the file's time as its last activity. Such a row has
pending: true and no counts. The Sessions page asks again every 1.5 s while
any row is pending, and redraws only the list, so the filter keeps its focus
and the folders shown stay. A glance is never saved in the index (savable),
and a refresh never takes it as a parse (parsed). A small store is read whole
as before, so its rows come complete the first time.

Measured on the Linux box (magpie-desktop), a sandbox HOME with 1,200 Claude
Code files and 600 Codex rollouts (1,985 MB, 2% 20 MB, 10% 2-8 MB) and one
Codex gateway record. Each mode ran in a fresh process, twice, origin/main
449231c19 against this change:
- no index, Claude Code's page, first answer: 1.94 s / 1.83 s before,
  282 ms / 343 ms after;
- no index, Codex's page after it: 8.93 s / 0.73 s before, 1.63 s /
  1.73 s after;
- no index, every row read whole: 10.9 s / 2.6 s before, 2.0 s / 2.1 s
  after;
- with the index: Claude Code 51-61 ms before, 49-51 ms after; Codex
  700-714 ms before, 718-800 ms after.
On the owner's real store (13 GB of Claude Code and 52 GB of Codex files,
counted read-only), a cold first answer read all 65 GB. A glance reads at
most 320 KB a file. The fixture was in the page cache, so these numbers
undersell a cold disk.

Tests:
- TestManageAnswersBeforeFirstReads holds every whole read on parseHook.
  On this change Manage answers with pending, glanced rows and Codex's ids,
  leaves no glance in the cache or a save, and answers a second ask while
  the read is under way. After the read, the rows are counted, no longer
  pending, and have the folder and title the glance showed. Broken by hand
  (Manage back on plain refresh): red at its 30 s fail-safe, "Manage
  waited for the whole read (2 files being read)".
- sessions-pending-fill.test.cjs: pending rows show at once, are asked
  for again on the page clock and filled in with the filter still focused
  and typed into, and then no more asks.

What was run:
- mote: go vet ./internal/sessions ./internal/gui; go test
  ./internal/sessions ok.
- go test ./internal/gui on mote at load 35-67, under another session's
  full GUI suite: TestCoreScriptBudget was red on origin/main too (#4133,
  fixed since in 3959192e9; this change adds no core bytes). Ten
  real-window AppKit tests were killed at their deadlines (#2645, #4125).
- Linux (wsl-run): gofmt, go vet -tags nogui, go test ./internal/sessions
  ok. go test -tags nogui -timeout 40m ./internal/gui (1021 s): red only
  in TestCoreScriptBudget (#4133, the base's) and
  TestRestartHandsTheGatewayOver, a request reaching the old pid after
  the handover (#4167, not on this path). Rebased on aad6546cd, both
  pass 3 of 3 with -count=3. GUI files sessions-pending-fill,
  sessions-manage, sessions-manage-paging, sessions-folder-paging,
  sessions-search and sessions-toolbar in Chromium and WebKit: 44 of 44
  pass.

Not run:
- The full go test ./... suite and the whole GUI suite: mote went
  unreachable mid-run, and WebKit hung there on existing tests too (#4125).
- No real account: the bench uses a generated store.
2026-10-29 12:12:30 +08:00
yetone 536a98316d sessions: a poll over unchanged files gets the stats the last one read (#2278)
The Usage page asks for its range every 10 s and the Sessions page for
7, 30 and every day every 15 s. Each read put every session of every
range together again, though between two polls the files mostly
haven't changed: statsReadAll allocated ~1.1 GB per 80 s of polling,
a fifth of all magpie allocated.

statsKept keeps each range's Stats (at most 8 ranges) and the native
keys, with what they were read from: every listed file's path, key,
agent, size, mod time, main/read-only, WSL distro and its parse pointer
(a published parse is never written; a changed file gets a new one),
today, and the cache generation. It also keeps the answers the read
got from the prices, Codex's thread names and Claude Desktop's names,
and asks them again before it hands anything out. When any of these
differ, everything is read again. The listing and the refresh of
changed files still run on every poll.

MergeExternalStats wrote into the Stats it was given (a day's usage
rows, an append into spare room in Sessions, sorts in place). It now
copies whatever it changes, so a kept range is never written.

What this doesn't help: while an agent is writing a session, every
poll sees a changed file and reads everything again. Reading only the
changed sessions is the next change.

Run at the pushed head on mote:
- GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions/
  ./internal/gui/: ok.
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/
  ./internal/usage/: sessions ok, usage ok, gui red only
  TestMainWindowCorners/macOS_26_SDK (#3949, open, same as main).
- New tests: TestStatsKeptBetweenPolls (the same backing array on an
  unchanged poll; a grown file and a price change are read in),
  TestStatsKeptNewDay, TestStatsKeptRangesBounded,
  TestMergeExternalStatsWritesNoInput. TestStatsAllRangesOnePass now
  forgets the kept ranges before each single read.
- Broken by hand, each red: keptFor always missing
  (TestStatsKeptBetweenPolls, "put together again"); the price check
  dropped (repriced cost unchanged); MergeExternalStats without its
  copies (TestMergeExternalStatsWritesNoInput).
- Real data (a copy of the owner's history, ~34k sessions), v0.1.1978
  against this: /api/sessions/stats?days=0/7/30 and both overviews
  asked 4 times 12 s apart, each pair byte-identical (1.97 MB for
  days=0).
- A/B, 80 s of GUI polling, v0.1.1978 against this: allocated 5512 to
  4480 MB, statsReadAll's share 1108 to 261 MB (the listing);
  GC 3.90 to 3.42 s, madvise 1.05 to 0.61 s, CPU 28.6 to 25.3%, avg
  RSS 1061 to 1019 MiB. mote's load was 20-40, so latencies aren't
  compared. The A/B binary was built before the 8-range bound was added.
- Rebased onto b9f1fcddd (redact only), then again: vet on the three
  systems over sessions, gui and redact, and go test of sessions, usage
  and redact: ok.
- Rebased again onto a4e929212 (GUI context map only), then at this
  head: the same vet and tests ok. TestCoreScriptBudget is red at
  a4e929212 itself (#4133); this commit touches no GUI file.
2026-10-29 08:52:32 +08:00
yetone f193c3865f sessions: a stats share keeps its days and models in slices, not maps (#2278)
statsOfRange made each session three maps per range on every poll (its
models, the dates it counted and its per-date shares) and a list of
the range's files first. A session has few models and few days, so
they are small slices now, and the files are filtered as they are
read. The output is the same: models are summed in name order and
listed by tokens, then name, as before.

Measured on mote (Usage stats polled every 5s with gateway feed, heap
diff 120s to 200s, A/B against v0.1.1971 2f5548371, load 40 to 73):
statsOfRange 870MB -> 417MB and statsReadAll 1578MB -> 1103MB per 80s,
total 7787MB -> 6386MB, while this binary answered 33 rounds of polls
to the other's 26. Peak RSS 1020 -> 976 MiB. CPU and latency are not
comparable at that load. /api/sessions/stats?days=0/7/30 and
/api/sessions/overview are byte for byte the same from both binaries
on the bench's copy of real data (1.97MB, 156KB, 656KB, 21KB).

Rebased onto fae438b4a (an agent change, no sessions files) and run
again at this head, on mote:
GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions/
./internal/gui/ ./internal/agent/ ok; go test -count=1 ./internal/sessions/
./internal/usageapi/ ok. Before the rebase, on magpie-desktop (wsl-run): go test -tags
nogui -run 'Stat|Overview|Session' ./internal/gui/ ./internal/sessions/ ok.
Not run: the full suite.
2026-10-29 07:38:36 +08:00
yetone 2f55483718 sessions: a stats share makes its tools and skills maps only when a day has some (#2278)
statsOfRange made four maps (tools, skills, skillLast and a day's
tools) for every session of every range on each poll, and most
sessions' days use no tools or skills. They are made now on the first
day that has one.

Measured on mote (Usage stats polled every 5s with gateway feed, heap
diff 120s to 200s, A/B against 905166d78): statsOfRange allocated
894MB against 938MB per 80s. Peak RSS and CPU in that A/B are not
comparable (the main leg ran under load 66.8% CPU).

Run at this head (905166d78 + this change), on mote:
GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions/ ok;
go test -count=1 ./internal/sessions/ ok. On magpie-desktop (wsl-run):
go test ./internal/sessions/ ok.
Not run: the full suite.
2026-10-29 07:25:58 +08:00
yetone 905166d786 sessions: Codex identities are kept while no rollout changes (#2278)
Every Sessions and Requests poll built the Codex thread identities again
over every rollout (CodexIdentities, CallSourcesAndCodexIdentities, List,
Stats, ListAgent, Get), though nothing had changed since the last poll.
codexIdentitySnapshot now keeps the identities it built for the last four
file lists, with what each Codex rollout gave them from: its key, the
cached identity's value and whether it conflicts. A list whose rollouts
give the same is handed the kept map. The maps are now shared, so only
read: CodexIdentities' comment says so, and the old test that deleted from
one is replaced by TestCodexIdentitiesKeptWhileNoRolloutChanges.

Run at this head (5637cca14 + this change):
- mote: GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions/
  ./internal/usage/ ok; go test -timeout 45m ./internal/sessions/
  ./internal/usage/ ./internal/usageapi/ ok.
- magpie-desktop (Linux): the same three packages ok.
- Broken by hand: madeFrom not comparing what a rollout gave, so a
  changed rollout got the kept map: the new test is red ("a rollout
  changed and the identities kept from before were handed out").
- A/B on mote, the #2278 bench (real history copy, 10 endpoints polled
  every 5s, 4 gateway calls/s from 60s), v0.1.1968 vs v0.1.1968 + this,
  load ~27: codexIdentitySnapshot's allocations 280 MB -> 0 per 80s;
  total allocated 7942 -> 7538 MB per 80s; peak footprint 761 -> 733 MB;
  madvise 11.0% -> 9.2% of CPU samples; avg CPU 40.8% -> 39.3%. Poll
  times within the box's noise (0.43s vs 0.44s mean).

Not run: the full suite and the GUI suite (no GUI change).
2026-10-29 07:08:23 +08:00
yetone fa2dfc1458 sessions: the page's 7, 30 and all-time stats are read again in one pass (#2278)
statsFor keeps each ?days range the Usage page asks for and reads it
again behind the page once it is 10s old. Each of the three ranges
(7, 30, 0) was its own combinedSessionStats: a listing of every Claude
Code and Codex file, a refresh, the Codex identities and task titles,
every session assembled for the native keys, and the ccCopies, all
identical whatever the range. With 25k Codex rollouts that was ~4.2s of
CPU a minute on a polled page.

Now a stale range takes every other stale range with it, and
statsReadAll does the shared part once and sums each range from it
(statsOfRange). The sessions assembled for the native keys are reused
for each range's list instead of assembling them again.

Rebased onto b4267de59; the tests and vets below ran again on mote at
the rebased head, same results. The A/B ran before the rebase:
- TestStatsAllRangesOnePass (new): ranges 0, 1, 7, 30 from one pass
  are each DeepEqual to statsRead of that range alone, and the files
  are listed once.
- GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions
  ./internal/gui: clean.
- go test ./internal/sessions ./internal/usage: ok. ./internal/gui: ok
  but for TestMainWindowCorners/macOS_26_SDK, the macOS 27 red in #3949
  (titlebar, untouched here).
- A/B on mote, sandbox HOME with a copy of the real 115MB usage.jsonl
  (240k rows) and 25k Codex rollouts, the page's 10 reads every 5s and
  4 appends a second, 240s each, v0.1.1959 (d7e9c3745) then this:
    stats refresh (statsFor.func1) CPU  4.17s -> 2.22s a minute
    process CPU in the 60s profile      33.8s -> 30.7s
    stats?days=0/30/7 mean              0.76/0.77/0.78s -> 0.39/0.36/0.39s
    /api/sessions/overview mean         1.29s -> 0.72s
    /api/sessions mean                  2.01s -> 1.37s
    every read's mean                   0.99s -> 0.62s
    peak RSS                            985 -> 1033 MiB (mote at load
                                        ~35 from other sessions; peak is
                                        next)
2026-10-29 05:29:36 +08:00
yetone 3ec9babe7d sessions: the overview points to the sessions it sums up, not copies (#2278)
Stats.Overview copied every Summary (~400 bytes) into its working slice,
then cloned that slice once per Top ranking. Over 34k sessions the
Sessions page's poll allocated ~1.5 GB in two minutes this way while an
agent worked (alloc profile of v0.1.1928 on mote: `in = append` 958 MB,
slices.Clone 557 MB). It now ranks pointers into st.Sessions and copies
only the k sessions each ranking keeps. shapes, toolUse and skillUse take
the pointers.

TestOverviewCopiesOnlyItsTop: a second Overview over 5000 sessions
allocates at most half of their Summaries' size, and its count and
rankings are what they were. Red on the old code (14,923,144 bytes over a
1,020,000 bar), green on the new.

A/B on mote (34,040 session files, 240k-row usage.jsonl, the feed run
of run2278c.sh: 230s, feed from 60s, Usage and Sessions pages polled),
v0.1.1928 code vs this change. mote's load was 47 to 66 from other runs
throughout, so the numbers are noisy:
  avg CPU after the feed starts  122.8% -> 69.4%
  heatmap poll mean               6.97s -> 4.84s
  all polls mean                  3.11s -> 2.16s
  footprint peak                 685.6M -> 626.1M
  footprint at the end           402.8M -> 337.5M

Run on mote, at base b5d2858f4:
  go test -count=1 -timeout 45m ./internal/sessions/ ./internal/usage/
    ok (30.9s, 18.0s)
  go test ./internal/gui/: FAIL only in TestMainWindowCorners, the open
    macOS 27 red #3949
Rebased onto origin/main 7a7931833 (no change to internal/sessions), and
run again at the pushed head on mote:
  go test -count=1 -timeout 45m ./internal/sessions/ ./internal/usage/
    ok (16.8s, 16.1s)
  GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions/
    ./internal/usage/ ./internal/gui/ ok
2026-10-29 00:48:47 +08:00
yetone 84a6a2c420 sessions: a range's session list is made to its size (#2278)
statsRead grew out.Sessions by append, so 34k sessions' list (Summary
is ~480 bytes) held up to a quarter more than its rows, 19.4 MB in the
heap after a cold start at #2278's scale, and copied itself through
every size on the way. Each range statsFor keeps holds its list. It is
now made with room for the range's sessions (shares holds only those
with a day in range), and Keys with room for the list.

TestStatsHoursAndSessions checks the list and keys hold their rows and
no more. Broken by hand (the make removed) it failed with "3 sessions
held in 4".

Run at this change (mote): go vet -tags nogui of internal/usage and
internal/sessions for linux, windows and darwin ok; go test -tags nogui
./internal/usage ./internal/sessions ok.
Rebased onto 60561129f and run again at the pushed tree: the same
three packages (usage, sessions, codexcat) ok.
2026-10-28 20:53:36 +08:00
yetone 7e58591dcf sessions: Grok Build's tool calls and skills are counted (MaxMooreMy on X)
MaxMooreMy on X, after v0.1.1870 counted Codex's skills: "grok build 好像
也不支持。grok build 的工具调用啥的也没采集到". Usage > Sessions showed no
tool use and no skills for Grok Build.

Cause: parseGrok only ever read the first prompt and "turn_completed"
usage from updates.jsonl; nothing counted a tool call or a skill.

What Grok Build writes (grok 1.0.67, run headless in a sandbox
HOME/GROK_HOME, never the live ~/.grok): each call is one
"sessionUpdate":"tool_call" line, its name in _meta["x.ai/tool"].name
(also the line's title), followed by "tool_call_update" lines for its
progress. Grok has no skill tool: its prompt lists every SKILL.md by
absolute path, and the model calls one up with read_file (rawInput
.target_file) or a run_terminal_command, as Codex does. A user's
/<name> prompt is written to updates.jsonl as typed; the skill's text is
put into the prompt only in chat_history.jsonl (<skills_referenced>).
An unknown /nonexistentzz is written the same way, and Grok's own
commands (/compact) carry _meta.hostTurn.

Fix: a tool_call line counts its tool, and the skills its read_file path
or command reads (skillReadsIn, the loop cxSkillReads already had, now
shared). A non-hostTurn /<name> prompt in the main session counts skill
<name> when a skill or command of that name exists where Grok finds them:
.grok/.agents/.claude/.cursor skills/<name>/SKILL.md or commands/<name>.md
from the session's cwd up and in the home folder, $GROK_HOME/skills and
commands, and $GROK_HOME/bundled/skills. cacheVersion 26 so kept parses
are read again.

Tests: TestGrokToolsAndSkills runs on four real sessions captured from
grok 1.0.67, updates.jsonl and summary.json byte for byte (only the
encoded cwd folder name shortened): a cat + a read of greet-user's
SKILL.md (2 tools, 1 skill), /greet-user (1 skill), /nonexistentzz and
/compact (none, with a "compact" skill present). TestGrokSlashSkill
covers repo-level .claude/skills, cwd .grok/commands, bundled skills,
~/.agents/skills, paths, "..", and mid-text slashes.

Run (on mote, through mote-run, at this tree on origin/main 27bf14790):
- new tests at the old grok.go/codex.go/sessions.go: red ("tools 0 []")
- hostTurn guard broken by hand: red (/compact counted as "compact")
- go test -count=1 -timeout 45m ./...: 76 packages ok; one red,
  internal/gui TestMainWindowCorners/macOS_26_SDK on mote's macOS 27,
  already filed as #3949 and unrelated (sessions isn't in its path)
- go vet, GOOS=linux go vet, GOOS=windows go vet ./internal/sessions: ok
- gofmt -l internal/: clean

Not tried: skills from Grok plugins/marketplace (installed-plugins was
empty here, layout unknown), so a /<plugin skill> isn't counted; a /name
skill whose folder was deleted since isn't counted when the file is read
again; the TUI (only headless grok -p sessions were captured); Windows
and Linux runs of the Grok CLI.
2026-10-28 20:28:27 +08:00
yetone b3edcabf29 sessions: a Claude copy's subagents and what only it holds count in the usage stats
beautiful2674 (Discord): after updating from a 0.1.17xx to a 0.1.18xx,
Usage's total over All was ~200M tokens lower, with the same filters.

Since f4762e921 (v0.1.1803) a Claude Code file whose last message
another file holds is a copy, and statsRead left every file of the copy's
key out. Claude Code 2.1.312's `--resume --fork-session` (and /branch)
copies only the conversation along its last message, so that dropped
spent tokens no other file holds:
- the subagents the first session ran: their files stay in the first
  session's subagents folder only (a sandbox run of 2.1.312 against a
  fake API: the fork's folder has none);
- what came before a compaction, when the branch was made after /compact
  (it starts from the summary) and went on while the session didn't:
  the session is then the copy, and its whole pre-compaction history was
  dropped;
- messages /rewind left on another branch, and sidechain messages an
  older Claude Code wrote into the session's file.
Part of the drop is right: before 1803 the copied messages were counted
in both files.

A copy now adds to the session it is kept in: its subagents' files whole,
and its own file read for the user and assistant messages the keeper's
file doesn't hold (ccRest, kept while neither file changes). A copy that
is a copy through and through adds nothing, as before.

Fixtures: testdata/claude-forks/subagent*.jsonl are Claude Code 2.1.312's
own files from a sandbox HOME with a fake API (a session whose first
prompt ran a subagent, and a --fork-session of it with a prompt of its
own), cut to user and assistant lines, paths rewritten to /w/proj. The
compaction case cuts compacted.jsonl before "rw prompt eight", as it was
when compacted-branch-on.jsonl's branch was made.

Run (mote) at this tree on efb55b5c9; rebased on 96d4715c6 (routing groups in
gateway, provider, cli and the GUI between; nothing in internal/sessions
or its callers' stats paths), internal/sessions ran again there: ok.
gofmt -l clean; GOOS=darwin, linux and windows go vet -tags nogui
./internal/sessions ./internal/gui ./internal/cli ./internal/tui ok;
go test -tags nogui -count=1 -timeout 45m ./internal/sessions
./internal/gui ./internal/cli ./internal/tui ./internal/usage all ok.
Broken by hand, each red: stats.go as on origin/main (4000 in, want
5000; 20 in, want 80); the copy's subagent files and its rest left out
(the same two).

Not changed: the Sessions row of the session a copy is kept in still
leaves out the copy's subagents and its pre-compaction messages (#4054).
Not tried: the reporter's own files; how much of their 200M was double
counting before 1803 and how much this gives back is not known.
2026-10-28 19:01:27 +08:00
yetone 1feee38d17 sessions: Codex's skills are counted, from its reads of their SKILL.md (MaxMooreMy on X)
MaxMooreMy on X: "magpie的skill调用统计是不是坏了。用了一天,一个都没统计到".
The screenshot is Usage → Sessions, Codex (gpt-6-astra), 10 sessions,
Tool use "exec 488": Top skills says no skill was called up.

Cause: nothing ever counted a Codex skill. Codex has no tool for skills:
its <skills_instructions> list each skill's SKILL.md, and the model calls
one up by reading that file through a shell command, now from inside a
code-mode exec script (tools.exec_command({cmd:"cat '.../imagegen/
SKILL.md'"})), before that through exec_command, shell or a
local_shell_call. codexHead counted each call's tool and passed "" for
the skill, so only Claude Code (Skill tool), Alma and Pi/omp had skills.
Not a regression: efd1b697e and the other recent sessions commits don't
touch this; no version of codex.go counted one.

Now cxSkillReads reads a call line that holds "SKILL.md" (only those are
decoded) and counts each skill whose SKILL.md path it names, by its
folder, once a call: the exec script's input, a function call's
arguments, a local_shell_call's command. A patch writing a SKILL.md, a
redirect or tee into one, a bare SKILL.md with no folder (find -name,
grep) and a glob count none. The sessions cache goes to 25 so cached
Codex files are read again.

Run (all on mote, through mote-run, at this tree):
- go test -tags nogui ./internal/sessions/: ok.
- TestCodexSkillReads: two real call lines from this Mac's rollouts, byte
  for byte (2026-08-07's code-mode exec, 2026-07-26's exec_command, its
  timestamp moved to the same day), plus a patch, a heredoc redirect and
  a find. TestCxSkillReads: shell, local_shell_call, a Windows
  Get-Content path, and the reads that count none.
- Real sessions in a sandbox CODEX_HOME: 19 rollouts copied read-only
  from ~/.codex/sessions (15 August ones with an imagegen read through
  exec, today's 4). Old code: skills calls=0. New: imagegen 15 calls in
  15 sessions, agent codex.
- Across all 11,846 compressed rollouts here, the exec calls naming a
  SKILL.md were grouped by how they read it (cat, /bin/cat, sed -n, awk,
  perl, wc && sed, `done < file`); each form is a read the rule counts.
- Broken by hand: with the loop that counts cxSkillReads' skills taken
  out, TestCodexSkillReads fails ("skills []") and the real sandbox reads
  0.
- go test -tags nogui of the packages importing sessions: usage, cli,
  tui, tune, otlp, davsync ok; gui had TestRestartHandsTheGatewayOver red
  once in the parallel run (#3451, open), 3 of 3 alone.
- gofmt -l clean; go vet darwin, GOOS=linux and GOOS=windows -tags nogui
  of internal/sessions ok.

Not tried: the GUI against a live magpie (the page only shows what
Overview returns; app.js unchanged, so no GUI suite run); a SKILL.md read
through tools the rule doesn't know (a plugin's own read tool) and a
skill whose SKILL.md sits in a nested folder (clawra-selfie/skill/
SKILL.md counts as "skill"); internal/gateway and internal/agent, which
import sessions for other things. Other agents with no skill count
(Droid, Kimi Code, Hermes, Cursor, Antigravity) have no real session
here to build from: #4037.
2026-10-28 17:34:27 +08:00
yetone 4c1fb7758b sessions: copies an older magpie left are swept when a live store is read in place (#1988)
1dc20e73f reads a live Cursor's state.vscdb in place, but the sweep of
magpie-cursor-* folders older than an hour ran only when a copy was
made. A user upgrading from a version that copied keeps whatever it
left (Echo-Huang0010 had ~7.1 GiB of such copies) for as long as Cursor
runs. openCursorEditorStore now runs the same once-per-process sweep
first.

Run at this head:
- mote: go vet ./internal/sessions for darwin, linux, windows ok;
  go test -count=3 -run Cursor ./internal/sessions ok.
- xiaomi-gpu (win-run): go test -count=3 -run Cursor ./internal/sessions ok.
- Broken by hand: sweep line removed, TestCursorEditorReadInPlaceWhileLive
  fails with magpie-cursor-left still in the temp folder.
2026-10-28 14:10:42 +08:00
yetone 1dc20e73fc sessions: a live Cursor's state.vscdb is read in place, not copied (#1988)
Beside a running Cursor, every listing, count, transcript and search
read the editor's state.vscdb from a copy in the temp folder, made again
each time Cursor had written since the last. The store is often several
GB, and on Windows, where no clone makes a copy free, Echo-Huang0010
measured ~10.6 GB written every few minutes.

While the store has a non-empty -wal and a -shm beside it, Cursor's own
processes share it as readers through the -shm, and magpie now opens it
the same way, mode=ro with a 3s busy timeout: no copy. Nothing magpie
shows comes from the store's file times (each chat carries
lastUpdatedAt), so a reader's mark in -shm changes nothing it lists.
With no -shm beside a live -wal, or if that open fails, it falls back to
the copy as before. CLI chat stores keep the copy path. OpenUntouched's
open is factored out as openSQLite.

Thanks to Echo-Huang0010 for the report and the measurements; their
patch capped the copy at 64 MiB, which would leave a larger history
unread, so this takes the in-place read instead.

The Cursor tests set TMPDIR only, which Windows' os.TempDir doesn't read
(TMP, TEMP), so TestCursorLeftCopiesSwept's folder landed in the real
temp folder and the next test counted it. cursorTempDir sets all three.

Run at this head:
- mote: go test -count=3 -run Cursor ./internal/sessions ok;
  go test -timeout 45m ./internal/sessions ./internal/agent ok;
  go vet ./internal/sessions for darwin, linux, windows ok; gofmt clean.
- xiaomi-gpu (win-run): go test -count=3 -run Cursor ./internal/sessions
  ok (red before cursorTempDir, from the stray folder).
- Broken by hand: in-place reads off, TestCursorEditorReadInPlaceWhileLive
  fails "a live state.vscdb was copied 3 times, want 0".
- Windows, two processes: a writer holding a WAL store (~40 MB) with
  busy_timeout(0) wrote 200 times while a magpie process listed 40 times
  and read transcripts. 0 failed writes, every list saw the latest title
  (40 of 40), 0 copies in the temp folder.

Not tried: a real Cursor install. Neither test machine has one, so the
writer was a stand-in process, not Cursor itself.
2026-10-28 14:09:05 +08:00
yetone 502674abb7 sessions: a Claude copy made after /compact is one row with its session
Neo (Discord #feedback, on v0.1.1803, used /compact and /rewind): one
conversation was still listed as many rows of the same title.

Claude Code 2.1.312's /branch (and --resume --fork-session) after a
compaction copies only the compaction's summary and what follows it,
under the same uuids. 1803 grouped copies by the file's first message,
so such a copy (its first message the summary) never met the session it
was copied from and was a row of its own; opened, it read from the
summary on. Each Claude file now also records its compact summaries'
uuids (state Compacts, cacheVersion 24, so every file is read again),
and files are judged together when one starts with a message the other
starts with or holds as a summary. Of two files that hold each other's
last message, the one that also holds the other's first message is kept
(a post-compact copy written last no longer stands in for the whole
conversation), then the newer, as before.

/rewind writes in place: "Restore conversation" and "Summarize from
here" both append to the same file (a new branch under an earlier
parent, a new compact summary), no new file. Its summary is recorded
with /compact's, so a /branch made after it folds too.

Fixtures (testdata/claude-forks/compacted*.jsonl): Claude Code
2.1.312's own files from a sandbox HOME with a fake API: a session of
/compact, a /rewind restore, a /rewind summarize, a /branch after them,
that branch gone on with a turn of its own, and a /branch made after
the session's last turn; trimmed of request records, cost lines and
attachment text, paths rewritten to /w.

Run (mote) at this tree, 8eaf10cac on 4655e1659: go test -tags nogui
-timeout 45m ./... 75 packages ok, internal/gateway red on
TestPluginStreamsPastTheBudgetWait only (connection reset, vendor saw
182 of 192), which is #3946: alone it is red 2 of 3 here and 1 of 3 on
origin/main 4655e1659, which this change doesn't touch. gofmt -l clean;
go build ./... ok; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/sessions ok.
Broken by hand, each red: grouping by the first message only (the
copies' rows came back: [11111111… 7b1e0c2a…]); keeping the newer of two
files that hold each other without the first-message rule (the branch
made last was the row, edc82b93…).
GUI: no file reaches it; the sessions page's JSON is unchanged
(Compacts is in the cache only, Copies is json:"-"), not run.
Not tried: Neo's own files; the ten copies of one moment he saw 16h
before are taken to be /branch or fork copies made after a compaction,
which he confirmed he used (/compact, /rewind). Copies made by a
compaction that ran in each copy on its own would each start with a
summary of their own and still be rows. The calls ledger (FindCall)
still holds a copy's calls.
2026-10-28 11:53:24 +08:00
yetone f4762e9217 sessions: a Claude conversation Claude Code copied into another file is one row
Neo (Discord #feedback): one Claude conversation was listed as ~11 rows
with the same title, message count and size, each under its own id.

Claude Code 2.1.312 copies a conversation into a new <id>.jsonl when it
forks one (--resume --fork-session, /branch) or moves it to a background
session: every message again, under the same uuids, with the new
sessionId. magpie keyed each file as a session, so each copy was a row,
and the copies' tokens were counted again in usage.

Each main Claude-format file (Claude Code, Qoder, Qoder CN) now records
the uuids of its first and last message (state Root/Leaf, cacheVersion
23, so every file is read once more and old copies fold in too). Of the
files of one agent that start with the same message, one whose last
message another holds is a copy (cc_copies.go). Only a random (v4) uuid counts, as Claude Code
writes them: files whose writer reuses ids like "u" stay apart. A copy
is not listed
(List, ListAgent, Agents), not counted in stats, and Delete trashes it
with the session that holds it (Restore brings it back). A fork that
went on with a turn of its own has a last message no other file holds
and stays its own row, as Claude Code's /resume shows it. The gateway's
session rows and the GUI's native keys know the copies' ids, so a
gateway-only row doesn't stand in for one.

Fixtures: testdata/claude-forks is Claude Code 2.1.312's own files from
a sandbox HOME with a fake API (a session, a --fork-session of it with a
third prompt, another fork with a different one), trimmed of request
records and attachment text. Pure copies are that session with its
sessionId rewritten, as /branch leaves one.

Run (mote) at 2b7ce2967 on d8c70504d: go test -tags nogui -timeout 45m
./... all 76 packages ok; gofmt -l
clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/sessions
./internal/gui ok; go build ./... ok.
Broken by hand, each red: ccCopies returning nil (all four row tests),
stats counting copies (110 in / 55 out, want 30 / 15), Delete not taking
copies (a copy came back as the row), MergeExternal ignoring Copies (a
gateway row came back). Without the v4 check, five tests whose
fixtures share "uuid":"u" went red (cli, gui x2, sessions, tui).
GUI: no file reaches it; the GUI tests fake the API and the JSON a page
gets is unchanged (Copies is json:"-").
Not tried: Neo's own files, and the opened view showing only "session
start" and one line in the second screenshot; that was not reproduced.
The calls ledger (FindCall) still holds a copy's calls.
2026-10-28 10:40:28 +08:00
yetone 67b12956ac sessions: a Codex rollout magpie rewrites keeps every line where it was
xybio (Discord #feedback): the Codex app often wouldn't reopen recent
threads: "invalid paginated history lineage for <id>: cutoff byte offset
is past the source rollout". Codex 0.162 keeps a fork's place in its
parent by byte (session_meta.history_base.end_byte_offset, checked by
rollout_lineage.rs validate_cutoff_bounds), and its state database keeps
turns and how far it has read by byte too. PortCodexRollouts (since
4896fc3ba, 10-21) wrote magpie's compaction item as Codex's summary
message, and since 79c8667c9 dropped Claude's sealed reasoning: both
shorter lines, so a parent shrank and every fork made before the pass
named a byte past its end.

Now every rewritten line keeps its length (fitLine): a shorter one is
padded with spaces after its JSON, which serde_json skips; a longer one
(a short summary under Codex's prefix) is left as it was in a paginated
rollout, and written as before in a legacy one, where Codex keeps no
place by byte. MoveCodexProvider, the sibling that rewrites session_meta,
pads the same way and refuses a longer provider id for a paginated
rollout. Forks already broken are repaired once per Codex home
(repairLineages): every line kept its count, and Codex names each line's
ordinal, so a fork's end_byte_offset is set again to where its parent's
line end_ordinal_exclusive-1 ends now, in a first line kept as long.

Run, at a47596ea6 plus this change:
- go test -count=1 ./internal/sessions/ ./internal/codexsummary/: ok;
  ./internal/agent/ -run 'Codex|Port|Move|Session': ok.
- gofmt -l internal/ clean; go vet ./internal/sessions/ ./internal/agent/,
  GOOS=windows and GOOS=linux go vet ./internal/sessions/: clean.
- Real, Codex 0.162.1 in a sandbox CODEX_HOME against a local mock
  Responses server that returns a magpie-claude1: reasoning item: codex
  exec made a paginated thread (50877 bytes), app-server thread/fork
  forked it, then a port pass. Old code: the parent went to 70570 bytes
  from 82912 and thread/resume and thread/read of the fork gave the
  reporter's exact error. New code: the parent kept 82912 bytes with no
  magpie-claude1: left, the fork resumed and read, the parent resumed,
  and codex exec resume ran a turn on the fork. A new-code pass over the
  old-code home repaired the fork (82912 -> 70570 in its history_base),
  after which it resumed and read.

Broken by hand:
- fitLine returning the rewrite as it is:
  TestPortCodexRolloutsKeepsBytePlaces red ("lines end at [... 11329],
  were at [... 14362]", the fork's offset past the end),
  TestPortCodexRolloutsLongerLine and TestMoveCodexProviderKeepsBytePlaces
  red.
- repairLineages a no-op: TestPortCodexRolloutsRepairsForks red.

Not tried: the Codex desktop app itself (the app-server it runs was);
a .zst parent against real Codex (the Go tests cover zst ports); Codex in
WSL, which the pass skips as before. The state database's turn offsets
for a parent already shrunk are left as they are; Codex 0.162.1 resumed
and forked such a parent in the sandbox.
2026-10-27 23:33:26 +08:00
yetone 11dcc743f4 sessions: a listed file is 96 bytes, what only some agents' files have kept behind one pointer
A Sessions poll copies every agent's list of ~20k files several times
(listedRollouts, heldFiles' clone, callFilesWith, allFiles, byKey,
statsRead). Each file was 232 bytes, most of it fields only OpenCode,
ZCode, Hermes, Alma, agy, Cursor's editor or WSL files fill. Those move
into fileMore behind file.more (nil when a file has none); reads go
through m(), writes through w(), which copies first, so copies of a file
never see each other's writes, as before.

A/B with the real ~/.codex and ~/.claude data (ab5.sh, 8 polls 15s
apart, alloc_space between heap-0 and heap-1), base f51ab771f vs this:
- sessionRoutes 848 MB -> 731 MB
- allFiles 426 MB -> 281 MB, heldFiles 322 MB -> 216 MB
- callFilesWith 199 MB -> 109 MB, byKey 86 MB -> 56 MB
- statsRead 467 MB -> 375 MB, listSessions 456 MB -> 352 MB
- all HTTP handlers 1422 MB -> 1379 MB; the profile's total rose
  (2392 -> 2570 MB) in usage's ledger reads, a package this doesn't
  touch, on live data that grew between the runs.
Footprint was not compared: a GUI suite and Go tests ran beside it.

Run before the rebase, at f51ab771f plus this change:
go test -timeout 45m ./internal/sessions/... ./internal/gui/
./internal/usage/... ./internal/cli/ ./internal/tui/ ./internal/otlp/
./internal/tune/ ./internal/agent/ ./internal/gateway/: all ok.
Run at the pushed head (rebased on 6a6c06868, which touches no
sessions file): go test ./internal/sessions/... ok; gofmt clean;
GOOS=linux, windows, darwin go vet -tags nogui ./internal/sessions/
./internal/gui/ ok; the whole tree vetted on all three before the rebase.
Not run: the GUI JS suite (no GUI file changes).
2026-10-27 12:40:00 +08:00
yetone 50606d8c0b sessions: a live file's calls read back from its shard are read on from, not copied
Requests evicts a file's expanded calls after each read, so every change
of a live session loads its calls from the disk shard (loadKept) and
then prepareCalls cloned them whole to read on from. The loaded copy
has no other reader, so the clone was a second full copy of the
session's calls on every poll, held at once with the first while the
chunk was built. readCalls and callsAlong now say when the calls came
from disk, and prepareCalls then copies only the reading state
(cloneState: the Claude window, Codex's maps, which can be a kept
continuation's) and keeps the calls, Msgs and Began. Calls from the
cache are still copied.

Measured on real history (rss-home, owner's ~/.claude and ~/.codex,
read-only), ab5.sh, 90s warm-up then 8 GUI polls 15s apart, alloc
between the heaps:
  before (v0.1.1673 head): callFile.clone 160 MB, prepareCalls 201 MB;
    footprint 264-412 MB, Requests 287-722 ms
  after: clone gone from the profile; footprint 201-367 MB, Requests
    144-472 ms
The history is live, so loadCalls itself varied run to run (741 MB vs
172 MB); the clone's share is the part this change removes.

Run at this head (2e165fe9d + this change):
  go test -timeout 45m ./internal/sessions/  ok
  go test -timeout 45m ./internal/usage/ ./internal/usageapi/  ok
  GOOS=linux/windows go vet -tags nogui ./internal/sessions/  ok
  gofmt -l internal/sessions  clean
New TestCallsFromTheShardAreNotCopied (claude, codex): red with the
owned branch turned off by hand ("calls read from the shard were
copied to be read on from"), green with it.
Not tried: a GUI run (no GUI change).
2026-10-27 11:42:49 +08:00
yetone 79c8667c92 gateway: Codex gives Claude its signed thinking back through encrypted_content
Codex calling a Claude model through magpie (mysterious_dove_96933 on
Discord): a reply's reasoning items carried only the summary, so Claude's
thinking signature and a redacted_thinking block's data were gone. On
the next request of a tool loop magpie sent Anthropic the turn as
[tool_use] alone, with thinking on, which Anthropic documents as a 400
("final assistant message must start with a thinking block"), and the
model lost its reasoning across calls either way.

Now the Anthropic decoders name a signature as Claude's (KSig with
sealAnthropic, Part.SignedBy). The Responses encoder and renderResponses
give each thinking block a reasoning item whose encrypted_content is
"magpie-claude1:" and the block's JSON in base64 (internal/claudeseal):
its summary beside it, an empty summary for a block signed with no
text, and redacted_thinking as an item of its own. parseResponses reads
it back into the block as Claude wrote it, in order, so anthropicBody
sends it as before for an Anthropic client. A Gemini thought's
signature isn't named and isn't sealed.

The envelope never reaches a Responses API: withoutClaudeSeals in
passthrough and forwardOnce (the item keeps its summary, one with none
goes), codexInputAs leaves such an item out for Codex's own models, and
codexUpstreamOn takes it out before the ChatGPT backend. OpenAI's own
encrypted_content is untouched. sessions.PortCodexRollouts writes such
an item as its summary, so a thread resumed against OpenAI itself isn't
refused. redact.MaskJSON already keeps a reasoning item's seal whole
(no change); TestMaskJSONKeepsClaudeBlocks holds that.

Run, at 5e3dd1d52 plus this change:
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/sessions/
  ./internal/redact/ ./internal/claudeseal/: sessions, redact,
  claudeseal ok; gateway ok but for TestResponsesStreamToolThenHiddenThinking
  (#1786), whose hidden cases wanted no reasoning item, the loss this
  fixes. They now want one item carrying the sealed block with an empty
  summary, and its guarantee (a whole stream, no panic) is unchanged;
  re-run green.
- gofmt -l clean; go vet (darwin) on the touched packages, GOOS=linux
  go vet -tags nogui ./internal/..., GOOS=windows go vet on the touched
  packages: clean.
- TestCodexToolLoopGivesClaudeItsThinkingBack (a fake Anthropic: signed
  thinking, redacted_thinking, a text-less signed block, tool_use; a
  Codex-shaped request with store false and the encrypted_content
  include; then the follow-up) fails on 5e3dd1d52: "stream=true:
  Anthropic was sent 1 assistant blocks, want 4". Passes now, streamed
  and not.
- Real: a sandbox HOME with only OpenRouter's key (Anthropic endpoint,
  anthropic/claude-opus-5.5, served by Claude Platform on AWS), magpie
  serve on its own port, a Codex-shaped two-turn tool loop at effort
  high, streamed and not: turn 1 gave a reasoning item with
  magpie-claude1: (3.1KB), turn 2 was 200 through /v1/responses →
  /v1/messages and answered from the tool output.

Broken by hand:
- withoutClaudeSeals a no-op: TestClaudeBlocksNeverGoToAResponsesAPI
  red, the relay sent magpie-claude1: items.
- codexInputAs not leaving them out: red, "ChatGPT backend would be
  sent …".
- sealing any signature (no sealAnthropic check):
  TestGeminiSignatureIsNotSealedAsClaudes red.
- portValue's reasoning branch off: TestPortLineDropsClaudeBlocks red.

Not tried: the 400 itself. Through OpenRouter, Opus 5.5 answered turn 2
with the envelope stripped too (the old shape), so this route shows
only the lost reasoning, not the refusal. Not tried on api.anthropic.com
directly, Bedrock or Vertex keys, or Claude's subscription (whose tool
loop stays inside Claude Code's run). Codex resuming a ported thread
against OpenAI with such items wasn't run.
2026-10-27 11:26:54 +08:00
yetone a87f051974 sessions: the index is written at most once a minute, not after every poll
A Sessions or Usage page polls every 15s, and a live session changes its
file between any two polls, so each poll's refresh saved the whole index
again: tens of MB of JSON for a long history, and encodeCache allocated
~20-30 MB a write (170 MB over 8 polls). The index only spares the next
start a read, and a parse a save hasn't written yet is read again then,
so a save now waits saveGap (1 minute) after the last one written; saves
in a row are still folded into the latest. Saved (a CLI or the app
ending) sets hurry, so every save queued is written at once without the
gap, and an unused wake-up is drained when the saves end so it cuts no
later gap short. The package's tests write saves as they come
(saveGap = 0 in TestMain).

Run:
- TestSaveWaitsOutTheGap (new): a second and third save right after the
  first are not written while the gap stands, and Saved writes them, as
  one, at once. Red with the wait removed ("2 writes with saveGap not
  yet past") and red with Saved not hurrying ("Saved waited out the
  gap", 10s).
- go test -timeout 45m ./internal/sessions ./internal/gui ./internal/usage
  ./internal/usageapi ./internal/cli ./internal/tui: ok at this change on
  205e3b8ae. gofmt clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/sessions ok.
- A/B, 8 sequential polls of the Sessions and Usage pages under a
  sandbox HOME with the real ~/.codex and ~/.claude sessions (live, so
  totals vary run to run): writeCache 169.5 -> 95.9 MB, encodeCache
  163.7 -> 92.5 MB; the run spans a few minutes, so a write a minute
  still lands in it. At the GUI's 15s polls that is one write a minute
  instead of four.
Not tried: quitting the real app and checking the index on disk; the
CLI's exit path calls Saved, as before.

Rebased on 2badacaad (provider and plugin changes): go test -count=1
./internal/sessions ./internal/gui ok at 26ed62752 (15.6s, 162.0s).
2026-10-27 10:21:10 +08:00
yetone 205e3b8ae7 sessions: a poll groups its files by session in one copy, not an append at a time
listSessions, statsRead (twice), nativeIDs, the Codex provider's list
and the two manage paths each grouped the files by key with
groups[f.key] = append(groups[f.key], f): every group grown by
doubling, copying a few-hundred-byte file struct each time, over ~16k
files. byKey counts the kept files per key, makes one slice for all of
them and cuts each group from it with its capacity capped, so a later
append to one group can't write into the next. Each group keeps the
files' order, as before.

Run:
- TestByKeyGroupsAsAppending (new): byKey equals the append loop with
  and without a keep, and is unchanged after every group is appended to.
  Red with the cap removed (kept[at:at]): a group's first file became
  the previous group's appended one.
- go test -timeout 45m ./internal/sessions ./internal/gui
  ./internal/usageapi: ok (15.1s, 118.9s, 3.4s) at this change on
  f3c4d7b7a. gofmt clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/sessions ok.
- A/B, 8 sequential polls of the Sessions and Usage pages (state,
  sessions, stats, usage, usage/requests, quotas, providers) under a
  sandbox HOME holding the real ~/.codex and ~/.claude sessions, alloc
  diff between heap profiles: listSessions flat 143 -> 77 MB, statsRead
  flat 170 -> 84 MB, byKey's own 92 MB, so ~60 MB less in all;
  sessionRoutes 1026 -> 993 MB.
Not tried: the GUI against a real window; the JSON the routes answer is
built from the same groups.
2026-10-27 10:01:09 +08:00
yetone d5f86d9919 sessions: a Sessions poll's three reads share one listing of the files
The Sessions tab asks /api/sessions, /api/sessions/stats and
/api/sessions/overview at once, and statsFor refreshes its memo in a
goroutine beside them. Each listed every session file again. The stats
and overview routes and the refresh now take sessions.ShareListing: a
hold that, unlike OneListing, doesn't start a new "since" when one is
already held, so a listing a read in flight is making is waited for
and shared (heldFiles keeps a ready channel per listing) instead of
made again. The refresh is also counted as a page read (readingPage),
so its memory goes back once it rests.

Run at this head: go test ./internal/sessions ./internal/gui ok,
TestShareListing -race -count=5 ok. TestShareListing was red with the
wait taken out of heldFiles by hand (the second read listed again).
A/B on real session files, 8 polls of the parallel trio then
/api/state, v0.1.1661 vs this: total allocated 1.96 -> 1.82 GB, trio
mean 572 -> 438 ms, first trio 2071 -> 1456 ms, allFiles 353 -> 322 MB.
Footprint between polls stayed ~160 MB; statsRead (~520 MB) and
listSessions (~345 MB) are the rest and are not changed here.
Rebased on 65ee8c65c and run again: dirent and sessions ok; gui had
one red, TestRestartHandsTheGatewayOver, with an A/B run of magpie
beside it; it is #3451 (EOF during the handover under load). It passed
3 of 3 alone and the whole gui package passed on a rerun.
Rebased again on cc9d68ffd (agent and update only) and run at the
pushed head: dirent, sessions and gui ok.
2026-10-27 09:28:34 +08:00
yetone d4c6230964 sessions: a folder's listing is a sorted slice, and one Codex folder isn't copied
dirent.Stats returned a map per folder. Eight Sessions-page polls on the
owner's real ~/.codex and ~/.claude (copied into a sandbox HOME) spent
~90 MB of their 2.3 GB on those maps alone. It now returns a Listing
sorted by name, found with a binary search (Listing.Get), and
listedRollouts walks it in order instead of sorting the map's keys.
listCodexFiles took the one folder most users have into a fresh slice;
that copy was ~65 MB of the same polls, and the folder's own slice is
now kept.

Run at this head: go test ./internal/dirent ./internal/sessions
./internal/usage ./internal/usageapi ./internal/gui ok; gofmt clean;
GOOS=linux and GOOS=windows go vet -tags nogui on dirent, sessions,
usage and gui clean. stats_test checks the listing is in name order.
A/B on real session files (8 polls of the Sessions trio, 15 s apart,
v0.1.1661 vs this with the next commit): listCodexFiles 129 -> 89 MB,
listedRollouts 87 -> 76 MB, dirent.stats 44 -> 36 MB.
Not tried: the Linux and Windows readdir paths beyond go vet; they
build the same Listing through stats_other.go.
Rebased on 65ee8c65c (gateway and plugin fake only) and run again
there with the next commit: dirent, sessions and gui ok.
2026-10-27 09:26:09 +08:00
yetone 2929135abc sessions: Codex's rollout listing is sized as its last one was
listedRollouts appended each of ~20k rollouts to a slice grown from
nothing, on every Sessions, stats, requests-page and effort read; past
256 entries a slice grows by a quarter, so the growth allocated about
five times the list. It now starts at the size the root's last listing
had (plus a sixteenth), and codexFilesIn takes the first folder's list
as its own instead of copying it.

Measured on a copy of the owner's real history (real ~/.claude/projects
and ~/.codex sessions), warm start, 12 GUI-like poll cycles 15 s apart,
v0.1.1655's tree against this one: listedRollouts' allocation over the
polls 762 MB -> 343 MB, its append growth (538 MB flat) gone. The
run's total isn't comparable: the live Codex history changed between
the runs and the requests page read the changed rollouts again.

Run at this tree: go test ./internal/sessions/ ./internal/usage/
./internal/gui/ ok; gofmt -l clean; GOOS=linux and GOOS=windows go vet
-tags nogui ./internal/sessions/ ok.
2026-10-27 07:53:16 +08:00
yetone 0e7d2391ce sessions: the list of call files is sized once, not grown a file at a time
callFilesWith appended each of ~20k session files (a ~200-byte struct)
to a slice grown from nothing, on every Sessions and stats read: every
15 s poll of the window. It now gathers each source's list first and
makes the slice and the seen map at their total.

Measured on a copy of the owner's real history (rss-home: real
~/.claude/projects and ~/.codex sessions), warm start, then 12 GUI-like
poll cycles 15 s apart (api/state, api/sessions, stats?days=30,
api/usage, requests today, quotas, providers), origin/main a3d4f8c5c
against this tree with the next commit's effort gap: allocation over
the polls 4668 MB -> 3879 MB; callFilesWith's 1167 MB -> 342 MB (its
append growth, 984 MB flat, is gone). Footprint 241-336 MB against
256-296 MB, the same within noise.

Run at this tree: go test ./internal/usage/ ./internal/sessions/ ok;
./internal/cli ./internal/davsync ./internal/gui ./internal/middleware
./internal/otlp ./internal/tui ./internal/tune ./internal/usageapi ok;
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui of usage
and sessions ok. Not run: internal/agent and internal/gateway, which
don't read this list's order or size.
2026-10-27 07:46:32 +08:00
yetone 51a2068b52 sessions: a Sessions poll lists the session folders once, not twice
Each /api/sessions read listed every Claude Code and Codex session file
for its list (allFiles), then again for the Codex threads' effort
(usage.CodexModelEffort -> readRequestState -> CallSourcesAndCodexIdentities):
~21k files on this machine, twice every 15 s poll.

sessions.OneListing holds the folders' listings (ccFiles per folder,
codexFiles) while a request is answered; GET /api/sessions and
/api/sessions/manage take one. A listing is shared only if it was taken
after the latest hold began, so no request reads files from before it
came, and the listings go when no hold is left. Folders are listed
outside the lock. The warm-up's own memo (warmListing) is unchanged.

Measured on the real history (rss-home, symlinked ~/.claude/projects;
prof.sh, 20 s CPU profile, /api/sessions back to back), against
fe903798f:
- poll 170 ms -> 118 ms
- readRequestState 3.89 s -> 1.58 s of samples; listedRollouts 4.95 s ->
  3.50 s, now only under List

TestOneListing: one listing under a hold; a hold begun after a listing
lists again; every read lists once no hold is left. Red with the
"taken since the latest hold" check removed by hand.

Run at df1ba9586 (on fe903798f):
- gofmt clean; GOOS=linux and GOOS=windows go vet -tags nogui ok for
  sessions and gui
- go test -tags nogui -count=1 -timeout 45m: sessions 12.6s, usage 15.0s,
  gui 52.3s, dirent 4.7s, all ok
- not run here: the GUI suite (no page script changed) and the importer
  packages (run at fe903798f, all ok)
2026-10-27 06:40:30 +08:00
yetone 7b2a330a56 sessions: each session folder is read in one listing on macOS, not a stat() a file
Every 15 s Sessions poll (and every Requests page) lists every agent's
session files and stat()s each one: on a real history of ~21.7k files
in 462 folders that was ~21.7k lstat()/stat() calls, ~10 µs each on
APFS, and the largest part of the poll's CPU. Codex's day folders were
also read twice, once by WalkDir and once more for the stat()s.

dirent.Stats reads a folder's names, kinds, sizes and modification
times with getattrlistbulk, a few calls for the whole folder. statFiles
looks each file up in its folder's listing and stat()s alone only a link
it follows (ccFiles) or a folder that couldn't be listed so. Codex's
rollouts are walked with the listings themselves (listedRollouts), in
WalkDir's order, falling back to walkLinked and statFiles when a folder
can't be read so. Other systems keep the stat()s as they were.

Measured on the real history (~/.claude/projects and ~/.codex
sessions, read only):
- Stats against os.ReadDir + os.Lstat over all 21,672 entries in 462
  folders: 0 mismatched kinds, sizes or times; 43 ms against 257 ms.
- `magpie serve` on the real history (sandbox HOME, its projects a link
  to the real ones), /api/sessions asked back to back with
  X-Magpie-Had for a 20 s CPU profile: before, 177 ms a poll, process
  CPU 48.5 s for the run, 17.5 s of samples in statFiles; after, 157 ms,
  34.3 s, and no per-file stat() in the profile beyond links.

Tests:
- TestStatsAsLstat: a file's size and time to the ns, a folder, links
  to a file, a folder and nothing, a unicode name, and 3000 long names
  (more than one call's 64 KB answer), each as os.Lstat says.
- TestStatFilesAsStat: follow and not, the same files kept with the same
  sizes and times as os.Stat/os.Lstat; on macOS only the two links are
  stat()ed alone. Red (7 alone, want 0) with Stats turned off by hand.
- TestListedRolloutsAsWalked: nested days, a folder and a link named as
  rollouts, a .zst, a non-rollout, and a sessions folder that is a link
  (#2233): the same rollouts, order, sizes and times as walkLinked plus
  statFiles. Red with the listing's sort taken out by hand.
- TestCodexFilesStatInOrder (existing) passes on the new path.

Run at this head:
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui on
  internal/sessions and internal/dirent ok.
- go test -tags nogui -count=1 -timeout 45m ./internal/dirent/
  ./internal/sessions/ ./internal/usage/ ./internal/gui/: ok (2.4 s,
  13.9 s, 15.9 s, 51.1 s).
- go test -tags nogui -count=1 -timeout 45m at fe903798f, the packages that
  import sessions: agent 293s, cli 57s, davsync 73s, gateway 493s,
  library 192s, otlp 19s, tui 31s, tune 7s, all ok

Not tried: Windows and Linux run the stat()s as before, so no change
there; an SMB or other network volume on macOS, where getattrlistbulk
fails and the per-file path is taken.
2026-10-27 06:40:30 +08:00
yetone eee5719991 sessions: a session's cost is summed in its models' order, so it reads the same each time
assembleListed summed a session's cost over a map of its models, and
statsRead summed a summary's the same way, so the float came out a last
digit apart from read to read (15225.3933882, then 15225.393388199998,
on a real Claude Code session with nothing new written). Each read of
the Sessions list then had a changed row, and the stats a changed
summary, though nothing had changed. Both sum in name order now.

Run at this head (macOS, go1.27):
- TestSessionCostSummedInOneOrder (assembleListed, 7 models, 200 reads)
  and TestSummaryCostSummedInOneOrder (statsRead, 6 models priced, 50
  reads): red on the old code (2 different numbers each), green after,
  -count=3.
- go test -tags nogui -timeout 45m ./internal/gui/ ./internal/sessions/
  ./internal/usage/ (provider's #3632 skip): ok.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/gui/ ./internal/sessions/: ok.
- Real history (~15.9k sessions, a live session being written): six
  /api/sessions reads 15 s apart, each the same as a whole read taken
  just after it; before, the 506 KB row of one session flipped its cost
  between reads.

Not tried: Windows and Linux runs of the package tests.
2026-10-27 05:39:12 +08:00
yetone bbb4fd478a sessions: a parse's models, days and tools are sorted slices, not maps
A kept parse holds a model or two, a day or two and a few tools, and Go's
map of one entry is a whole group of eight: ~500 bytes for one model's
Tokens, where a sorted slice entry is 56. Over a long history (15.9k kept
parses) state.Models, Days, day.Models, Tools and Skills held 18.4MB as
maps and 4.2MB as named[V], a slice kept in name order. It is written as
the same JSON object a map writes, byte for byte, so the parse cache
saved before reads unchanged; names are interned with unique.Make, and
plain integers in ints and Tokens are read without reflection.

Measured with the real ~/.codex and ~/.claude histories (sandbox HOME,
warm cache, 40s after start), base 3393e61d0 vs this change, two
alternating runs each:
  live heap   102 / 105MB  ->  92 / 91MB
  footprint   164 / 167MB  -> 156 / 150MB
Cache decode at start: ~58ms -> ~61ms (best of 7).
Side by side on the same data, /api/sessions/overview?agent=codex and
/api/stats?days=30 are identical; the other overview queries differed
only in the two Claude sessions being written during the run.

TestNamedIsAMapInJSON: marshal is byte-equal to a map's (HTML-escaped
key included), round trip, a repeated name keeps its last value, an
unknown Tokens field is ignored, omitempty leaves none out, and 1.5,
"1", [1], 1e3 and a too-big int fail as they fail into a map. Broken by
hand (the int fast path accepting 1.5) it went red.

Run at this head (rebased on 2beed3b04): gofmt clean; go build ./...;
GOOS=linux go vet -tags nogui sessions, gui, usage; GOOS=windows vet
sessions; go test -timeout 45m ./internal/sessions ./internal/usage
./internal/gui ./internal/gateway all ok.
Not run: the full ./... suite and the GUI node tests (no GUI change).
2026-10-27 04:39:56 +08:00
yetone 3393e61d00 sessions: a summary's tools, skills and days are sorted slices, not maps
Each range statsFor keeps (all days, and 30, warmed at start) holds a
Summary for every session, and each had four maps (tools, skills,
skillLast, perDay) plus a tools map in every day. Most hold one or two
names, and a Go map of one is a few hundred bytes. They are now
counts (name, calls, a skill's last date) in the names' order, and
perDay a slice of days in order; the build still sums into maps and
hands those over once.

Run at this head (8ab4fd612 + this change), in a sandbox HOME with the
real ~/.codex and ~/.claude sessions (15,921 files), warm start, two
alternating runs each, 40 s after settling:
  before: footprint 174 / 178 MB, live heap 104 / 104 MB
  after:  footprint 165 / 170 MB, live heap 97 / 96 MB
Both builds side by side on the same files, /api/sessions/overview at
days 30, 0, 30&agent=codex and 0&agent=claude, and /api/sessions/stats
at 30: stats identical; the overviews differ only in the title length
8ab4fd612 changed and in today's counts of the Claude sessions being
written between the two reads (codex-only: titles alone).
go test ./internal/sessions ./internal/gui ok; ./internal/usage red
once on TestUsageReadAfterAppendHashesNothingOnAFineClock's whole-second
case (#3511, #3551, untouched here), 5 of 5 ok rerun. gofmt clean;
GOOS=linux and GOOS=windows go vet -tags nogui ./internal/sessions ok.
2026-10-27 04:15:48 +08:00
yetone 8ab4fd6120 sessions: the overview keeps each session's own title, not a copy cut to 160
title() keeps 160 characters and an ellipsis, 161 in all, and the
overview cut every such title again to 160. So each range statsFor
keeps (all days, and 30) held a new copy of nearly every title, and
clip made a []rune of each title to count it. On a 15,921-file
history, 12,220 of the 12,289 titles are 161 long.

The overview now clips at titleKept (161), and clip counts runes
without converting, returning s itself when it fits.

Run at this head (d4699c00a + this change), in a sandbox HOME with
the real ~/.codex and ~/.claude sessions, warm start (KEEP=1, the
parse cache kept), two alternating runs each, at 40 s after settling:
  before: footprint 191 / 193 MB, live heap 112 / 112 MB
  after:  footprint 185 / 179 MB, live heap 107 / 102 MB
TestStatsTitleIsTheSessionsOwn is red with titleKept set back to 160,
green with it. go test ./internal/sessions ./internal/gui
./internal/usage ok; gofmt clean; GOOS=linux and GOOS=windows go vet
-tags nogui ./internal/sessions ok.
Not run: the full suite (two packages' worth of change, the GUI
package passes).
2026-10-27 04:04:55 +08:00