Commit Graph
76 Commits
Author SHA1 Message Date
yetone 7cabf0da98 sessions: one place says which ids a ZCode request names, and drafts are one group (#5754)
On top of Flandern1211's cherry-picked fix (the commit before this one).
GatewayKeys gave the bare id of a ZCode session (sess_<id> in ZCode's
database, <id> in the gateway's record), but NativeIDs kept its own copy
of the keys: the management page still counted every ZCode session sent
through the gateway as a gateway-only session, its delete listed them,
and its search read them a second time. requestIDs is now the one place
that says which ids a request names a session by; GatewayKeys (Sessions
list, its spend, the stats' native set, viaOf, the manage search) and
NativeIDs (the manage page's count and delete) both read it.

ZCode runs a session started without a project in a folder it makes for
that session alone: <workspaceDirectory>/draft-<id> or <ms>-<uuid>, with
workspaceDirectory = ~/.zcode/workspace (read from ZCode 3.17.2's
out/host/index.js, downloaded from cdn-zcode.z.ai; never the live
~/.zcode). The reporter's group is renamed from "Scratch sessions" to
"Draft sessions" (草稿会话 / 草稿會話 / 下書きセッション /
Entwurfssitzungen), after ZCode's own word for them, with a GUI test of
its own. Comments no longer quote "Seen through the gateway", which
i18n-keys' plugin-words guard read as the core saying the word.

Run (mote, at this tree, rebased on 0eac4e6aa):
- gofmt -l: clean. go vet of sessions/gui/usage for darwin, linux
  (-tags nogui), windows; GOOS=linux -tags nogui and GOOS=windows
  go build: ok.
- go test -run 'ZCode|Gateway|Native|Manage|Merge|External'
  ./internal/sessions ./internal/usage ./internal/gui: ok.
- GUI, Chromium and WebKit: sessions-zcode-drafts (new, 5 languages x 2
  widths), sessions-folder-list, i18n-en-no-cjk: ok. i18n-keys' "a
  plugin's words are its own" is red at origin/main for three words not
  touched here, filed: #5332 (View routing), #5426 (No session ID),
  #5482 (Use the library's). The reporter's comments quoted "Seen
  through the gateway" and made a fourth; reworded.

Broken by hand:
- TestZCodeGatewayRowIsTheSessionItself on origin/main's raft.go,
  manage.go and external.go: red (keys lack zcode|main, fork_of_main,
  abc; NativeIDs lack them; 29 rows for 26 sessions).
- sessions-zcode-drafts on origin/main's Sessions client.js/i18n.js:
  red in every language and width.

Not tried:
- The full Go suite and the whole Sessions GUI set: queued behind other
  sessions on mote's suite lock; run after the push, reds filed.
- A real ZCode database: none on this machine; the reporter's own run
  over 1,105 sessions is in the issue.
- Windows/WSL GUI, and a ZCode data folder the user moved elsewhere
  (only ~/.zcode/workspace is matched).

Reported-by: flandern1211_58540 (Discord)
Refs #5754 (left open for the reporter)
2026-11-09 18:55:01 +08:00
Flandern1211 a39b63e886 sessions: a ZCode session is listed once, and its draft folders are one group
A ZCode request names its session by the id its database gives with a
prefix stripped (sess_…, a subagent's sess_subagent_agent_…: zcodeBareID,
which Titles already used for names), while GatewayKeys kept only the
prefixed id. MergeExternal therefore matched no native session for any
ZCode session sent through magpie's gateway, and each was a row under its
folder and again a row under "Seen through the gateway" with no files
behind it. On this computer's database (1,105 sessions, 3,536 gateway
records) that was 70 of 70 gateway rows: 38 top-level sessions, 9 forks,
23 subagents. A group already holds its forks' and subagents' files
(ocRoots), and assembleListed counts every file's calls in the row, so
each of the 70 counted the same calls a second time.

GatewayKeys now gives the bare id of a ZCode session and of its forks and
subagents; externalAdded reads GatewayKeys instead of keeping its own copy
of the keys in pairs; idInFile names ZCode, so subIDs collects the ids
their own rows give (their files are in the group, no row lists them
apart). The Sessions page draws a ZCode session whose folder ZCode made
for that one session (~/.zcode/workspace/<draft|time>-<uuid>, one for
each session started without a project) in one "Scratch sessions" group
after the projects: 42 of them here were 40 folders of one session under
Other folders, and they are no projects of the reader's. cwd, files and
usage are untouched; a row's tooltip gives the folder it ran in.

The list went from 1,286 rows to 1,216 over the same 1,213 native ones;
the 70 gateway rows had 34.3M input and 2.59M output tokens and $125.66
of the ledger's cost on top of the rows that already counted those calls.
A ZCode row now prices its own calls from the catalog like every other
agent's, and Usage keeps the ledger's figures.

Run:
- go test ./internal/sessions -run 'TestZCode' -count=1: ok.
- go test ./internal/gui -run 'Session|Gateway' -count=1: ok.
- go build ./...; go vet ./internal/sessions: ok.
- gofmt -l; git diff --check; node --check on client.js and i18n.js: clean.
- go test ./internal/sessions -count=1: the same failures as without this
  change (TestAgySessions, TestAgyRowOnly, TestAntigravityAppFolder,
  TestCCListingKeepsItsNames: path separators and allocation counts on
  this Windows box).
- go test ./internal/gui -count=1: the same failures as without this
  change (lody's %AppData%, pageservice's symlink privilege here).

Broken by hand:
- dropping the bare key puts the 70 rows back under Seen through the
  gateway (TestZCodeGatewayRowIsTheSessionItself fails);
- leaving ZCode out of idInFile keeps a fork's and a subagent's own rows
  as gateway rows while the group already counts their calls.

Not changed: the scratch group is worked out on the page (client.js), so
Usage's folder filter still lists the draft folders by their paths; the
group is ZCode's only, and other agents' per-session folders are left as
they were.
2026-11-09 18:49:15 +08:00
yetone f78d6b0d95 tune: gateway mode leaves Tuned for you out
/api/tune replays this computer's Claude Code and Codex files, and a
~/.claude folder alone makes a Claude Code card. In gateway mode the agents
are on other computers, so the card said Claude Code made 0 requests while
the harness card counted the gateway's. /api/tune now says gateway: true
with no agents, Use and Undo answer 409, and context.js draws no section.

Run (mote): go test ./internal/gui -run 'TestTune|TestGatewayMode' ok;
node --test context-tune-gateway, context-tune, context-tune-shapes 334/334
(Chromium and WebKit, en and zh, 900 and 420 wide); vet both OSes and gofmt
clean.
Broken by hand: with the ownSessionsOff checks taken out the Go test shows
the reported Claude card with 0 calls; the GUI test fails 20 of 30 (every
gateway-mode case) on the old context.js.
Not tried: a real Docker magpie; the full suite (mote rebooted mid-run).

Reported-by: linkaww on Discord
2026-11-08 02:37:09 +08:00
yetone 371b2b63a0 sessions: gateway mode lists the sessions the gateway counted
Usage › Sessions lists only the stats' keys, and the keys named only the
agent files this computer reads. A Docker magpie in gateway mode reads none,
so the sessions that came through the gateway were counted and not listed.
MergeExternalStats now puts them in the keys too, in the list's order.

Run (mote): go test ./internal/sessions ./internal/gui -run
'TestGatewayStats|TestGatewayMode' ok; GOOS=linux go vet -tags nogui ./...
and GOOS=windows go vet ./... clean, gofmt -l clean.
Broken by hand: on the old code the unit test's keys are [claude:a] and the
gui test's [] (gateway mode off, days=0).
Not tried: a real Docker magpie; the full suite (mote rebooted mid-run).

Reported-by: linkaww on Discord
2026-11-08 02:37:09 +08:00
yetoneandRuijia Zhang 04aabf3a01 sessions: read Antigravity Insiders conversations (#5634)
Antigravity - Insiders keeps its conversations in a separate store,
~/.gemini/antigravity-insiders/conversations/<id>.db, with its own
conversation_summaries.db beside it. Only the stable store was scanned,
so Insiders sessions and their token use never reached Sessions or Usage.

Both stores are now read under the existing antigravity agent and its
session-reading choice. An Insiders-only install shows up in Found, and
Dirs lists each store that exists. Each file takes its title and folder
from its own store's summaries. Insiders session ids carry an
"insiders-" prefix in magpie, so a UUID present in both stores stays two
sessions with separate call ids; stable ids are unchanged and nothing on
disk is renamed. Nothing maps a session id back to a path, so the prefix
can't send a reader to the wrong file.

Ported from BUKOWSKIREAL's branch (926d4fe50), unchanged.

Ran (mote, at this head):
- TestAntigravityInsidersSessions: green; red with the three source files
  put back (Insiders missing from Found, Dirs and List).
- go test -count=1 ./internal/sessions ./internal/usage ./internal/usageapi
  ok; go vet ./internal/sessions for darwin, linux and windows ok; gofmt
  clean.
- The author's own run: 42 real Insiders databases read in an isolated
  copy, 2,293 calls, each model's tokens matching an independent decoder.
Not tried: a real Insiders install on our machines; the full suite.

Co-authored-by: Ruijia Zhang <ruijiazhang76@gmail.com>
Reported-by: zhang9083 (Discord #feedback)
2026-11-08 00:33:08 +08:00
yetone 06c4582cca remote magpie: a list changed on the other magpie reaches this one's agents at once
KaCli (Discord) runs two magpies: the server's is the gateway, and the
local one has it as a Remote magpie and writes its models into dsh. A
route or group changed on the server reached the local dsh only on the
next 10-minute fetch (#2135's RemoteMagpieEvery). The server knows when
its list changes (filememo), so it now says so.

- Server: GET /v1/models with X-Magpie-List-Wait: <secs> and
  If-None-Match answers the list with an ETag once it differs from that
  tag. It answers 304 at the end of the wait (at most 50s, under a
  proxy's 60s) or as the gateway stops. The list is looked at again on
  each magpie write and on each change another process makes to its
  files (filememo.Written). It is the list's own route, so the key,
  lanGuard, corsGuard and a key's models judge it as before. The wait is
  exempt from holdCatalog, and each look holds the catalog for itself.
  Without the header the answer is the same as before, with no ETag.
- Client: KeepRemoteListsFollowed (started beside KeepListsFresh) keeps
  one long-poll per Remote magpie. On a new tag it fetches the list
  through the same RefetchTaking, so catalog.Touched rewrites the
  agents' configs. A magpie from before answers at once with no ETag; it
  is left to the 10m schedule and asked again after an hour. A Remote
  magpie whose user set its list to "off" is not followed. The schedule
  stays as the fallback.

Run (on mote, through mote-run):
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build ./..., GOOS=linux -tags nogui and
  GOOS=windows builds: all ok.
- go test -tags nogui -count=1 ./internal/gateway ./internal/provider
  ./internal/catalog ./internal/filememo: all ok (gateway 863s, provider 152s, catalog, filememo).
- After the rebase on 650bf8412 (11 files changed under gateway and
  provider since): go vet of both, go build ./..., and -run
  "ModelsWait|RemoteMagpie|ListsFresh|HoldCatalog|Models" of both: ok.
- Two real magpies (this build, `serve`, sandbox HOMEs, 127.0.0.1:3561
  server and :3562 local, a gateway key, dsh profile web wired to
  office/up/m1). `magpie group add kacli-fast` on the server put
  office/group/kacli-fast in the local cordis.patch.yml in 1.14s
  (log: "office: its list changed there, fetched again: 3 models"). 130s
  idle after it: no further fetch.
  Control: origin/main on both, nothing in 37s. origin/main server, this
  local: nothing in 37s, logged once "doesn't wait ... fetched on its
  schedule", asked once.

Broken by hand, each red:
- Without the dispatch to the wait: TestModelsWaitTagged,
  AnswersAChange, EndsWithTheGateway.
- Without the filememo.Written wake: TestModelsWaitAnswersAChange
  (answered after 5.0s, at the others timer).
- Without RefetchTaking in the follower: TestRemoteMagpieListFollowed.
- Without the RefreshInterval > 0 check: TestRemoteMagpieOffNotFollowed
  (asked 3 times).
- Removing the holdCatalog exemption is caught by no test: a held
  catalog is still dropped on a write (heldFreshLocked), so the change is
  seen. It is kept so a 50s hold doesn't pin the build, as with a
  WebSocket.

Not tried: across two real computers on a LAN, or behind a reverse
proxy (only loopback with a key, and the LAN/no-key, foreign Origin and
Origin null refusals in TestModelsWaitGuardedAsTheList). Not tried on
Windows or Linux. Agents other than dsh weren't checked, though they go
through the same catalog.Touched sync.

Reported-by: KaCli (Discord)
2026-11-06 20:57:55 +08:00
yetone d70f422043 gateway: a conversation of pictures keeps its text and pictures in Routing and Sessions (#5407)
matrix0487 on Discord: since images go to DeepSeek by file id, the
Routing card shows no pictures and the Sessions page loses the turns.

Cause: the views keep the body as the agent sent it, with every
picture inline, and they cap it. The Routing card keeps a body of up
to 32 MiB (promptBodyMax), and its archive read refuses a larger one.
A gateway-recorded turn keeps 8 MiB of input (conversationBodyMax),
and cutting it there leaves JSON that doesn't parse. Before #5407,
DeepSeek refused more than 64 MiB inline, so a conversation never got
far past these caps. With file ids it does: the reporter's turns send
about 30 MB of pictures each. The card then says the text is gone and
draws nothing, and the Sessions turn keeps only the reply.

Fix: leanImages swaps each inline picture's base64 (a data:image/...
URL, or a bare Anthropic or Gemini source that starts as a PNG, JPEG,
GIF or WebP does, 1 KiB or more, with no escapes) for a short ref
before the caps apply.
- Routing card: the kept body and the archive's copy (before its cap)
  keep their pictures in keptImages. It is memory only and bounded:
  128 MiB, least recently used first, and the same picture is kept
  once. dataImage reads a ref back to the data: URL. A ref whose
  picture has gone draws nothing.
- Sessions: the recorded input drops the base64 outright, since the
  page shows a picture as [image].
What goes upstream, what the archive stores, and the Recent calls'
body are unchanged.

Run (mote, through mote-run):
- go test ./internal/gateway -run 'Prompt|Context|Conversation|
  DeepSeek|Archive|Image|Lean|FileID': ok.
- go test ./internal/gui -run 'Context|Gateway|Sessions': ok.
- go vet: darwin gateway+gui, GOOS=linux -tags nogui, GOOS=windows.
- gofmt -l: clean.

TestFileIDConversationStillShows covers chat, responses and anthropic.
Each sends a 36 MiB turn of three 12 MiB pictures through the fake
DeepSeek, which names them by file id. It checks:
- the card draws all three, from memory and from the archive;
- the chat text is still there;
- the Sessions transcript holds the turn's text and three [image].

Broken by hand, each one red:
- wiring removed: memory, 0 pictures drawn;
- the archive's cap put back before the lean: archive not read;
- the conversation lean removed: the transcript keeps only the reply,
  cut:true (the reporter's "会话内容也看不到了");
- the ref not resolved: memory, 0 pictures drawn.

Not tried:
- the reporter's real DeepSeek account and the GUI by eye. No GUI file
  changed, so the GUI suite was not run.
- masking turned on explicitly with a lean body. The refs are plain
  text, so they are not expected to match a mask.
- Sessions read from an agent's own transcript (Claude Code, Codex)
  never pass through the gateway, so #5407 cannot touch them.

Reported-by: matrix0487
2026-11-06 13:42:40 +08:00
yetone ef176e21f6 sessions: a Claude Code session moved with /cd is listed under its new folder
usrname1833 on Discord (#feedback, 11-05): after Claude Code's /cd the
session's file is in the new folder's .claude/projects directory, while
magpie kept showing the session under the folder it was started in.

What /cd does (Claude Code 2.1.316, read in the binary and run for real
in a sandbox CLAUDE_CONFIG_DIR against a fake API): relocateSessionTranscript
renames projects/<old>/<id>.jsonl and its <id>/ folder to
projects/<new>/, and appends {"type":"relocated","relocatedCwd":"<new>"}.
The lines from before keep the old cwd; a second /cd adds another line,
and the last one names the folder.

Cause: a Claude Code session's folder was its first line's cwd only, and
a relocated line went to the default case. Every place that groups or
resumes by folder (GUI, TUI, `magpie sessions`, stats, the resume
command's cd) reads Session.Cwd, so all of them showed the old folder.

- claudeLine reads the relocated line (ccRelocated): the last move's
  folder is the session's.
- A parse kept by an earlier magpie isn't read again when the file
  hasn't changed. One whose folder isn't the project folder the file is
  in (ccStale, with Claude Code's own name: non-alphanumerics as "-",
  past 200 cut and a hash added) is read again once. state.CdRead marks a
  parse made by this reader, and a kept one in its right folder is marked
  on the first refresh, so the name isn't worked out on every poll.
  parseVersions isn't raised: that would read every Claude file again.
- A glance (a long file's row before its first read) takes a relocated
  line in the last 64 KB too.
- Sibling, magpie's own project move (relocateClaudeJSONL): a /cd'd
  session was judged by its first cwd, so moving the folder it was moved
  to failed with "a different project cwd", and relocatedCwd was never
  rewritten. It now judges by the last move and rewrites relocatedCwd.
- docs/subsystems/gateway-sessions.md says how the folder is found.

Fixtures (internal/sessions/testdata/claude-cd) are Claude Code
2.1.316's own lines from that run, paths written as /w, without request
records, attachments and file snapshots.

Run (mote, at a754660b2 + this):
- go test -count=1 ./internal/sessions ./internal/tui ./internal/cli: ok.
  ./internal/gui: ok but TestMainWindowCorners/macOS_26_SDK, which is
  #3949 (macOS 27 on mote), not this change.
- GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: ok.
  gofmt -l: clean.
- wsl-run go test ./internal/sessions: ok.
- win-run go test ./internal/sessions: the new tests ok; TestAgySessions,
  TestAgyRowOnly (#4115) and TestCCListingKeepsItsNames (#4925/#5277) are
  red on Windows the same on a754660b2 alone.

Red on the old code (a754660b2 with the new tests):
TestClaudeCdListedUnderNewFolder (under /w/projA, resume cd '/w/projA')
and TestClaudeRelocationAfterCd ("a different project cwd").

Broken by hand, each red: ccRelocated not called (ListedUnderNewFolder,
KeptParseReadAgain); ccStale always false (KeptParseReadAgain); the kept
parse not marked (KeptParseReadAgain); the glance tail skipping relocated
lines (TestClaudeCdGlance); relocateClaudeJSONL not resetting the first
cwd on a move, and not rewriting relocatedCwd (RelocationAfterCd).

No GUI file changed and the GUI tests stub /api, so no GUI test was run.

Not tried: the reporter's own files; the fixed build against a real /cd'd
session in the app (only the package's listing, Find and resume command
in tests); a /cd across WSL, or Windows paths beyond the vet and the
package run there.

Reported by usrname1833 on Discord.
2026-11-06 07:32:04 +08:00
yetone 24d315fa85 routing: the request list can be grouped By key, each gateway key's calls under its name
acezan (#help on Discord) asked to see API use on the Routing page the way
it shows each agent's, live and in the history. The list's group bar gets
a third button, By key, after By request and By session. It shows once
Settings has a gateway key (/api/caller-keys). Each head is the key's
current name (else the name the route kept, else its id), with its agents
dim beside it and the usual count, tokens, in progress and cost. Calls with
no key (from this computer, or kept before 75fb76186 named the key) go
under "No gateway key". A row's tooltip names its key too. The choice is
kept in localStorage (magpie.routingGroupBy), and the old
magpie.routingBySession still works. Text added in zh, zh-TW, ja and de.

click-scroll counted two group buttons and now counts three, with By key
hidden when there is no key. purpose-filter clicked .last() for By
session and now picks [data-by="session"].
reference.md and gateway-sessions.md describe By key and Route.CallerKey.

Run (WSL magpie-desktop: mote's disk is full, ld errno=28):
- routing-by-key.test.cjs: 20/20 in chromium and webkit, in en, zh,
  zh-TW, ja and de, at 1100 and 420. Red 20/20 with client.js and
  i18n.js at the parent (waits for By key).
- 254 Routing-related GUI files at concurrency 4. Every red was rerun
  serially, with this change and at origin/main 73c98ebc2.
  - Only purpose-filter and click-scroll were this change's; both are
    fixed above and green now.
  - The rest are red at main too, or flake there: #5045 call-headers,
    #4385 click-scroll wheel, #5049, #1745, #4689, #3402, #4623, #1937,
    #3773 idle-frame (10 frames, passes on rerun), plus routing-rule-*,
    zero-priced-free and others under #4121/#4400.
- Windows: go test ./internal/gui. Reds are #4115/#1827, plus
  TestPluginAgentMissingSaysSo and TestGatewayHeldByAContainer, red at
  main too and filed now as #5324.
Not tried: the real app, the whole GUI suite, the tray panel (no By key
there). A key renamed after a row was drawn shows its old name in that
row's tooltip until the row is drawn again.
2026-11-05 14:47:18 +08:00
yetone f44fa2ef6a sessions: gateway mode lists only the gateway's sessions, never this computer's agents' files
paultian on Discord: magpie web in gateway mode, on a machine with Claude
Code and Codex installed, listed that machine's own sessions beside the
ones other computers sent through it. Owner's call (via the lead): keep
Sessions in gateway mode, scope it.

- sessions.OwnOff (set by the gui to ownSessionsOff): while it holds,
  currentReads answers "none", Found and Dirs are empty, the trash lists
  and restores/purges only what the gateway kept, and moving Claude
  Code's folder is refused. Every route built on Reads follows: the list,
  one, transcript, markdown, export, stats, overview, search, manage,
  delete, carry, Usage's agent-file calls. Gateway-recorded sessions
  (ledger projection, recorded conversations) are not behind the gate.
- ownSessionsOff: magpie web's page, and Settings' gateway mode On, or
  Automatic with --gateway or no agents found (looked at once per 30s,
  and again on another HOME/PATH). A turn of the answer resets the
  sessions' caches and stats; the gateway-mode route does it at once.
- /api/sessions/reads says gateway:true: the page asks nothing, its empty
  state names the gateway's sessions (en/zh/zh-TW/ja/de), and Settings ›
  Privacy leaves out Agents' session history.
- The gateway-mode subtitle (5 languages), docs/reference.md and
  site docs/docker.html (en/zh/ja) say Sessions stays and what it lists
  (they said there was no Sessions tab, which was already wrong);
  docs/subsystems/gateway-sessions.md has the design.
- Tests: Handler marks the process as magpie web for good, and 13 tests
  served magpie web's page, so a later test's sandbox could be in gateway
  mode by itself. webPageHandler ends the mark with the test, and
  TestWebPageHandlerEveryWhere fails on a direct Handler(webHost{...}).

Ran (mote, at this tree rebased on origin/main):
- TestGatewayModeListsNoOwnSessions: red on the old code, green now.
- gateway-mode-sessions.test.cjs: chromium + webkit, en 900/390, zh,
  zh-TW, ja 420, de 390: 36/36; red on the old client.js (every case).
- GUI files the change reaches (gateway-mode*, sessions-*, session-*,
  privacy-*, usage-sessions-*, i18n-keys), both engines: 657/657.
- TestCoreScriptBudget ok.
- go test -shuffle=on ./internal/gui ./internal/sessions: sessions ok;
  gui ok but TestMainWindowCorners/macOS_26_SDK, red the same on
  origin/main 2f726b1f9 on mote (#3949).
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of both
  packages; gofmt -l clean.

Broken by hand: OwnOff answering false (the Go test goes red on the list,
stats, manage, one, transcript); the Purge guard and the Restore guard
each (red on purge / restore); the old client.js and settings.js (the GUI
test red). An injected stale agents memo and leaked webPage did not
reproduce the one TestUsageRequestContent red seen in the first package
run; it did not come back in two more runs, one shuffled.

Not tried: a real magpie web on a server with real agents on other
computers; the Go test on Windows and Linux boxes; the 30s memo under
real use.
2026-11-04 20:20:41 +08:00
yetone 43849d51c3 routing: By session heads a session by its title, its folder quieter beside it (flandern1211_58540 on Discord)
Routing's By session headed each session "Claude Code · folder · title",
and with no title only the folder and id ("路由这里的会话名只能看到目录名和
会话ID吗"). Now the head is the agent and the session's title on one
line (whitespace folded), with its folder after it in a quieter .dir; with
no title the folder stands in, and with neither the id. The tooltip keeps
the title, the folder and the id.

The title comes from what magpie already reads, no second reader:
sessions.Titles (the agent's own title, else its first prompt) and Codex's
name index, and where both find nothing, the first prompt the gateway
recorded for that session (sessions.GatewayTitler, the title the Sessions
page shows for it), looked up under the agent the page names and the one
the gateway records it under (usage.AgentOf). A Codex thread Codex never
named now goes to sessions.Titles as a codex: key, so its rollout's first
prompt names it. withGatewayTitles and codexReadableTitles in trace.go.
Nothing is read that the Sessions page doesn't show already, and nothing
leaves the local GUI.

Tests: TestSessionTitlesFallBackToFirstPrompt (new): an unnamed Codex
thread gets its first prompt, a named one keeps its name, an unknown id
stays out, a pi session known only to the gateway gets its first words.
routing-session-folder.test.cjs follows the new head: title then .dir,
the first prompt on one line, the folder said once, the id with neither,
nothing clipped (chromium and webkit, en zh zh-TW ja de, 1100 and 420px).

Run on mote via mote-run, at origin/main e7b0c398e plus this change:
- Whole Routing GUI set (routing-*, panel-routing*) + i18n-keys,
  chromium and webkit: 2583 pass, 35 fail. Every red is a known one:
  rule-remove (#3096), rule-drag (#3789), row-swap (#3799),
  order-unknown (#4627), rules-line (#3593), many-keys, steady,
  steps-cap and story-shrinks (#5088), and under the load of another
  session's whole GUI suite (load ~200) routing-credits webkit ja 420
  (#5161) and routing-flood webkit en (#2215). Run again: credits 20/20
  and flood 12/12 here; order-unknown's webkit de 420 red the same at
  e7b0c398e alone.
- routing-session-folder: 20/20 (both engines, 5 languages, 2 widths).
- go test ./internal/gui: TestSessionTitlesFallBackToFirstPrompt ok;
  red only TestCoreScriptBudget (1534001 > 1533802, the same at
  e7b0c398e, #5139: this change adds nothing to the core scripts) and
  TestMainWindowCorners (the same at e7b0c398e, #3949).
- Rebased onto origin/main 1a67ca614 (its routing client.js changes
  merged clean), at this commit: routing-session-folder 20/20,
  routing-session-title 40/40, routing-kept-again 20/20,
  usage-compact-counts 30/30, routing-live-calm 2/2, i18n-keys 4/4, and
  go test ./internal/gui -run 'TestSession|TestCoreScriptBudget' ok
  (the budget passes at this base). The whole Routing set was not run
  again here. Then onto 0f1b40bbc (routing client.js and css again,
  merged clean): routing-session-folder 20/20, routing-live-bytes
  20/20, routing-live-calm 2/2, i18n-keys 4/4.

Broken by hand:
- withGatewayTitles a no-op: TestSessionTitlesFallBackToFirstPrompt red
  ("titles = map[]").
- client.js back to the old head: routing-session-folder red in every
  engine, language and width.

Not tried: the real app with real Codex, Claude Code and gateway-only
sessions (fixtures only), the Linux WebKitGTK app, Windows.
2026-11-04 19:43:00 +08:00
yetoneandFlandern e7b0c398ee sessions: find a ZCode title by its gateway id (#5195)
ZCode sends its session id to the gateway without the sess_ prefix stored
in its database. Routing asks Titles with that bare id, gets no title, and
falls back to the folder name even though the Sessions page can show the
real title.

Titles treats zcode:<id> as an alias for zcode:sess_<id> when it reads
local session files, and returns the title under the key Routing asked
for (the sess_ key too, which callers ignore). A regression test uses the
database id shape ZCode writes and the bare request id it sends.

Ported from Flandern's b1a952b73 (fix/zcode-routing-session-titles on
flandern12111/magpie), code and test unchanged, reviewed line by line;
the body is rewritten (the original had literal \n's), and
gateway-sessions.md says it.

Run on mote via mote-run, at origin/main c7bbd3faf plus the change before
this one: go test ./internal/sessions -run
'TestZCodeTitlesByRequestID|TestSessionTitles|TestTitles|TestZCode'
-count=1: ok. Again at this commit on origin/main 14f6d10de: go test
./internal/sessions -count=1 ok.
  Pushed on c4245c4c2, which changes only internal/gateway's
  object_root and its doc after 14f6d10de; not run again on it.

Broken by hand: the alias lookup removed, TestZCodeTitlesByRequestID red
("zcode:578bd3d1-…: title \"\", want \"A ZCode session's title\"").

Not tried: a real ZCode session through a running gateway.

Co-authored-by: Flandern <3180066912wzw@gmail.com>
2026-11-04 18:33:07 +08:00
yetone f8987ce617 gateway: Qoder 1.1.82's requests find their session in Qoder's own files
qodercli/qoderclicn 1.1.82 (11-03) stopped sending session-id to a
provider of the user's own, and nothing else in a request names the
session (coderlee233 on Discord). Its requests were recorded with no
session: the Sessions page lost the conversation's title and showed each
title and suggestion side call as a row of its own.

A request from Qoder or Qoder CN (by its agent token) on this computer
that names no session is now matched against Qoder's session files
(sessions.QoderDir/projects/<project>/<id>.jsonl and its subagents'
files): the session whose typed prompts (user lines with humanInput /
origin.kind human) appear most in the request's user text wins, the file
written last on a tie. Qoder's <system-reminder> blocks are left out. A
side call (no tools) no file matches yet is held up to 600ms, since the
first title is asked ~0.1s before Qoder writes the file. The id found
goes on the request as session-id, the header 1.1.81 sent, so it is
grouped and titled as before. A request that names a session (older
Qoder's session-id, X-Magpie-Session) is left as it came. Files are read
incrementally; a half-written last line waits for the next read.

Run (on mote, rebased on origin/main 6b47bce67):
- go test -run TestQoder ./internal/gateway: ok. Fixtures are the literal
  bodies and headers qodercli 1.1.82 sent to a capture server, and its
  own session files, from a sandbox HOME (headless turns, a subagent, a
  second headless session, interactive turns, first title, later title,
  transcript title, suggestion).
- go test -timeout 45m ./internal/gateway and the full suite run after
  the push (mote at load 200 from another suite); a red is filed.
- gofmt -l; GOOS=linux and GOOS=windows go vet ./internal/gateway: clean.
Broken by hand, each red: no qoderSession call in handle; no
named-session guard; no agent check; subagent files not read; array
content not read; no wait for side calls; no newest-file tie-break; a
half-written line taken.

Not tried: the reporter's own account or a real model (fake upstream
only); Qoder in WSL (its files are in the WSL home, not found from the
Windows magpie); a keyed or MAGPIE_ADDR gateway on another machine (not
matched by design). The in-flight Active session (status bar) is not
fed from this. A large session file is read whole once per process.
2026-11-04 16:45:47 +08:00
yetoneandSKYhuangjing 2741b749f9 sessions: a codex fork's rollout-<n> turn does not end the copied head (#5090)
ownTurn ended a Codex fork's copied head at the first turn id the parent's
file didn't hold (fb1f4856a). codex-rs names a turn that has no id of its
own "rollout-<n>" (the rollout canonicalizer's implicit turns; the
thread-history builder), and a copied head can carry one the parent's file
lacks. It was taken for the fork's first own turn, so every copied
checkpoint after it was booked as the fork's call: July and August usage
that was the parent's history over again. Reporter: SKYhuangjing, whose
fork branch codex-fork-head-marker (acb034645) this ports.

ownTurn now leaves a "rollout-" turn id alone. callParseVersions and
parseVersions raise codex to 3, so kept shards and call caches are read
again once (the same one-time re-read the codex 2 raise cost).

Changed from the patch: the code comment and the subsystem page
(docs/subsystems/gateway-sessions.md) say what codex-rs does, not what
the reporter's corpus showed; the test comment names #5090.

Checked, not changed: ZCode's fork path (zcDB.copied) matches copies by
the original message id and never reads a turn id; ownTurn has one
caller (codexUsageState.context).

Run (mote-run, at this tree on origin/main + this commit):
- TestCodexForkHeadMarkerDoesNotEndTheCopies red with ownTurn as on
  origin/main (4 calls on the fork, want 1), green with the fix.
- go test -count=1 ./internal/sessions ./internal/usage ok; gofmt -l clean.
- GOOS=windows and GOOS=linux go vet ./internal/sessions clean.
Not tried: the reporter's real database (we have no copy of their
corpus). Not confirmed: codex-rs main has no writer that puts a
turn_context with "rollout-<n>" into a forked file from
record_initial_history, as the issue says; the prefix is confirmed from
the two codex-rs writers above, but which one produced the reporter's
files is unknown. Not handled: a fork whose own first turn is itself a
"rollout-<n>" (a legacy rollout migrated with no ids) still doesn't end
the copies by turn id; checkpoints still match it as before.

Full suite: run after the push, result on #5090.

Co-authored-by: SKYhuangjing <13705011+SKYhuangjing@users.noreply.github.com>
2026-11-04 09:10:52 +08:00
yetone fb1f4856a8 sessions: a fork's own calls are counted; only its copies are the parent's (ZCode, Codex)
Sky (skyhuang1994) on Discord, on their real ZCode database after
v0.1.2847 (1d0fc2bb0): September's message table holds 57,787 rows,
13.552B tokens; 5,204 rows (1.537B) carry a forkOrigin and are copies,
and ZCode's cloud usage says 12.057B. The new version took 5.094B out,
3.6B of it real. The biggest was the "msc" session: forked at the end of
August, then 11,409 calls of its own in September (3.489B), none with a
forkOrigin, a custom-UUID provider. The Usage page had 0 of them.

Cause (ZCode): readZCodeCalls marked copies in a map keyed by m.ID. A
row's id is in the message table's id column, not in its data (OpenCode
writes data without id; checked on this machine's real opencode.db: 2 of 2
rows have no $.id), so every message decodes with ID "". One copy in a
session set copies[""], and every assistant message of that session was
left out: a fork that went on working lost all of its own calls. The test
fixtures had "id" inside data, so they never saw it. The Sessions page
(parseOpenCode) asks zcDB.copied per message and was right.
Fix: copies are marked by row index. Only a message whose forkOrigin
names a messageId still in the database is skipped.

Codex: a fork's checkpoint was a copy whenever its {total, last} was one
the parent's rollout holds, anywhere in the fork. A fork goes on working,
and its first own call can carry exactly the numbers of the parent's
next call after the fork (same history, same next prompt). The copies
are now the head of the fork only: the fork's first turn_id the parent
never had (turn_context or task_started) ends them (ownTurn,
CopiedTurns, read with the parent's checkpoints). A rollout with no turn
ids is matched as before; its running total keeps later calls apart.

callParseVersions codex 2, zcode 2 and parseVersions codex 2, so the
parses kept by v0.1.2847 are read again once. ZCode's Sessions parse
didn't change and stays at 1.

Tests (fixtures follow Sky's case: a parent of 08-30, a fork with
forkOrigin copies of its replies, ZCode's fork notice, then 40 replies of
its own in September with no forkOrigin, no id in data, provider a UUID):
- TestZCodeForkThatWentOnWorkingKeepsItsOwnCalls: red on origin/main
  7d022bdb6 ("the fork's calls: 0 {...}, want its 40 own"), as Sky saw.
- TestCodexForkThatWentOnWorkingKeepsItsOwnCalls: red on main and with
  ownTurn turned off by hand (1 call on the fork, want its 2 own).

docs/subsystems/gateway-sessions.md says this.

Run on mote (mote-run) at this change on origin/main 7d022bdb6; rebased
on 08d7bfaaa (gui, redact, gateway-key only), go build ./... and
internal/sessions run again: ok.
- gofmt -l internal: empty
- GOOS=linux go vet -tags nogui ./... ; GOOS=windows go vet ./... : ok
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage
  ./internal/tune ./internal/otlp ./internal/davsync ./internal/tui : ok
- go test -run 'Session|Usage|Calls|Ledger|Stats|ZCode|Codex|Fork'
  ./internal/gui ./internal/cli : ok

Broken by hand:
- the copies keyed by message id again (origin/main): the ZCode test red,
  0 calls on the fork.
- ownTurn's call in context() off: the Codex test red, 1 call on the fork.

Not tried:
- Sky's real ZCode database; there is none on this machine and no ZCode
  source to read its writer. That ZCode's data has no id, as OpenCode's,
  rests on the symptom (every row of the fork gone) and OpenCode's real
  rows here.
- a real forked Codex rollout that went on working; the turn ids of a
  real 0.117 fork were read from the fixtures' shape, not a real file.
- the whole gui and gateway suites, and a full go test ./...: other
  sessions' suites were running on mote.
2026-11-03 20:21:17 +08:00
yetone 1d0fc2bb08 sessions: a fork's copies of its parent's calls are counted once (Codex, ZCode)
Sky (skyhuang1994) on Discord: on ZCode, 10-31 showed ~0.70B GLM-5.3
tokens where ZCode's own model_usage had ~0.28B. A selection side chat
opened on 11-02 from a 10-31 session holds a copy of its 860 assistant
messages, with the 10-31 times and the same 421,041,276 tokens, and made
no calls. On Codex, a week of 2026-03 read 5,136,041,178 gpt-5.4 tokens,
where the machine had spent ~0.27B.

ZCode: ZCode 3.17's CLI copies a session's messages (gce, for a side
chat, a fork and a checkpoint restored) with a new id and session, the
original's time, model and tokens, and metadata.forkOrigin
{sessionId, messageId}. zcDB.copied says a message is a copy of one still
in the database, and readZCodeCalls and parseOpenCode (for ZCode) leave
it out. A copy of a copy names the copy it came from, so of each chain
one is counted. A copy whose original is gone is counted. ZCode's own
fork notices carry a forkOrigin with no messageId, and are not copies.

Codex: a fork (/fork, spawn_agent with the parent's context) writes every
line of the parent's rollout into its own first, token_count events too,
stamped at the fork's time (codex-rs 0.117 record_initial_history,
InitialHistory::Forked). Each copied checkpoint was booked as a call on
the fork's day. The fork's session_meta has forked_from_id. The parent's
rollout is found in the same Codex home: the UUIDv7 day of its id ±1
day, then every day, then archived_sessions. Its checkpoints, {total,
last}, are read once (8 parents kept), and a fork's checkpoint found among
them only advances the running total, on Usage (calls) and Sessions
(stats) both. A parent not found leaves the fork read as before.

callParseVersions and parseVersions raise codex and zcode to 1, so their
kept parses are read again once. The version tests (call_versions,
parse_versions, cache_decode) now hold the versions at none raised: they
test the mechanism, not the current numbers.

docs/subsystems/gateway-sessions.md says all of this. Filed #5072:
OpenCode's fork copies the same way and names no original, so it is
still counted twice.

Run at this head on mote (mote-run):
- gofmt -l internal: empty
- GOOS=linux go vet -tags nogui ./... ; GOOS=windows go vet ./... : ok
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage
  ./internal/tune ./internal/otlp ./internal/davsync ./internal/tui : ok
- go test -run 'Session|Usage|Calls|Ledger|Stats|ZCode|Codex'
  ./internal/gui ./internal/cli : ok

Broken by hand:
- zcDB.copied returning false: TestZCodeCopiesCountedOnce red. msg_c1 and
  msg_d1 were counted as calls, and the Sessions page's 10-31 read
  {1200 300 1800} for {400 100 600}.
- the copied() check in count() off: TestCodexForkCountsOnlyItsOwnCalls
  red. 4 calls on the fork, {87984 5950 268416} for {45744 3550 179584}.

Not tried:
- a real ZCode database or side chat. There is none on this machine.
  The copy shape was read from ZCode 3.17.2's zcode.cjs (gce).
- a real forked Codex rollout or one from 2026-03. ~/.codex/sessions here
  spans 2026-07 to 11 and has no forks. The fixtures follow codex-rs
  0.117's writer. Whether Sky's 5.1B week is all fork copies is not
  known; a cumulative count read as per-turn in an older format was not
  found in that source.
- newer rollouts' token_usage_record copies in a fork, and a parent in
  another Codex home (WSL, CODEX_HOME).
- the whole gui and gateway suites. Another session's suite was running
  on mote; gui and cli ran only the tests above.
2026-11-03 19:13:00 +08:00
yetone 69167bc299 usage: a reply let go under a second after a wait four times longer tells no speed
pluviophile714 on Discord: a gpt-6.1-sol row on Routing read 1,539
tok/s (input 21,617, output 392, first token 8.2 s, total 8.3 s), where
another monitor measures ~70. The reply came whole about 255 ms after an
8.2 s wait. Its content was spread over that short window (flow 230 ms),
so the HeldShare flow check passed, and so did the 100 ms floor, and
392/0.255 s read as 1,539 tok/s.

New rule, usage.HeldWindowMs: a window under 1,000 ms whose start
(first token, first text or first reasoning) is more than HeldShare (4)
times the window tells no speed. One rule in every place that computes
one:
- usage.DecodeOf: the Usage page's speed and totals, the CLI, the GUI's
  model speeds, and the gateway's Speed first pacing (noteTrySpeed);
- routing/client.js decodeOf: the Routing row's speed and its story line;
- usage/page.js ledDecode, plus a ledNoSpeed_ reason for the dash's
  tooltip, in en, zh, zh-TW, ja and de.
docs/reference.md and docs/subsystems/gateway-sessions.md say so.

On the owner's usage.jsonl (read only), 103 of the 106 rows over 600
tok/s were such windows (e.g. 448 tokens in 107 ms after 8.1 s) and are
dropped. The 3 that stay have windows of 2 to 5 s. The overall speed
goes from 103.8 to 97.9 tok/s.

What it costs: a short reply that really streamed after a long wait
tells no speed either. The live visible-reasoning fixture (76 tokens
over 731 ms after 6.8 s, ~104 tok/s) and #2637's grok record (307 tokens
403 ms after a 4.6 s first token, 531 tok/s) now read "—". Their tests
keep their guarantees with the same timings after a short wait, and also
check the long-wait case.

Tests:
- New: internal/usage TestShortWindowAfterLongWaitTellsNoSpeed (the
  reporter's numbers, a reasoned row from the ledger, the boundary, a
  second after a long wait, Totals) and internal/gateway
  TestShortWindowAfterLongWaitNotesNoPace.
- GUI: usage-speed-every-row has the reporter's row (dash, and the
  tooltip in all five languages); routing-burst-speed has it (first
  token 8.2 s, no tok/s).
- Updated to the new rule: TestVisibleReasoningSpeed's decode-minimum
  and max-speed cases (short wait now), TestCodexTurnMeasured...'s
  gateway/Claude rows, TestLiveVisibleReasoningFixture and
  TestUsageIngestTellsSpeed.

Run on mote at this tree (rebased on e41ef6288):
- go test -timeout 45m: internal/usage ok, internal/tui ok.
- internal/gateway: red only in TestCompactionOverByteCapEveryTime
  (#4862, full package run; passes 3 of 3 alone).
- internal/gui: red only in TestMainWindowCorners (#3949, macOS 27).
- internal/cli: red only in TestEveryRouteHasACommandOrIsNamed (#5026,
  red on main since 0872bc2a0).
- The two speed fixtures that failed in the gateway run pass on rerun.
- GUI, chromium and webkit: 36 files (every speed, ledger, i18n,
  routing-request and burst file), 609 tests, 603 pass. The 6 reds are
  usage-ledger's "newest live route needs no return-to-live button"
  (#5048, #4078, #3104 on main).
- Rebased on 1af868a15 (f0e0385a0 changed routing/client.js), then
  run again at the pushed head: internal/usage ok; the gateway speed
  tests (-run ...Speed|Pace|Decode|TTFT...) ok; 8 GUI files (both
  speed files, routing-request-metrics/-model, routing-speed-first,
  i18n-keys, reasoning-speed, usage-speed-tip) 94 of 94 in both engines.
- gofmt -l clean. GOOS=windows go vet of usage, gateway, gui and cli ok.
  GOOS=linux go vet of usage and gateway ok; gui and cli need cgo/GTK
  for Linux, the same on main.

Broken by hand: with the check off in usage.go, client.js and page.js,
the new Go tests, TestCodexTurnMeasured..., TestLiveVisibleReasoningFixture,
TestUsageIngestTellsSpeed and both GUI files (1537 tok/s shown) go red.

Not tried:
- the reporter's own request;
- a real GPT stream, to confirm that a 255 ms window after 8.2 s is a
  held reply from this vendor;
- the whole GUI suite (no new API call or layout change);
- the Linux and Windows app.
2026-11-03 17:01:51 +08:00
yetone c28220a5e7 sessions: a Codex thread saved on another provider resumes from Sessions
mrten_95615 on Discord: opening a Codex session from Sessions ran
`codex resume <id>` and Codex 0.166 stopped at "This chat uses custom,
but your current provider is magpie. Switch to custom to continue."
(modelProviderMismatch). Codex 0.166's app-server resumes a thread only
on the provider it was saved with (its state-database row, else its
session_meta), checked against the one config.toml (with -c) selects
(codex-rs app-server config_manager.rs load_for_resume); no flag lets a
resume go on another provider, and a provider config.toml no longer has
fails as modelProviderNotConfigured. Codex 0.165 resumed it on its own
provider without asking.

sessions.ResumeNow is the line that runs when the user opens a session
(GUI Terminal, TUI enter); the listed line is unchanged and nothing more
is read on a listing. For a Codex thread saved on a provider other than
the one Codex is on:
- config.toml still has that provider's table, or it is a Codex
  built-in (openai, amazon-bedrock(-runtime), gcp, ollama, lmstudio):
  `codex resume -c model_provider=<it> <id>`. Codex runs that embedded
  (no shared daemon) on the thread's own provider.
- the provider is gone: MoveCodexProvider moves the thread to the
  provider Codex is on (files copied to magpie's trash first, the state
  row too) and it resumes there, the only way Codex resumes it at all. A
  thread written to in the last minute or open in a Codex is left
  (ErrActive) and the plain line runs.
A WSL distro's Codex session and every other agent are as listed.

Run at this head (mote):
- go test -count=1 -run 'TestCodexResume|TestMoveCodexProvider|TestCodexProviderIn' ./internal/sessions: ok
- go vet ./internal/{sessions,gui,tui}, GOOS=linux -tags nogui and GOOS=windows vet of them: ok; gofmt -l: clean
- At this head (rebased on origin/main bf05291e2): go test -count=1
  ./internal/sessions ./internal/tui: ok; ./internal/gui: ok but
  TestMainWindowCorners/macOS_26_SDK (#3949, mote is macOS 27; this
  change touches only gui/sessions.go's terminal route); go vet darwin,
  GOOS=linux -tags nogui, GOOS=windows of the three: ok; gofmt -l clean.
- Full suite before the rebase (go test -tags nogui -timeout 45m ./...
  on mote, at eb779ce92 + this change): 86 packages ok; internal/gateway
  red on TestCodexPoolSaysTheClientsVersion alone (#4807, open, a full
  package run's known red). Not re-run after the rebase.
Broken by hand: ResumeNow returning the listed line, TestCodexResumeOnItsProvider
fails "resume ... && codex resume 01a0bdc9-..., want ... codex resume -c
model_provider=custom 01a0bdc9-..."; with the move dropped it fails
"the thread's rollout wasn't moved to magpie".
Real Codex: codex-cli 0.166.0 (npm darwin-arm64) in a sandbox
CODEX_HOME with two fake Responses servers: a thread made on "custom",
config.toml switched to magpie. Plain `codex exec resume` failed with
the reporter's modelProviderMismatch; ResumeNow's line resumed it and the
turn reached custom's server. With custom's table removed, plain resume
failed with modelProviderNotConfigured; ResumeNow moved it and the turn
reached magpie's server. The TUI `codex resume -c model_provider=custom`
was also driven in tmux (resumed, turn on custom, "Running without the
shared background server" warning). Codex 0.165.0 resumes it plainly.
Not tried: a Codex profile that names its own model_provider (a -c
override may lose to it); the Codex desktop app's resume; Windows'
PowerShell line (same flag, not run there).
2026-11-03 10:50:30 +08:00
yetone 6a6e4fefac sessions: WorkBuddy AI's own sessions are listed under its name (maxleebeta)
maxleebeta (Discord #general) is signed in to both WorkBuddy builds, the
China one and the international one, and the international one was
missing from an agent list. The provider side lists both: provider.All()
and CatalogFor have workbuddy/* and workbuddy-ai/* models under "WorkBuddy"
and "WorkBuddy AI". The sessions package, though, read only ~/.workbuddy.
WorkBuddy AI keeps the same files in ~/.workbuddy-ai (its product.json
dataFolderName, as internal/agent wires it), and nothing read them. So
WorkBuddy AI was missing from the Sessions page's agent picker, from
Usage > Sessions' agent strip, from the reading consent's folders and
from the usage ledger.

Changed:
- WorkBuddyAIDir and workbuddyAIFiles read ~/.workbuddy-ai/projects as
  agent workbuddy-ai with WorkBuddy's parser, in allFiles, Dirs,
  callSources (wholeCallReaders), Deletable and Found.
- buddyDir picks WorkBuddy AI's own models.json for the
  call-through-magpie skip.
- A ~/.workbuddy-ai that is a link to ~/.workbuddy is read once, as
  WorkBuddy's.
- skillsCounted names workbuddy-ai (WorkBuddy's parser counts no skills).
- docs/subsystems/gateway-sessions.md has a line for it.

Tests:
- TestWorkBuddyAI checks sessions, cwd, title, tokens, Deletable, Found,
  calls, the skip of magpie's gateway, and the link.
- TestWorkBuddyAIGatewayIsItsOwn: one model id that WorkBuddy's
  models.json gives to magpie and WorkBuddy AI's gives to the user's own
  provider.
- TestWorkBuddyAISessionsListedUnderTheirName checks /api/sessions,
  /api/sessions/manage and /api/sessions/stats: name "WorkBuddy AI",
  icon workbuddy-color, deletable.

Broken by hand (each went red): allFiles, parserFor, Deletable, Found,
the call sources, the wholeCallReaders entry, buddyDir.

Run on mote at this head (base origin/main c86fa2a34):
- gofmt -l and go vet for darwin, GOOS=linux and GOOS=windows -tags nogui
  (internal/sessions, internal/gui): clean.
- go test -tags nogui -timeout 45m over sessions and every package that
  imports it: ok for sessions (after the skillsCounted line), agent, cli,
  davsync, gui, otlp, tui, tune and usage.
- internal/gateway failed only TestCodexPoolSaysTheClientsVersion, which
  is #4807 (red in a full package run on mote, another test's Codex
  identity reaches it). Nothing here touches it.

Not tried:
- The reporter's screenshots, which we couldn't download, so their list
  may be another one.
- A real WorkBuddy AI install.
- The Agents page's detection of a newer, renamed WorkBuddy AI bundle
  (5.9.3).
- Windows.
- WORKBUDDY_CONFIG_DIR set: both apps then use that folder, and its
  sessions are listed as WorkBuddy's.
- No GUI JS changed (the page reads the agents from the API), so no
  Playwright files were run.
2026-11-03 08:54:40 +08:00
yetone 1829cd52ff sessions: a poll while a session grows makes only the rows it shows
VeryBTC on X (tweet 2117104179454091396) reported RSS that rises and
stays up while the window is open and a long-context session is active.
In that case every Sessions poll sees a changed file and rebuilds the
list. That rebuild copied every gateway-only session three times
(GatewaySessions, listedGateway, gatewayListed) and made each one a
Session row before EachMerged stopped at its 5000-row limit. It also
made every Claude Code file's path and key again.

- usage.EachGatewaySession walks the projection without copying it.
  gui's listedExternal stops at the list's limit and skips hidden
  sessions and sessions without an agent or id, as listedGateway did.
- sessions.EachMerged sorts indexes and makes a row only when the merge
  reaches it. The order is unchanged: newest first, stable on ties.
- listCCFiles reuses the last listing's path and key strings while a
  folder lists the same names. One file new or gone is stepped over.
  This holds ~32 B per file (~480 KB at 15k files), and the strings are
  shared with the listing it already held.
- page_memory.go's ~330 MB comment now has current numbers.
  gateway-sessions.md describes the lazy rows.

Per poll, on mote (go test probe through the real /api/sessions
handler, TotalAlloc):
  15k sessions x 10 turns, 400k ledger rows
    after a session file grows  150.6 MB, 201 ms -> 109.9 MB, 170 ms
    unchanged (warm)             17.2 MB         ->  12.0 MB
  3k sessions x 40 turns, 150k rows (no gateway-only rows past the cap)
    after a session file grows   31.3 MB         ->  29.6 MB
    unchanged (warm)              4.5 MB         ->   3.4 MB
  /api/usage is unchanged at 0.4 MB.

Tests:
- TestSessionsListMakesOnlyTheGatewayRowsItShows (gui) uses 3 natives,
  6000 gateway sessions in tied pairs, one hidden and one carrying a
  native's id. At limits 5, 40 and 6010, and with no limit, the rows
  equal the old pipeline's (listedGateway + gatewayListed +
  MergeExternal) after the JSON round trip. A grown native comes first
  with its new Last. The poll's allocation stays under 6000 rows' size.
- TestEachMergedMakesOnlyTheRowsItReaches (sessions): 15000 externals
  and 20 rows give MergeExternal's first 20, with allocation under a
  tenth of the rows.
- TestCCListingKeepsItsNames (sessions): a second listing of 3000 files
  is equal to the first, in at most 3n mallocs. A file added, files
  removed, and a folder gone with another new each list as a fresh
  listing does. Another agent's keys keep their own prefix.

Broken by hand, each red:
- EachMerged building every row first: 8.8 MB, the sessions test fails.
- The GUI handler back on the listedGateway(GatewaySessions) loop, with
  the lazy merge kept: 13.7 MB, the gui test fails.
- The gui test on origin/main's code: 23 MB, fails.
- The ccNames reuse turned off: 12197 mallocs, the listing test fails.

Run on mote (mote-run) at 73a1b8769, rebased on origin/main 07f4d46c5:
gofmt -l internal (empty), go vet ./..., GOOS=linux go vet -tags nogui
./..., GOOS=windows go vet ./... all clean. go test -count=1 -timeout
45m ./internal/sessions ./internal/usage ./internal/gui: sessions ok,
usage ok. gui is ok except TestMainWindowCorners/macOS_26_SDK, which is
#3949 (red on mote's macOS 27, an AppKit title bar test this change
doesn't reach). It was red the same way in the run before the rebase.

Not tried:
- A real app window with RSS measured over time. The numbers are
  allocation per poll from a probe.
- The rest of a changed poll: statsKept re-sums every session (~26 MB at
  15k), listing (~24 MB) and byKey (~9 MB). None was a cheap, safe
  change.
- Windows and Linux test runs (vet only).
- A gateway title store in the fixture. GatewayTitler's ReadDirs now run
  only for the rows shown.
2026-11-02 17:19:23 +08:00
yetone 276c806db2 plugins: a plugin's own requests are counted; a provider plugin's options get the editor (plugins#592)
zelong77 asked for two things once Devin 0.1.30's cache keep-alive
worked: its pings were invisible in magpie, and the interval and ping
count could only be edited in plugins.json. The owner decided pings are
shown as counted usage and the two numbers are edited in the GUI.

- host.js gives plugins input.magpie.usage(provider, call) and
  input.magpie.account(provider). usage validates the call (kind
  [a-z0-9_-]{1,40}, a model id, whole-number tokens from 0, status at
  most 999, error clipped to 500) and sends an unasked "usage" event;
  host.go hands it to plugin.OnUsage in the background.
- internal/usage/plugin_calls.go writes each one as a row of agent
  magpie on the plugin's provider (provider.PluginID) and account
  (provider.PluginAccountUser), with its kind. It is counted, priced
  and in every total, not a probe. Kind cache_keepalive is in the
  purpose catalog as "Cache keep-alive" (five languages), so the
  request log names and filters it. The ping itself still goes straight
  to Devin, never through the gateway, which would break the cache.
- /api/plugins reads every plugin's package options example, not only a
  middleware's or request hook's, and the Installed row offers the same
  Options JSON editor for a provider or agent plugin that suggests or
  has options (not while it is off). Clear's confirm no longer calls
  them a middleware's options.
- The Devin mover's min is 0.1.31, which reports each ping and gives
  its two settings' defaults (285 s, 6) to the editor. npm has 0.1.31
  (published 10:03Z); the plugins publish run is red only for
  think-tags' known E404 (plugins#180).
- docs: provider-plugins.md (the API, the options editor),
  gateway-sessions.md (the counted row beside probes).

Run at this tree (rebased on origin/main 85e37162e):
- mote (mote-run): go test -count=1 -timeout 45m ./internal/plugin
  ./internal/usage ./internal/gui ./internal/provider: plugin, usage,
  provider ok; gui red only in TestMainWindowCorners/macOS_26_SDK, the
  macOS 27 red already filed as #3949 (not this change's code).
- mote: GOOS=linux and GOOS=windows go vet of plugin, usage, provider ok;
  gofmt -l clean.
- mote: plugin-provider-options.test.cjs (new, 5 languages, 980/420px,
  Chromium + WebKit), plugin-gateway.test.cjs and i18n-keys.test.cjs:
  28 of 28 pass.
- The whole GUI suite (make test-ui) on WSL magpie-desktop (mote was at
  load ~100 with other sessions' suites, #4125), at the 8f804396f base:
  cut off after 498 test entries, when the session's background jobs
  were killed; 495 ok, 3 red, none on a page this change touches. Run
  again alone at origin/main 85e37162e, the same files are red there
  too: account-eye webkit (#4244), agent-expand-steady webkit 980px
  (#2935), add-button zh's 3000ms waitForFunction (filed #4792). The
  rest of the suite was not run.
Broken by hand (each red, then put back):
- host.go dropping the "usage" event: TestPluginReportsOwnUsage fails.
- plugins.go reading optionsExample for middleware/hooks only:
  TestProviderPluginOptionsExample fails.
- purpose.go without the Cache keep-alive kind:
  TestPluginKeepaliveIsCounted fails (purpose {}).
- plugins.js without ownOpts: plugin-provider-options.test.cjs times
  out waiting for the Options button in every language.
Not tried: a real Devin account's keep-alive ping reported into a real
magpie (needs a live Devin conversation idle for 285 s); a plugin can
report a row for any provider id, as magpie.load can.
2026-11-01 22:14:19 +08:00
yetone b52c39b65e routing: an account's row names the session it answers
connor_yang (Discord #help) asked that the Routing stage say which
session an account is serving next to its "answering…" / "answered this
request" status. The row now ends "· <title>", one line cut short with
the full title on hover, and only when the agent itself named that
session:

- Claude, Gemini and the other agents: sessions.Titles by agent:id, the
  same source the By session list heads use.
- Codex: its own name index (session_index.jsonl) by thread id.
- A Codex request whose parent the server inferred from prompt and
  reply fingerprints (parentMatched) shows nothing, since that parent
  is a guess. An untitled session shows nothing too.

Cost: no new server path. The titles come from the existing
/api/gateway/session-titles calls that refreshSessionNames already makes
every 15s and on focus. A session id the page hasn't seen is asked for
once (marked asked before the fetch, 300ms debounce, never two calls at
once), and the ask is skipped when a read since then already covered it
(namesDue). The per-second render only reads two maps. The title sits in
its own nowrap span, because the narrow stage (.max560/.max460) wraps
the status.

A Codex names reply silent on a session no longer clears the title
the trace brought. CodexTitles leaves unknown ids out, and returns {}
when the index can't be read, so the old loop turned a failed read into
"no title". With the earlier ask it also raced the trace: routing-sessions'
"title helpers belong to the named parent" went red 3 of 6 runs under
--test-concurrency=4 until this change, then 6 of 6 green.

Run:
- routing-session-title.test.cjs (new): engines x claude/codex x en, zh,
  zh-TW, ja, de x 1100/420px = 40 tests. Chromium 20/20 on mote.
  WebKit 20/20 on the Linux box (wsl-run, magpie-desktop). On mote even
  a bare webkit.launch() timed out at 60s under other sessions' load (21,
  67 pw_run processes), so WebKit there tested nothing.
- 16 nearby routing GUI files (answered-still, row-reuse, row-two-lines,
  stage-routes, sessions, reroute-title, tick-no-layout, live-patch,
  busy, served, js, steady, steady-garbage, session-folder, live-calm,
  request-model) in Chromium and WebKit on the Linux box, before the
  rebase onto 82b45888a. The reds that came back were compared with
  origin/main in a detached worktree:
  - routing-steady "requests coming in leave the routing groups" is red
    in both engines at main 03f609e3f (#3412).
  - routing-request-model's 5 WebKit cases are red at main 82b45888a,
    run alone (#4120 lists them).
  - routing-sessions "background memory groups" WebKit en is red at
    82b45888a, overflowing at 560px (filed #4538).
  - routing-sessions "title helpers" was mine; fixed above.
- After the rebase and the last edits, routing-session-title,
  routing-sessions, routing-session-folder and routing-rest-error
  (82b45888a's test, whose lines in client.js this change meets), three
  times per engine at --test-concurrency=4: Chromium 59/59 each time;
  WebKit 59/59 once, then 58/59 twice, the one red being #4538.

Broken by hand:
- titleOf without the parentMatched check (and the Codex name loop
  without it): the Codex cases go red, "a matched session's title is
  not shown".
- askUnnamed asking again on every pass: red, "asked 4 more times in 3s"
  (again on the final code).
- The silent-reply guard was not broken by hand on its own. What shows
  it is the title-helpers race above (3 of 6 red without it, 6 of 6
  green with it), not a deterministic test.

Not tried: a real app with a real agent's sessions, WebKitGTK in the
Linux app, and the whole GUI suite (it runs after the push).
2026-10-31 15:43:31 +08:00
yetone 7bc602236b library: the MCP hub is called the MCP router
The owner asked why it was a "hub". Composio calls the same thing a Tool
Router; "router" says what it does (one server that routes each call to
the right one), and "gateway" is taken by magpie's LLM gateway. Only
the words change: MCP router / MCP 路由 / MCP 路由 / MCP ルーター /
MCP-Router, "Router address", and the CLI's `magpie library mcp router
on|off`, where `hub` still works. The URL /mcp/magpie/hub, the mcpHub
setting, the servers/hub API and the Go names stay, so nothing a user
or an agent config holds changes. docs/subsystems/mcp-hub.md moves to
mcp-router.md and the pages that link it follow.

#4382's new words follow too: "Through the MCP router", "Not through
the router" and their hints in every language, and the CLI's
`magpie library mcp router <name> shared|direct` (`hub` works there
too; library_hub_test.go says router for direct, hub for shared).

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.
The CLI's TestProviderAddressMovesALocalServer red at -count=3 was
the same on origin/main 380032cda and is fixed in 65c792410.
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.
2026-10-31 02:49:08 +08:00
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 1bbaded622 usage: an agent's call to magpie's own MCP tools is a row of Requests
ferock (Discord) asked to see calls to magpie's MCP tools, such as
magpie-image's generate_image, generate_video and generation_result, in
Routing > Requests.

Each tools/call to magpie's own MCP servers (image, vision, web search,
tools and the Library hub) is now a row of the request log. The row has
Source and Kind "mcp", the tool as its model, the server as its host,
how long the call took, and its error if it failed. The provider and
model it shows are those of the model requests the call made, collected
through the request's context in appendUsage. generation_result names
the model of the job it answers. The stdio Magpie Image server reports
each call it answered to the gateway as "magpie/toolCalled". That report
carries the tool, ms, model and error, never the prompt.

The arguments are never stored at all, so there is nothing to mask. The
rows go down the probe lane: they are listed, but no total, host list,
budget or key limit counts them. The model requests a call made are rows
of their own.

In the GUI the row reuses the Requests list. It gets a muted "MCP" badge
with a tooltip, the server beside the provider, and a Succeeded/Failed
status. The Purpose filter gains "MCP tool" in every language. There is
no new page, no <select> and no left border.

The core scripts went over their budget with the new purpose.
genpurposes now writes purposes.js as compact JSON, which makes the core
448 bytes smaller than main in all, and coreScriptBudget is lowered to
the new total, 1,538,975. No room is added.

Run on mote, at the rebased head:
- gofmt -l: clean. go vet -tags nogui ./... with GOOS darwin, linux
  and windows: ok.
- go test -tags nogui -timeout 45m: ./internal/usage, ./internal/imagemcp,
  ./internal/usageapi and ./internal/gui ok. internal/budget has no test
  files. ./internal/gateway (805s): every test ok except five Antigravity
  and Codex/Grok tests. They fail the same on a clean origin/main
  3bebc3839 and are filed as #4362.
- GUI, the usage-ledger*, routing-request*, purpose*, i18n* and
  gui-zh/ja/de files (25). On mote, Chromium: 32 of 32 ok; WebKit
  could not launch (10 other sessions' suites on mote). On Linux
  (wsl-run), both engines: 335 of 355 ok. The 20 reds are
  routing-request-model, usage-ledger, -ttft, -chart and
  -open-settled, which fail the same at the parent 1534474c8 (#4120).
  usage-ledger-mcp, purpose-filter and i18n-keys are ok in both.
  The whole GUI suite runs after the push, and each red it finds gets
  an issue.
- At the pushed head, rebased on 0804f2d97: ./internal/gui (the
  budget and purpose asset tests among them), ./internal/usage,
  ./internal/imagemcp and ./internal/usageapi ok, and ./internal/gateway
  -run "MCP|Purpose|Probe" ok.
- usage-ledger-mcp.test.cjs covers 5 languages, widths 1180 and 420,
  light and dark, with no sideways scroll.

Broken by hand. Each break went red:
- sawHost's MCP skip removed: TestMCPCallRowsListedNotCounted (the hosts
  list had magpie-image).
- Row/Record.IsProbe's MCP case removed: the same test (3 calls counted),
  and TestMCPCallCountsInNoKeyLimit (Calls: 1).
- The callMCPTool hook removed: TestMCPToolCallIsARequestRow and its
  siblings (no rows).
- The appendUsage hook removed: the row had no provider or model.
- imagemcp's report removed: TestToolCallsAreReported.
- The gateway's magpie/toolCalled case removed:
  TestMCPCalledFromStdioIsARow.
budget's in-memory counts() now skips these rows too. Breaking only that
stays green, because budget.Of reads the file through usage.Visit, which
already skips probes, and limits count tokens and cost.

Not tried:
- no real agent calling a real vendor's drawing;
- no test run on Windows or Linux;
- the page not checked in the real app or in WebKitGTK.
A generate call that answers while its drawing still runs has no model on
its row. The generation_result row that follows names it.
2026-10-30 15:00:16 +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 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 ec789445db gui: Settings' session rows are the sessions plugin's settings.js; app.js back under its budget
af8f3a939 (session reads, RustCats on X) added Settings › Privacy's
Agents' session history to app.js and took it to 1,314,299 bytes, over
its 1,311,735 budget, and the core scripts to 1,535,027, over 1,532,459:
TestCoreScriptBudget red on main.

Moved, not raised: renderSessionReads and loadSessionReads (Privacy's
Agents' session history) and renderSessionTerminal (General's Session
terminal, data-feature="sessions") go to plugins/sessions/settings.js,
loaded after app.js like plugins/gateway and plugins/search's settings.js
and drawn whether the plugin is on or off. The code is moved as it was;
app.js calls them by name as before. app.js is 1,310,042 and the core
1,530,770, both under budgets left as they are. Docs: gateway-sessions.md
and plugin-runtime.md name the new file.

Run on mote at this tree (on af8f3a939):
- go test -count=1 ./internal/gui: TestCoreScriptBudget ok; red only
  TestMainWindowCorners/macOS_26_SDK, the same on main (#3949, open).
- GUI, Chromium and WebKit: i18n-keys, sessions-reads (5 languages,
  390-900 wide), session-terminal, account-discovery, settings-general:
  every case ok.

Not tried: the real app.
2026-10-30 00:14:37 +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 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 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 012c584cc1 usage: clear a model's usage, or all of it, from the Usage page
CrazyMouse_TT on X asked for a way to clear usage, all of it or one
model's, to measure a local model fresh after deploying it.

The Usage page's Models list has a "…" on each row (and a right-click
menu) with "Clear usage…", and "Clear all usage…" sits under the lists
below the "Counted from…" note. Each asks first, in a confirmation that
says what is deleted, that it can't be undone, and that key spending
limits and allowances still count the calls.

A clear is a mark in settings (usageCleared: provider, model, unix ms),
read at read time; usage.jsonl is never rewritten. The Overview hides
calls up to the mark in summarizeFrom; the Requests page, heatmap and
ledger/CSV hide them in Filter.keepsRow, their one choke point, and the
request index's meta carries the marks so its cache is dropped. Key
budgets, window holds and Codex reads go through usage.Visit and the raw
log, so a clear never resets a key's spending limit or a quota. A later
clear of the same model or of everything takes the place of an earlier
one. The marks ride the settings part of a sync (sync-backup.md) and a
save of the Settings page keeps them (api.go's keep list; the guard
test TestSettingsSaveKeepsWhatItDoesNotSend caught it missing).
gateway-sessions.md and sync-backup.md say so.

Run on mote (mote-run) at this tree, rebased on origin/main c26b2992e
(the Go packages and usage-clear.test.cjs; vet and the 68 GUI files
ran at the earlier base f835bd713, four commits behind):
- go test -tags nogui -timeout 45m ./internal/usage ./internal/settings
  ./internal/usageapi ./internal/gui: all ok after the
  keep-list fix (before it, TestSettingsSaveKeepsWhatItDoesNotSend red).
- gofmt -l: clean. GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: exit 0. (Linux vet without nogui fails in
  wails' cgo, as on main.)
- usage-clear.test.cjs: 32/32 in Chromium and WebKit, en/zh/zh-TW/ja/de,
  at 1200, 560 and 390 (web). With the old page.js/client.js/i18n.js it
  fails (TimeoutError).
- 68 GUI files the change can reach (every usage-*, gui-de/ja/zh-tw,
  i18n-keys, click-scroll, idle-ticks, mobile-web, panel-usage,
  sessions-purge): 941/980. The reds are filed and red on main
  (usage-ledger run alone at origin/main 84a6a2c42 too): i18n-keys "masking…" (#4053), mobile-web
  (#3952), usage-agents-hide (#2276, #3414), usage-ledger "newest live
  route needs no return-to-live button" (#3104, run alone at main too).
  i18n-keys first also named "Clear usage…" in Go comments of this
  change; reworded.
Broken by hand, each red: hides() always false (usage and gui tests),
keepsRow's clear check removed ("Requests after the clear: 5 rows"),
clearedKey out of the request meta ("after clearing everything: 3"),
the api.go keep line removed (UsageCleared [] after a save).

Not tried: the full go ./... suite and the whole GUI suite (mote was
busy with other sessions' full suites), the real app, a sync between
two computers. usage.jsonl doesn't shrink, and the Sessions tab's
figures are not cleared.
2026-10-28 21:13:09 +08:00
yetone 7c900f468f antigravity: a tier Google refuses in fetchAvailableModels is asked once a day and is no "Model list" row (ferock4669)
ferock4669 on Discord: with an Antigravity subscription, the Requests
page filled with "Model list" (模型列表) rows for
/v1internal:fetchAvailableModels, each answered 400.

Cause. For an account loadCodeAssist gives a paid or non-free tier,
magpie asks fetchAvailableModels first with entitlement.userTier named
(7806395c7: the paid tier, then the current tier) and, on a refusal,
again without one. The only real paid account seen (#1553, AnxForever's
log: free-tier, paid g1-pro-tier, aicode-consumers) gets 400
INVALID_ARGUMENT "Request contains an invalid argument." for the named
tier and its list from {project} alone. magpie remembered nothing, so
every list (start-up's FetchNew, the hourly relist, Refresh, sync) and
every quota reading sent that 400 first, and each list ran under a
probelog KindList mark, so the refused request was written down as a
failed model_list row (quietProbe hides only answered lists). The list
itself came from the second request. The request without a tier is
what CLIProxyAPI, sub2api and Antigravity-Manager send; the value the
official client puts in userTier for a paid account is still not known
(Antigravity isn't installed on any box here, nothing captured in the
repo), so the request isn't changed beyond not repeating the refusal.

Now:
- a tier Google answers 400 is left out of that account's
  fetchAvailableModels (lists and quota readings) for tierRefusedFor
  (24h), keyed by refresh token, project and tier, so a tier the account
  newly has is still asked; a 503 or other failure doesn't rest it;
- a request with a tier named is sent under probelog.Taken: a step
  towards the list, no row of its own; the request without one is
  written down as any list, so a list that really fails is still one
  400 row under Failed;
- googleAccount.call returns codeAssistError carrying the status, with
  the same message text as before.
Retries: FetchNew asks an account with no list at most every
newFetchRetry (1 min) while a page is open, the relist hourly; with this
a refused tier adds no extra request to either.

Docs: gateway-sessions.md (a list's step is no row) and
providers-accounts.md (askTiers, tierRefusedFor).

Tests: TestAntigravityRefusedTierAskedOnceAndNoRow (#1553's replies:
three Fetches and a quota reading name the tier once, 5 requests, no 400
row; a day later it is named again; a list refused without a tier too is
one row "400 model_list /daily/v1internal:fetchAvailableModels") and
TestAntigravityTierNotRestedForOtherFailures (a tier answered 503 is
named again). Broken by hand on mote:
- without probelog.Taken: FAIL "a refused tier written down:
  {... Kind:model_list ... Endpoint:/daily/v1internal:fetchAvailableModels
  Status:400 ...}";
- without tierRefused: FAIL "asked 8 times, 4 with the refused tier
  named; want 5 and 1".
Both pass with the change, as do the existing tier tests
(TestAntigravityTierRefusedFallsBack, ...ProInvalidTierAsksWithoutOne,
...TierFreeAndKeptProject, ...ProAccountNamesItsTier).

Run on mote (mote-run), at efb55b5c9 + this change: gofmt -l on the
changed Go files prints nothing; go vet ./..., GOOS=linux go vet -tags
nogui ./..., GOOS=windows go vet ./... exit 0; go build, GOOS=linux go
build -tags nogui, GOOS=windows go build exit 0; go test -count=1 -tags
nogui -timeout 45m ./... under a sandbox HOME with pinned caches: exit
0, 77 packages ok, no FAIL. Rebased on origin/main b3edcabf2 (no change
to google.go, probelog or usage's probes) and ran internal/provider,
internal/probelog and internal/usage again at the pushed head: ok.
GUI suite not run: no file under internal/gui changes.

Not tried: a real Google AI Pro/Ultra account (none here), so the 400
in ferock4669's rows is matched to #1553's by shape, not by their log;
the official Antigravity client's userTier value for a paid account.
2026-10-28 19:07:21 +08:00
yetone f39fc3ac8b usage: a model list that was answered is no row of Requests (ferock on Discord)
ferock (Discord #general): Usage > Requests is full of rows like
"magpie · magpie's own · Remote magpie · API · Model list · 0 0 · 757 ms
· 200, GET /v1/models", which no tool of theirs sent.

Cause: ffe493773 (v0.1.1446) wrote every request magpie sends a
provider on its own into the request log (source "probe"): the editor's
Test and Detect APIs, and every model-list fetch. 0152f6696 then gave a
Remote magpie a 10-minute list schedule (KeepListsFresh), so each Remote
magpie added ~144 such rows a day. The same rows came from every other
automatic fetch: start-up's FetchNew, the panel's FetchNewSoon, the
Providers page's FetchNewBehind and any provider with a RefreshEvery.
They were already counted in no token, cost, chart, budget or quota
total, but they were listed and counted in the page's row total.

Fix: a model_list probe with a 2xx/3xx status and no error
(usage.quietProbe) is not written by usage's probelog.Sink, and is
skipped when the log's index parses one (logSnapshot.probes). This rule
covers every list fetch, whoever started it, so every sibling is
covered by one check. A list that failed is still a row (the Failed
filter finds it, and the row says why models are missing), and every
Test and Detect APIs row stays as it was. Older rows: the answered
model lists already in usage.jsonl stop being listed at the next start
of the index, with no rewrite. The lines stay in the file and nothing
reads them. Quota and usage polls and health checks were never written
there (only Test, Detect and list are marked by probelog), so nothing
else needed changing. The TUI and CLI have no request list. The heatmap,
Summarize, Load and the exports skipped probes already.

Tests:
- usage TestAnsweredModelListIsNoRow (new): 200 and 304 lists aren't
  written; a 503 and a connection-refused list are listed and Failed
  finds both; a 200 Test is listed; an old answered list line in the log
  is not listed, and Total is 3.
- TestProbeRowsListedNotCounted and the rename tests now use a failed
  list (a 200 one would no longer be a row).

Broken by hand, each red: quietProbe returning false (the 200 list
written and listed); the index's skip removed, Sink's kept (the old line
listed, total 4).

Run, on mote:
- go test -tags nogui -timeout 45m ./... at the pre-rebase head
  (b4f2fa9d3 on 0a7633136): every package ok, 76 ok, exit 0 (gateway
  547s, agent 298s, provider 167s, usage 48s).
- After rebase on origin/main 9ba3f049e (which touched neither usage
  nor probelog): go build ./...; go vet for darwin, GOOS=linux and
  GOOS=windows on usage and probelog; go test usage, probelog,
  usageapi, and provider -run Probe|Detect|TestTestWrites: ok. gofmt
  -l clean.
- GUI (no asset changed): usage-ledger*.test.cjs, ledger-*.test.cjs and
  own-requests.test.cjs, chromium and webkit, each file's languages:
  381 tests, 375 pass. The 6 reds are usage-ledger's "newest live route
  needs no return-to-live button" (en, zh, both engines), which is
  already filed as #3104. usage-ledger-probe passed in every language.

Not tried: a real Remote magpie over a day. The row filter was not
checked on a real usage.jsonl.
2026-10-28 09:42:21 +08:00
yetone 94c2aaecba usage: a deleted provider's tests stay listed under it, not its host (cybercaius)
cybercaius on Discord: one custom provider (example, on api.example.me)
was listed in the Requests page's provider filter under its id and its
host, and the host stayed after the provider was deleted.

The Add sheet's Detect, model-list and Test requests are sent before the
provider has an id, so probelog records them under the host asked
("a provider being added has no id yet"). 8e2ba36de (v0.1.1697, yyddbds)
lists those under the provider saved on that host now (Renames.ProbeOf),
but a deleted provider is on no host any more, so its probes went back
to the host beside the id its calls are kept under.

Now the log's index notes, as it reads each line, the provider each
host's calls went to (logSnapshot.hosts; "" once two providers were on
one host). probeProvider lists a probe recorded under its host by the
provider saved on that host, and with none there, by the one the log's
calls to that host were made under. A host two providers are or were
on, or none, stays the host, lowercased, so one typed in two cases is
listed once. It is done when the log is read, so rows written before
this release are merged too. Renames.OnHost tells "no provider on this
host" from "two providers on it", so a host shared now is never given
to a deleted one.

Not added: deleting a provider's usage rows. usage.jsonl is the record
budgets, windows and totals are read from, and probe rows are counted in
none of them; with them under one name there is nothing left to clean.

Run:
- go test -tags nogui ./internal/usage ./internal/usageapi
  ./internal/probelog: ok, at the pushed head (rebased on 56de2d192).
- ./internal/provider, skipping the reds open on main
  (TestUnreadLoginsWriteErrorsKeepCredentials #3632, TestFetchAsksASharedBaseOnce
  and its two siblings #3854): the disk was full from other sessions'
  temp files, and TestLoginUsageEachAccount failed on "no space left on
  device"; it and the Rename tests passed on a rerun.
- New TestProbesOfADeletedProviderStayWithIt: probes under
  api.example.me and API.example.me before provider.Add, a Test after,
  a gateway call with the provider's Where, and twice.example used by two
  providers; after provider.Delete the list is [example one
  twice.example two] and example's filter has its 4 rows.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Broken by hand: probeProvider without the log's hosts fails it with
"deleted: providers [API.example.me api.example.me example one
twice.example two]", the reporter's extra names.

Not tried: the reporter's own usage.jsonl; a host typed in the Add sheet
and changed before saving (its probes went to another host and stay
under it); the GUI suite (no GUI file changed; the filter lists what
QueryPage returns); the full go test ./... (disk full).
2026-10-27 18:32:44 +08:00
yetone b30734f964 sessions: Antigravity CLI (agy) conversations are listed, with title, folder, tokens and resume (RickyWei, #1718)
agy's conversations were on no Sessions page: internal/sessions had no
lister for them, only the calls reader of #2097. Now each
~/.gemini/antigravity-cli/brain/<id>/.system_generated/logs/transcript_full.jsonl
is a session (agy.go). Its steps give the start and last times, the first
prompt (taken out of agy's <USER_REQUEST> wrapper), prompts, replies, tool
calls, and tokens under the model "agy", since no step names one. A step
written again replaces its tokens, read on or read whole. The title and
folder come from the conversation's conversation_summaries.db row:
title, and workspace_uris through agyFolder, which turns file:///C:/... and
file:///c%3A/... into C:\... and a host into \\host\share on Windows. agy
writes the title after the transcript, so the row is the file's rev. The
database is read again only when it or its -wal changed, and a failed read
keeps the rows read before. A row with conversations/<id>.db and no
transcript (#1718's case) is listed from the row alone, with no tokens and
no conversation to open. Resume is "agy --conversation <id>". When agy is
set to use magpie, it is the agent's launch command (gateway variables and
--model, the PowerShell form on Windows) with --conversation after it,
through sessions.AgyStart, which package agent sets. The transcript (user
text, thinking, text, tool calls, tool results) can be opened and searched.

Format read from real files: agy 1.3.5 and 1.4.7 in a sandbox HOME
against a fake Gemini endpoint, with plain replies, a read_file tool call
with thinking, invalid tool calls, and a conversation picked up again with
--conversation from another folder. testdata/agy-sessions is three of
those conversations with paths rewritten to /work.

Resume tried for real in the sandbox: `agy --conversation <id> -p again`
from another folder appended steps 2-4 to the same transcript and kept the
row's folder. Interactive `agy --conversation <id>` (in tmux) showed the
earlier turns.

Run at this tree, rebased on origin/main:
- gofmt -l internal clean
- go vet: darwin; GOOS=linux -tags nogui; GOOS=windows
- GOOS=windows go build ./...; GOOS=linux go build -tags nogui ./...
- go test -count=1 ./internal/sessions ./internal/gui ./internal/agent: ok
  before the row-only change. After it, sessions ok, and gui had one red,
  TestMainWindowCorners killed at its 40s deadline at load ~300 (#1936).
  It passes alone (47s).
- GUI (playwright 1.62.0, chromium and webkit, en and zh): i18n-keys,
  gui-de, gui-ja, gui-zh-tw, session-terminal, sessions-bar-names,
  sessions-manage, sessions-talk, sessions-toolbar: 49 of 49. No GUI asset
  changed. Tab names come from the agent registry.

Fails without the change (broken by hand, each one red):
- agyFiles out of allFiles: TestAgySessions, TestAgyTitleLater, TestAgyTranscript
- agy out of refresh's DBRevision check: TestAgyTitleLater
- no dropUse of a rewritten step: TestAgyGrows (4510 input, want 3010)
- AgyStart ignored: TestAgySessions (wired resume)
- drive letter not handled: TestAgyFolder
- agy out of HasTranscript: TestAgySessions, TestAgyTranscript
- the row-only listing off: TestAgyRowOnly; readable() off: TestAgyRowOnly

Not tried: agy on Windows. The Windows box (10.0.0.132) didn't answer
ssh, so the Windows paths are covered by unit tests only (agyFolder,
the Set-Location resume form). A wired resume through magpie's real
gateway was not tried. Not done: subagents (parent_conversation_id),
which I never saw agy write. The model name, which is only in
conversations/<id>.db's protobuf (#3147). Deleting an agy session from magpie. agy in WSL: #3595.

Side effect: agy's self-updater ran in the sandbox and replaced the
live ~/.local/bin/agy, 1.3.5 -> 1.4.7.
2026-10-25 18:24:20 +08:00
yetone 15f0d4cdeb sessions: a Claude Code session goes on in Codex, and a Codex one in Claude Code
0xPlato on X asked for conversations to carry across agents, at least on
one machine. A session row's Continue in (换 Agent 继续) now offers Codex
for a Claude Code session and Claude Code for a Codex one, when the other
is installed. Picking it converts the session then: a new session in the
target's own store, which its own resume opens. Listing converts nothing.

- Claude Code to Codex: a rollout in CODEX_HOME/sessions/YYYY/MM/DD with
  session_meta (model_provider from config.toml now, no
  base_instructions, so Codex uses its own), response_items and the
  event_msg user/agent messages the TUI shows. Codex indexes it on
  resume itself.
- Codex to Claude Code: CLAUDE_CONFIG_DIR/projects/<cwd>/<uuid>.jsonl,
  lines chained by parentUuid, assistant model "<synthetic>" so usage
  counts no call for them.
- Carried: user and agent text, pasted images, shell calls natively
  (Bash and exec_command) with their output, other tools as the agent's
  text (name, input, result in fences, cut at 64 KiB). Dropped: thinking,
  reasoning, signatures, encrypted content, Claude Code's own and Codex's
  context messages. After a compaction only what replaced the history.
- The source is only read. The new file goes through temp, sync, rename
  and never over an existing path. Asking again for an unchanged file
  gives the same session (memo by path, target, size, mtime).
- POST /api/sessions/carry {agent, id, to, open}: copies the resume line,
  or with open (Mac app) opens it in the session terminal. The details
  pane's Continue in line converts from its copy button too.
- Read-only and WSL sessions get no offer. Pi, omp, OpenCode, Kimi,
  Cursor and the rest are not converted.

Run (worktree at 42976f9a0, rebased onto origin/main before push):
- Real use in a sandbox HOME (HOME, CLAUDE_CONFIG_DIR, CODEX_HOME under
  magpie-wt/carry-sb), real binaries Claude Code 2.1.310 and Codex
  0.162.1, through magpie's gateway:
  - Claude to Codex: a Claude session that ran Bash, Write, Read and Edit
    was converted. `codex exec resume <id>` answered what the dog was
    called, which command ran and what was added. `codex resume` showed
    the whole history in the TUI.
  - Codex to Claude: a Codex session with exec_command and apply_patch was
    converted. `claude -p --resume <id>` answered the colour, the commands
    and the function added. `claude --resume` showed the history in the
    TUI.
- Fixtures in internal/sessions/testdata/carry are those real sandbox
  files. Claude's attachment text (system prompt, instruction files) and
  api-request lines were taken out; the line chain is kept.
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/:
  sessions ok (15.7s), gui ok (119s), size budgets among them.
- Broken by hand, each red: Codex context kept (environment_context
  carried), no convert offer (all four TestCarry* red), images dropped
  (TestCarryImagesAndCompaction red). sessions-convert.test.cjs is red
  in chromium on the old client.js.
- GUI (playwright 1.62.0, chromium and webkit): sessions-convert in en,
  zh, zh-TW, ja and de, every sessions-*.test.cjs, i18n-keys,
  click-scroll, gateway-conversations: 424 of 424 pass.
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build.

Not tried: Windows and WSL with real binaries (WSL sessions get no
offer), images through the real binaries (round trip in tests only),
Open in session terminal on a real Terminal (the POST is tested, the
terminal path is the existing openTerminal), a Codex session compacted
by OpenAI (encrypted, not carried), and the full ./... suite.
2026-10-25 12:25:06 +08:00
yetone ff6090354e gateway: dsh's session and compaction marks are held on Messages and Responses too (#3298)
A user's own dsh llm-deepseek row pointed at magpie (e3491e2bb's docs)
calls /v1/messages with x-deepseek-harness-session-id and
x-deepseek-harness-compact. #2505 reads both in sessionOf/dshCompacts
for every route already, but TestDshMarksSessionAndCompaction only
covered /v1/chat/completions. TestDshMarksOnEveryRoute sends both marks
(and llm-deepseek's x-deepseek-harness-user-id) to /v1/messages on an
Anthropic provider and /v1/responses on a Responses provider, and checks
the recorded session, kind "compact" or none, and that the vendor gets
no x-deepseek-harness-* header. No behaviour changes: this guards what
the docs now tell users, and so it passes on the old code too.
docs/subsystems/gateway-sessions.md names it.

Broken by hand: dropping x-deepseek-harness-session-id from
sessionHeaders turns all four cases red (session ""); making dshCompacts
always false turns both compact cases red (kind ""). Restored after
each.

Run before the rebase onto 500aa7096: go test ./internal/gateway
-count=1 -timeout 45m (ok, 450s). At this head, after it (500aa7096
changes internal/sessions only): go test ./internal/gateway -run
'TestDshMarks|Session' ok, go test ./internal/sessions ok; gofmt -l internal/gateway empty; GOOS=linux and
GOOS=windows go vet ./internal/gateway ok. Real dsh 0.2.1-rc.2 through a
sandbox magpie recorded its session on /v1/messages (see e3491e2bb).

Not tried: streaming on these two routes in the test (the real dsh run
streamed /v1/messages), Windows test run.
2026-10-25 05:51:52 +08:00
yetone ffe493773c usage: magpie's own Test, Detect APIs and model list requests are rows of the request log, counted nowhere
neiko and gys619 on Discord: a provider's Test or Detect APIs left no
trace in Usage > Requests, so a failing test couldn't be read back.

The provider package marks the context of the editor's Test, Detect APIs
(and per-model detection) and a model list's refresh with a kind
(internal/probelog). Each request sent under the mark is written once:
by the provider's Do, or by probelog.Transport under http.DefaultClient
(netproxy.Install), whichever sends it first; the Claude Code run and
the gateway's translated test write theirs from their result. A row
keeps time, provider, account, model, host, path (no query, no
user:password), method, status, ms and the first 500 bytes of the error.

The row is usage.SourceProbe, agent "magpie", Kind provider_test /
api_detect / model_list ("Test", "Detect APIs", "Model list" in Called
for; purposes.js regenerated). The log index keeps probes apart
(logSnapshot.probes), so Visit, Load, Summarize, budgets, Vias, heatmap,
shared days, LastSeen and observers never meet one. The request page
lists them (probeChunk) and counts none: Row.IsProbe, since a packed row
keeps the row's Source and not its record's. The page shows a muted
badge "magpie's own · not counted in any total" (en, zh, zh-TW, ja, de);
no new control, no layout change.

Tests, each red on the old code:
- usage TestProbeRowsListedNotCounted: listed, clipped, and absent from
  Sum, Through, every By group, Summarize, Load, LastSeen, OwnDays and
  the observer; a provider filter lists it and sums 0.
- provider TestTestWritesItsRequestsDown / TestDetectWritesItsRequestsDown:
  every request the fake server saw is exactly one row, with the right
  kind, model and 401 text; an unmarked Do writes nothing.
- probelog TestNoteKeepsNoSecret, TestTransportOnce.
- GUI usage-ledger-probe: badge per language, both engines, 1180/420,
  light and dark, no left border, no sideways scroll.
- gui TestProviderDetectDraft now expects the log line (source probe,
  kind api_detect, no key) and leaves usage.jsonl out of the unchanged
  config comparison.

Broken by hand, each went red: request_page's uncounted check,
log_index's probe skip, Append's observer skip, Do's Taken (6 rows for
4 requests), Test's and Detect's marks, probelog's query strip,
page.js's badge (11 GUI fails).

Run at this head (on origin/main 22a7f86c9): gofmt -l clean; go vet
./..., GOOS=linux -tags nogui and GOOS=windows clean; go test -count=1
usage, probelog, netproxy, usageapi, provider and gui packages ok (the
rebase over 22a7f86c9 applied cleanly; upstream's 8b460833e chunk
cache leaves probeChunk, built per query, alone).

Run one rebase earlier (on origin/main 0b72ccbef; request_page.go
merged by hand onto 7d67910f7/66b6d6ade's per-row Totals, with
uncounted rows skipping the caller and account groups too):
- go test -tags nogui -timeout 45m ./... in a sandbox HOME, log tee'd:
  every package ok (gateway 640s, agent 514s, provider 278s, usage 77s)
  but internal/gui's TestRestartHandsTheGatewayOver (7 of 8 requests
  answered during the restart), 3 of 3 green alone after (#3451).
- gofmt -l clean; go vet ./..., GOOS=linux -tags nogui and GOOS=windows
  go vet ./... clean.
- GUI usage-ledger-probe, usage-ledger-reported, i18n-keys,
  purpose-filter, quota-pool-model: 72/72. usage-ledger's "newest live
  route needs no return-to-live button" is red on origin/main 0b72ccbef
  alone too (#3104).
- Whole GUI suite, both engines, at the pre-rebase base 761904b5a:
  1313 tests; reds, each also red on origin/main 7b1faf99f alone:
  account-discovery "agents' sign-ins read" (#3497), builtins
  "Plugins > Built-in" (Masking page in the list, #3518 filed), and
  context-map "two tiles overlap" chromium ja 420 (#3488; 1 of 2 red on
  main alone, 3 of 3 green on this branch alone). Earlier package run:
  TestRestartHandsTheGatewayOver red under load, passes alone (#3451).
- No size budget raised.

Not tried: no real vendor account (fake servers only); a plugin's model
list, fetched in the JS plugin host, isn't written down; the real GUI
app wasn't launched (Playwright only).
2026-10-25 04:12:06 +08:00
yetone ea9454d2d8 usage: count two ids of one model as one, magpie model alias (SlouchyQuill507 on Discord)
A vendor names one model two ways (deepseek-v4.1-flash and deepseek-flash),
and Usage, Usage > Sessions and `magpie usage` showed two rows. Now:

  magpie model alias deepseek-v4.1-flash deepseek-flash
  magpie model alias deepseek-v4.1-flash            (what it is counted as)
  magpie model alias deepseek-v4.1-flash --reset
  magpie model aliases

kept as settings.json "usageAliases" {from: to}. Off until one is written.
Ids match as routing groups match them (provider.sameModel: vendor/ prefix,
case, "_", snapshot date), at every provider; a chain is followed to its
end; an alias to itself, a loop, or a flag as an id is refused. A loop
written into the file by hand counts each model under its own id.

Display only: requests, agents' model lists, /v1/models, routing groups,
Same as and prices never read it. Each call is priced by the id it was
made under and only then counted under the alias; the alias's own price
is never put on the other id's calls, and a merged row is priced only
when every id in it is. Applied in usage summarize/direct (Models
groups), the gateway sessions projection (alias read before
gatewayCache's lock; the cache key hashes usageAliases), and
sessions.List/Get/Find/Stats (read before storeMu/mu, merged into new
slices so the memo is untouched; ModelEffort rows merged too). A failed
settings.json read keeps the last aliases read, and SetUsageAlias refuses
to write over an unreadable file (EditUsageAliases under fileMu). The GUI
settings save carries usageAliases. No GUI control.

Not aliased: the Requests ledger's per-request model and its model
filter, which show each call's own id.

Run (worktree at f4640c0ae, rebased onto 2b4c0664e with no overlap):
- gofmt -l: clean. go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows: ok.
- go test -count=1 -timeout 45m (sandbox HOME) internal/usage,
  sessions, provider, cli, settings, gui, tui: all ok.
- Real binary in a sandbox HOME: two usage.jsonl calls priced $2 and
  $100 per M: `magpie usage` showed two model rows ($2.00, $100), and
  after `magpie model alias` one row, 2.0M, 2 calls, $102; the session
  row too. alias/aliases/--reset/loop/self output checked by hand.

Broken by hand, each red then restored:
- no alias in summarizeFrom: TestUsageAlias* red
- nil alias into the gateway projection: TestUsageAlias* red
- statsIn without aliasStats / List without aliasSession:
  TestSessionsCountAliasedModelsAsOne red
- merged usage row keeps Priced true: TestAliasStatsLeavesItsInputAlone red
- loop check off / self check by == / last-good read off / flag check off:
  TestUsageAliasRefusesSelfAndLoops, TestUsageAliasUnreadSettings,
  TestModelAliasCmd red
- GUI save drops UsageAliases: TestSettingsSaveKeepsWhatItDoesNotSend red

Not tried: the GUI pages in a browser (no app.js change; the Usage and
Sessions pages read the same rows), the full go test ./... before push,
Windows box.
2026-10-24 02:48:50 +08:00
yetone 42e6aee534 sessions: the stats and id lookups don't build every session's subagents
Why: in a 48-minute heap profile of the user's magpie,
gui.combinedSessionStats → statsFor → StatsAndNative → statsIn
allocated 3.9 GB, and gui.warmSessions → Warm 5.7 GB. Their scans went
through assemble → subagentsOf → ccTask: the stats built every
session's subagents (each one's task read from its file), only to
count tokens and tell which sessions are listed. Every statsFor call
in the profile came from the warm-up's steps.

What changed:

- assemble is split. assembleListed holds the part that decides
  whether a session is listed and gives its agent, id, title, models
  and usage. assemble adds resume, carry, transcript and subagents on
  top.
- These callers now use assembleListed: the stats' native-key and
  summary loops (stats.go), Titles, the Codex provider lookup
  (codex_provider.go) and manage's id lookup.
- List, One and manage's listing still use assemble.
- The docs/subsystems/gateway-sessions.md subagent section says
  which callers build subagents.

Tests:

- TestStatsReadNoSubagentFile writes a subagent with no meta and no
  task in its first lines, then simulates a restart (Saved, Reset,
  memos cleared). It then runs StatsAndNative(0), StatsAndNative(30)
  and StatsFor(7) three times and expects 0 scans of that file. List
  still shows the subagent.
- Broken by hand: the stats back on assemble make it go red with
  "the stats read an unchanged subagent's file 1 times". Green again
  once restored.

Measured on a read-only APFS clone of the user's ~/.claude/projects
and ~/.codex/sessions/2026/10, in a sandbox HOME, at load ~500 from
other sessions. The whole series against origin/main dee5c9d75; this
commit is the change to the stats rows.

| Pass | origin/main | This series |
| --- | --- | --- |
| warm StatsAndNative(0) | 596.7 MB, 157,195 allocs, 6.2–9.0 s | 28.9 MB, 73,976 allocs, 0.08–1.1 s |
| warm StatsAndNative(30) | 594.9 MB, 6.8 s | 28.7 MB, 0.8 s |
| restart StatsAndNative(0) | 3,106.7 MB, 509,239 allocs, 30.0 s | 48.2 MB, 241,721 allocs, 1.9 s |
| restart StatsAndNative(30) | 594.9 MB, 9.6 s | 28.7 MB, 0.5 s |

Run at the final tree of this series:

- gofmt -l internal: nothing.
- GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean.
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/:
  - sessions: ok, 366.7s.
  - gui: only TestMainWindowCorners failed, "measuring the windows:
    signal: killed". It also fails alone on an untouched origin/main
    export, at load ~500. Filed as #1936 and #2645. Every other gui
    test passed.
- go test -race -count=3 on the new tests: ok.
2026-10-20 20:32:04 +08:00
yetone a23fbaeadf sessions: a subagent's file is read for its task only when its meta names none, once per change
Why: a 48-minute heap profile of the user's magpie allocated 6.3 GB
in sessions.scanAt, 3.5 GB of it from ccTask. The user has 3,174
Claude Code subagent files, 1,798 of them over 1 MB. Two things
caused it:

- subagentsOf titled each one `cmp.Or(m.Description,
  ccTask(f.path))`. Go evaluates both arguments, so every subagent's
  file was read for a first user line that was then thrown away
  whenever the meta file had a description, which is nearly always.
- ccTask kept only a found task. A file whose first 16 lines name
  none was read again on every ask.

What changed:

- Claude Code and Kimi subagent titles read the file only when the
  meta (or the spawn record) gives no description.
- ccTask keeps what it read, a task or none, with the file's size and
  mtime from before the read. An unchanged file isn't read again. A
  grown, rewritten (even at the same size), or touched file is read
  again from its first lines.
- A read that fails keeps the last good result, and a deleted file
  gives "".
- A line appended while the file is being read changes the size, so
  the next ask reads it.
- The docs/subsystems/gateway-sessions.md subagent section says so.

Tests:

- TestSubagentTaskReadOnlyWhenTheFileChanges counts scans through
  scanHook for these cases:
  - first ask: 1 scan;
  - unchanged: 0;
  - grown with a task: 1, then 0 once found;
  - grown after the task: 1;
  - rewritten shorter: 1;
  - rewritten with no task: 1;
  - same size with a new mtime: 1;
  - a task appended past line 16: 1 scan, still "";
  - appended during the read: found on the next ask;
  - deleted: "", 0 scans.
- TestSubagentWithMetaTaskIsNotReadForIt lists a session after a
  simulated restart (Saved, Reset, memos cleared) and expects 0 scans
  of a subagent whose meta names its task.
- Broken by hand:
  - ccTask back to keeping only a found task (`t.task != ""`) makes
    the first test go red: "unchanged, no task yet: 1 scans, want 0".
  - The title back to cmp.Or makes the second go red: "the list read
    a subagent's file 1 times for a task its meta names".
  - Both green again once restored.

Measured on a read-only APFS clone of the user's ~/.claude/projects
and ~/.codex/sessions/2026/10, in a sandbox HOME, at load ~500 from
other sessions. Times are noisy; allocations are not. Restart, then
List(All):

| Code | Allocated | Allocations |
| --- | --- | --- |
| ccTask keep, title still cmp.Or | 153.9 MB | 270,838 |
| this commit too | 25.8 MB | 109,854 |
| origin/main dee5c9d75 | 301.1 MB | 80,004 |

The origin/main row also lacks the buffer pool (a later commit).

Run at the final tree of this series:

- gofmt -l internal: nothing.
- GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean.
- go vet ./internal/sessions/ ./internal/gui/: clean.
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/:
  - sessions: ok, 366.7s.
  - gui: only TestMainWindowCorners failed, "measuring the windows:
    signal: killed". It also fails alone on an untouched origin/main
    dee5c9d75 export, at load ~500. Filed as #1936 and #2645
    (real-window AppKit tests killed at their deadline under load).
    Every other gui test passed.
- go test -race -count=3 on the new and neighbouring subagent and
  scan tests: ok.
2026-10-20 20:32:04 +08:00
yetone 38f6bee23e sessions: the manage page reads its agents' files once, and only the agents it shows (#2776)
GET /api/sessions/manage went over every agent's session files three
times: sessions.Agents() for the counts, sessions.List(All) only to build
the set that keeps a gateway session its agent keeps too from being
counted twice, and sessions.ListAgent for the list. List(All) also read
every agent's changed files again and put every session together, prices
and titles included, to take its id. So a page showing Claude Code's
sessions parsed Hermes's and Codex's writes too.

sessions.Manage now does it in one pass over the files, under one hold
of the locks: the counts, the ids of the sessions of the agents that have
gateway sessions (nativeIDs: the id from the file's key, or from its
parse for the agents that write it inside the file, idInFile, which are
the only ones read), then the picked agent's list. The handler's pick
runs as a callback so the counts can include the gateway sessions. A
change to an agent not shown and with no gateway sessions waits for a
page that shows it. assemble's id rule moved into sessionID, which both
use.

That set was also wrong in two ways. List leaves out a session nothing
was said in and stops at 5000 (All), while the list beside it keeps
every one, so a gateway session whose agent's file was empty (or among
the oldest of more than 5000) was counted twice and listed once. The
set is now every native session, the same as the list's, and
POST /api/sessions/delete, which tells a listed gateway session from a
native one, uses it too (sessions.NativeIDs).
docs/subsystems/gateway-sessions.md says so.

Tests:
- TestManageReadsOnlyTheAgentsItShows: Codex's files changed, Claude
  Code's page parses none of them; asked for Codex's ids it reads them;
  the native ids equal the list's, the empty session included. Red with
  Manage reading every file as List(All) did ("read 2 of them").
- TestManageCountsAGatewaySessionTheAgentKeepsOnce: a gateway session
  whose Claude Code file has nothing said in it is counted once. Red on
  the old handler: "one session listed, counted [{claude 2}]".

Measured on the synthetic sandbox HOME (3000 Claude Code, 1500 Codex,
2000 Hermes sessions; no gateway sessions), CPU time of the request
(load average ~250 from other sessions, so wall times are noisy), the
parent bbee24810 against this change, the same run of each:
  first manage?agent=claude after a restart  2164 -> 627 ms CPU
                                    (15697 -> 10554 ms wall)
  warm manage?agent=claude   173-222 ms ->  64-88 ms CPU
  warm manage?agent=hermes   176-243 ms ->  56-70 ms CPU
  warm manage?agent=codex    237-269 ms -> 155-162 ms CPU (after its
                             first, which reads Codex's model/effort)

Run: go test ./internal/sessions -count=1, go test ./internal/gui -count=1;
gofmt -l clean; go vet. Full suite and cross-OS vet are recorded on the
last commit of this series.
2026-10-19 03:57:52 +08:00
yetoneandcaozeal cb05dc2d1b sessions: CodeBuddy Code's own sessions are listed on the Sessions page, resumed with codebuddy --resume and deletable (#2657, caozeal)
CodeBuddy Code keeps its sessions as WorkBuddy does, ~/.codebuddy/projects/<cwd>/<id>.jsonl. magpie read them for the calls ledger (#1779) but never listed them: allFiles() and Dirs() left them out, parserFor sent them to the Claude parser, and Deletable didn't name the agent. caozeal's branch (85cc186a2) adds them to allFiles, Dirs, parserFor (workbuddyLine) and Deletable, with the meta cwd fallback WorkBuddy has, and the ledger reads through the same list. On top of it: the resume command is `codebuddy --resume <id>` (its CLI's `-r, --resume [sessionId]`, read from @tencent-ai/codebuddy-code 2.168.2's dist/codebuddy.js; codebuddy is one of the package's three bins). The Sessions page's and Usage > Sessions' agent label come from the agent registry (CodeBuddy Code, codebuddy-color) and needed no change; a test now holds them.

Fixtures are the real `codebuddy -p` runs already in internal/sessions/testdata/codebuddy (#1779).

Tests:
- TestCodeBuddy (caozeal's, extended): two sessions with their cwd, title and model tokens; the resume command on each OS's form; Deletable.
- TestCodeBuddySessionsListedUnderTheirName (new, internal/gui): /api/sessions, /api/sessions/manage and /api/sessions/stats name them CodeBuddy Code with its icon, resume command and trash.
- Broken by hand, each red: allFiles reverted and parserFor reverted ("want 2 CodeBuddy Code sessions, got 0" in both tests), resume reverted (resume ""), Deletable reverted ("not deletable", "offers no trash").

Run at e085d6e92 plus this change:
- gofmt -l internal/: clean. go vet ./... (darwin): exit 0. GOOS=linux and GOOS=windows go vet -tags nogui ./...: exit 0.
- go test -tags nogui -timeout 45m ./... under set -o pipefail: 64 packages ok, 2 red at load average ~110, neither ours:
  - internal/agent timed out at 45m (TestWSLMoreAgentsPick running; 2702.7s), recorded on #2544.
  - internal/gui TestRestartWhenIdle "restarted in a tool chain's gap" (30ms sleep vs 80ms idleSettle); passes -count=10 alone; filed #2673.
- After rebasing onto origin/main 7660399a1 (#2576, #2578: gateway model list, gui Claude Desktop chip): internal/sessions ok (169.6s) and internal/gui ok (303.7s) at the rebased head on 7660399a1.

Co-authored-by: caozeal <21231607+caozeal@users.noreply.github.com>
2026-10-17 14:05:17 +08:00
yetone ebf3f48f7f usage: a reported call takes first_text_ms and flow_ms, so a reasoning reply tells its speed and a burst is held (#2637)
POST /v1/magpie/usage/requests turned away first_text_ms and flow_ms as
"not a field a reported record takes", so a reported reasoning reply was
timed from its first reasoning token and a burst-at-the-end reply was
never held. The ingest now takes both, validated like ttft_ms (whole
milliseconds, 0..ingestMaxMillis, null = unset), and checks:
- first_text_ms <= ms, and first_text_ms >= ttft_ms when both are set
  (the first text is content too);
- flow_ms <= ms*10/8+1, since the gateway's flow is the tenth-to-nine-
  tenths span scaled by 10/8 and can exceed ms.
The fields reach usage.jsonl through the Record, so DecodeOf, Row.Decode
(ThinkPace, HeldShare) and the Reported totals read them as they do the
gateway's own rows. docs/reference.md and gateway-sessions.md say so.

Tests: TestUsageIngestTellsSpeed posts the reporter's literal repro
(grok-4.7, out 307, reasoning 129, ms 5035, ttft 4632, first_text 4700:
178 tokens over 335ms), a burst held by flow_ms, an even reply told, and
a ThinkPace hold, and checks the totals. TestUsageIngestTimesChecked
covers each bound, its edge, null and absent fields.

Broken by hand: old code fails both tests (field refused); dropping
FirstText tells repro-1 0; dropping Flow tells the burst 601/4035;
removing the ttft check accepts first_text 299 < ttft 300; bounding flow
by ms rejects the valid 1501.

Run at 8bb9375e7 + this diff: gofmt -l clean; go vet ./... on darwin,
GOOS=linux and GOOS=windows -tags nogui clean; set -o pipefail; go test
-timeout 45m ./... exit 0 (66 ok, gateway 1192s) under a sandbox HOME and
private GOCACHE (an earlier run against the shared cache had build
errors from cache files removed mid-run, not code). Machine load ~250.
Not tried with a real reporting client.
2026-10-17 10:14:03 +08:00
yetone a2c4aab1ba gateway: DSH's session header and compaction mark are recorded, also through a remote magpie (#2505)
h4rk8s asked that the Requests list tell DSH's context compactions apart
and attribute usage per DSH session, also when the call goes through
Remote Magpie, from the headers DSH sends and never from the prompt.

- x-deepseek-harness-session-id joins sessionHeaders, after the others:
  sessionOf / nativeSessionOf / conversationID take it, so usage, the
  Routing page and affinity see DSH's session, and passOnCaller already
  sends a native session header on to a remote magpie.
- x-deepseek-harness-compact set (any value but "", 0, false, no, off)
  makes callKind "compact", which PurposeOf groups as Compaction. Only
  display reads that kind; routing is unchanged.
- withCaller keeps the mark on the caller and passOnCaller sends it on to
  a remote magpie, so the other magpie records the call as a compaction
  too. Neither header reaches a vendor (the request to it is built fresh).
- docs/subsystems/gateway-sessions.md says so.

Run:
- TestDshMarksSessionAndCompaction: direct and through a remote magpie
  (two gateways over httptest), marked and unmarked with a summarizing
  system prompt. Red on the old gateway.go/codex_backend.go/
  remote_magpie.go (session "", kind "", remote sent neither header),
  green now; asserts the vendor saw no x-deepseek-harness-* header.
- TestRemoteMagpieKeepsTheSession still green.
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows.
Full suite: go test -tags nogui -timeout 45m ./... (pipefail, suite-lock) at the four #2494/#2504/#2505/#2490 commits on origin/main a751f5282: 65 packages ok, among them internal/agent (2124s), internal/gateway (1845s) and internal/sessions (148s). internal/gui was red on TestSetAnswersWhileDevinAndProvidersHang alone (the state after a set took 11.5s at load ~250; #1375); internal/gui run again alone: ok (206s).
2026-10-17 00:39:36 +08:00
yetone 6e17d58ebf usage: a top session only the gateway saw says "Gateway session", not "(no prompt)" with no folder (#2285)
The reporter's Usage › Sessions card listed seven Pi sessions on
deepseek-v4-pro as "(no prompt)" with no folder, and their routing group
has no DeepSeek. Those rows were gateway projections: Pi asked magpie for
deepseek/deepseek-v4-pro (every served model is in Pi's models.json), most
likely through a pi-subagents child, whose session file is in a temp folder
magpie never reads. The card gave no sign of that, so it read as Pi's own
sessions with an empty prompt, and our first reply took it that way.

The overview's summaries from MergeExternalStats now carry gateway: true,
as MergeExternal's list rows already did. The card shows "Gateway session"
where the folder would be, "(prompt not recorded)" as the title when no
text was kept, and a tooltip pointing to Record gateway conversations.
Strings in zh, zh-TW, ja and de. gateway-sessions.md says it.

Run in this worktree (a1f7b8c13 base):
- go test -tags nogui -p 1 -count=1 -run 'TestTopSessionsMarkWhatOnlyTheGatewaySaw|TestGatewaySession|Overview|Session' ./internal/gui/: ok
- go test -tags nogui -p 1 -count=1 -run 'External|Overview|Stats|Gateway' ./internal/sessions/: ok
- Gateway: true removed by hand: TestTopSessionsMarkWhatOnlyTheGatewaySaw red
  (the Pi record, provider deepseek, came back with cwd "" and title "",
  no gateway field), green with it back.
- sessions-overview.test.cjs: 28/28 in chromium and webkit; with the
  page.js change undone by hand, red in en and zh ("(no prompt)").
- i18n-keys, gui-zh-tw, gui-de, gui-ja (chromium): pass.
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows on
  internal/sessions and internal/gui: ok.
Not run: the full Go suite and the full GUI suite.

Full suite: SUITE_LINE
2026-10-15 23:08:05 +08:00
yetone f15542d2ea sessions: OpenCode 2 subagents show their type, and a Kimi Code subagent opens on its task, not a context chip (#2290, infinitr0us)
OpenCode 2.0.29 keeps a child session's agent in session_v2.agent and
titles it with the task alone, so ocSubagentTitle found no kind and every
OpenCode subagent row showed only its title and time. The kind now comes
from session_v2.agent when set (ocV2DB.agent, kept once found; a missing
column or NULL reads as none and isn't kept), and the "(@agent subagent)"
title split stays the fallback for older versions.

A Kimi Code subagent's own wire.jsonl starts with the task its parent
gave it, a turn.prompt whose origin is {kind: system_trigger, name:
subagent}; the transcript folded every system_trigger as context. In a
subagent's own wire (not agents/main) that prompt now opens as its first
user message (kimiTask). Other system triggers, and a "subagent" one in
the session's main wire, stay folded.

Fixtures follow the reporter's described shapes: ocMakeV2's real
session_v2 schema with agent 'explore' and a task-only title beside a
child with no agent and an older suffixed title; a 1.5-shaped subagent
wire (agentId, promptId, turnId) with the subagent trigger, a reply and a
background_task trigger, plus a subagent trigger appended to main.
No real OpenCode child sessions or Kimi Code subagents on this machine.
No GUI change: the Sessions client already draws a subagent's kind.

Run: TestOpenCodeV2SubagentKind and TestKimiSubagentTask fail on the old
subagents.go/transcript_kimi.go (no kind; user/context first), and
TestKimiSubagentTask fails with the agents/main scope check dropped.
go test -p 1 -tags nogui ./internal/sessions/ ok at the rebased head;
gofmt -l clean; go vet -tags nogui ./internal/sessions/ for darwin,
GOOS=linux and GOOS=windows.
Full suite: SUITE_LINE
2026-10-15 23:08:01 +08:00