Commit Graph
391 Commits
Author SHA1 Message Date
yetone e4e9eb0928 usage: a ZCode call to a provider added by hand at magpie's address is not a local session's (jiangshangmuyun on X)
The Usage page listed one ZCode call as "new-provider · 本地会话" among the
gateway's own rows for the same Trae CN DeepSeek calls. The reporter has one
ZCode window and routes everything through magpie.

Cause: the user added magpie to ZCode by hand as a provider of their own
("new-provider", base URL magpie's gateway), not through magpie's connect,
which writes the id "magpie". ZCode records that id beside each reply, and
readZCodeCalls left out only "magpie"/"dial" (ocGatewayProvider). Its calls
were read from ZCode's database as well as logged by the gateway, and only
hidden again where pairing by session, tokens and end time matched; a call
whose counts didn't agree was listed twice as a "local session".

Fix: zcodeGateway also takes any provider whose base URL, in ZCode's
config.json or provider_config.json, is this machine (loopback, localhost,
0.0.0.0, one of its own addresses) on the gateway's port (MAGPIE_ADDR or the
saved port). Such calls are left out before pairing, as "magpie" ones are.
zcode's call parse version is 4, so cached shards are read again. Like
workbuddyGateway it reads the configuration as it is now. The label itself
is unchanged: a call that did go straight to a vendor is still a local
session's.

Siblings filed, not changed: OpenCode/MiMo (ocGatewayProvider), Pi
(piGateway) and dsh still match the gateway by provider name only (#7193).

Go run on mote at this change on base 9bf5848c1, rebased onto e2e8ea253
(no internal/sessions, usage or GUI file changed between): go test -count=1 ./internal/sessions
./internal/usage ./internal/usageapi (ok); GOOS=darwin/linux/windows go vet of
those packages (clean); gofmt -l clean. Broken by hand: with ocGatewayProvider
back in readZCodeCalls, TestZCodeHandAddedGatewayProvider is red ("a call to a
provider at the gateway's address was read as a local session's").
GUI (no GUI file changed, so as a check of the Usage page that shows these
rows): every usage-*, session-identity and i18n-* file, chromium and webkit,
each language they cover, on mote under load ~40: 1670 of 1777 pass. The 107
reds are in 12 usage files (usage-agents-hide, usage-chart-line,
usage-speed-all-models, usage-upload, usage-ledger and 7 more) and fail the
same at origin/main e2e8ea253 without this change (107 of 308 in those files,
same tests). Filed: #2276, #5834, #6003, #6743, #6790, #6975.
Not tried: the reporter's real ZCode database and config (this computer has
no ZCode); why that one call's tokens didn't pair (no data); the full Go suite.
2026-11-19 17:39:35 +08:00
yetone 3869aee3b0 sessions: agy's calls in T3 Code are on Usage → Requests
zzzkl on X: requests from Antigravity in T3 Code weren't on Usage →
Requests, while a plain agy's were.

T3 Code (pingdotgg/t3code, read at 00c6adbd) runs agy for each
Antigravity instance as an ACP server on the instance's own Google
sign-in: `agy acp --gemini-dir <profile> --app-data-dir antigravity-acp`
(antigravityAuthSupport.ts), the profile being
<T3 Code's folder>/userdata/providers/antigravity/<sha256 of the
instance id>, the folder $T3CODE_HOME or ~/.t3 (dev for its dev
server). Those requests go to Google, never through the gateway, and
magpie's agy reader looked only in ~/.gemini/antigravity-cli, so
nothing counted them. agy writes the same transcript_full.jsonl there
as in its own folder (agy 1.5.10 run that way in a sandbox against a
fake Gemini endpoint; the fixture is its bytes).

agyCallFiles now reads every T3 Code profile's antigravity-acp too, and
Found lists agy for those folders, so the read consent covers them.
T3 Code's folder is appdir.T3Code, shared with agent's t3Base.

Siblings: `agy acp` from any other ACP client with the defaults writes
to antigravity-cli, already read (agy acp --help). T3 Code's magpie
instances (Claude, Codex) go through the gateway and are counted there.

Run: TestAgyCallsInT3Code (default folder, T3CODE_HOME, ~/ form) red
on the old calls_agy.go/access.go with 0 calls, and with Found() =
[claude codex] when only access.go is old; green with the change.
gofmt -l clean; go vet (darwin, GOOS=linux, GOOS=windows) of appdir,
agent and sessions on mote. Full suite (go test -timeout 45m ./..., mica, at 0e3d09361 plus this):
every package ok but agent, dirent, gateway, gui, library and profile;
each red was run again at the base: TestWSLAgentFolderIsALink 2 of 12
red at the base too (filed #7150), the dirent watch tests and
TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes red at the base
(#7031, #7117), TestGatewayModeListsNoOwnSessions (#7064) ok alone,
library and profile hung in testenv.warmAt (#5267) and ok alone.
After the rebase on 14b6b9555 (this commit's tree): appdir ok, agent ok
but TestWSLAgentFolderIsALink (#7150), sessions ok (2335s).
Rebased again onto 9768b384e (its three commits touch none of
sessions, agent or appdir): go build ./... and the TestAgy/T3 tests
of sessions and agent ok at this commit.
No GUI file is reached (no string, API or page change).

Not tried: a real T3 Code signed in to Google (the profile layout is
from T3's source, agy's files from a real agy acp); T3 Code in WSL;
a plain agy with its own GEMINI_HOME/--gemini-dir. The calls count as
agy (Antigravity CLI), not T3 Code, and the Sessions page doesn't list
these conversations (agy --conversation would look in agy's own folder).
T3's throwaway helper sessions delete their files, so their calls go too.
2026-11-19 11:18:11 +08:00
yetone 14b6b95556 sessions: a session resumed into copies isn't read whole again after a start (shangyuan0818 on X)
shangyuan0818 on X, on the latest Windows build: after using an agent,
Sessions took 18 s to load. They had ~100 Claude Code sessions of 30 to
100 MB and read Claude Code only, and guessed it was dedup, since
ccusage is slow on the same files.

Cause: older `claude --resume` wrote each resume as a whole copy of the
session under a new sessionId. ccFamily judges such a group by every
file's message uuids (ccUUIDsOf), and ccRest reads each copy for what
its keeper doesn't hold. Both were kept in memory only. cc-rest.json
kept the rests, but without the uuids they were read from (ids nil).
After a start, the first turn of the session the copies are kept in
changed the group's signature and its size, so every file of the chain
was read whole twice: gigabytes before Sessions showed. Codex is not
read with Claude-only reads (the cold load is the same with its folder
empty).

Fix: the uuids of each file of a group are kept on disk, one file each
in cc-uuids/ (named by a hash of the path), with the size, mtime, the
offset read to and a prefixHash of the bytes up to it. A start reads
them back and goes on from the offset only while the hash still
matches the file's start; otherwise the file is read from its start.
The rest ids are kept in cc-rest-ids.bin under the rest's key, so a
keeper that only grew leaves its copies unread after a start too.
Entries whose session file is gone are pruned once a start. Trash
drops an entry. Reset forgets the in-memory uuids, like a real start.
Not changed: a first start (no cache) still reads each copy three
times (parse, ccUUIDsOf, ccRest), filed as #7143.

Windows (xiaomi-gpu, Windows 11, CGO_ENABLED=0 builds, Claude-only
reads, sandbox HOME). The fixture is 5 resume chains of 20 files, 30 to
107 MB each, 6.9 GB. Time is for the page's three requests together.
                                     origin/main   this change
  cold, no cache                         20.2 s        17.6 s
  warm restart                            0.30 s        0.30 s
  restart after 1 keeper's turn       3.29/3.14 s   0.38/0.25 s
  1 keeper's turn while running           1.60 s        0.11 s
  restart after 5 keepers' turns          7.25 s        0.92 s
  5 keepers' turns while running          3.32 s        0.78 s
The profile of a restart after a turn on origin/main was ccFamily →
ccUUIDsOf (1.23 s) and ccCopyStates → ccRest (1.14 s) in scanThin.
The kept uuids take 2.4 MB for the fixture's 100 files.

Tests (internal/sessions/cc_copies_test.go):
- TestClaudeKeeperTurnAfterAStartReadsNoCopy: a turn, then Reset, reads
  no file from its start, and the turn is counted.
- TestClaudeKeeperTurnTheBranchHeldAfterAStart: a keeper that grows,
  after a start, with a message the branch held on its own counts it
  once.
- TestClaudeKeptUUIDsOfAFileWrittenOver: an entry whose file was
  written over doesn't stand.
- TestClaudeKeptUUIDsRoundTrip.

Run at this tree:
- go test ./... -count=1 -timeout 45m on mote: 102 packages ok, 2
  red, both filed: internal/cli's TestHealthcheckFindsTheRunningGateway
  WithoutMagpieAddr, TestUpdateRestartsTheGatewayItFindsWithoutMagpieAddr
  and TestUpdateFindsAMagpieThatWroteNoRecord (#6471, #6223: they ask
  whatever serves 127.0.0.1:3425 on mote), and internal/gateway's
  TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (#7117, red on main).
- go test ./internal/sessions -race -count=1 -run TestClaude -timeout
  25m on mica: every new test passes; 2 reds, both data races filed and
  outside this change: TestClaudeCdKeptParseReadAgain (#6213, red the
  same at 0e3d09361 on mica) and the claude-desktop-3p subtest of
  TestClaudeTraceSubagentsShareSessionWithoutIDCollisions, failed by
  testenv.Zone's cleanup against provider's sweepStale timer (#4360).
  A first try at -count=3 hit go test's default 10m timeout mid-run
  (3 x ~240s under -race), not a hang.
- go vet ./internal/sessions on darwin, GOOS=linux and GOOS=windows
  (mote): clean. gofmt -l: clean.
- win-run go test ./internal/sessions: 4 reds, TestAgySessions,
  TestAgyRowOnly, TestAntigravityAppFolder and
  TestCCListingKeepsItsNames. The same 4 are red at origin/main
  0e3d09361 on the same box, filed as #6071.
- No GUI test reaches this: the GUI tests fake the API, and no asset
  changed.
Broken by hand:
- kept uuids not read back (ccUUIDKept ignored):
  TestClaudeKeeperTurnAfterAStartReadsNoCopy red, all three files read
  whole on each turn.
- rest ids not read back: that test red, the two copies read whole.
- rest ids read back as empty: TestClaudeKeeperTurnTheBranchHeldAfterAStart
  red, 90 tokens in where 80 are wanted.
Not tried: the reporter's own files, or a real Claude Code --resume
chain (the fixture is generated in that shape). Not tried on a slow
disk or with Defender scanning, which the reporter's 18 s may include.
2026-11-19 09:10:33 +08:00
yetone de58a3879b sessions: a cold read packs idle Claude sessions' calls into one file
shangyuan0818 on X: on Windows, Usage -> Sessions took 18 to 25 s with
long Claude Code sessions. The cause: a cold read wrote a calls-v15 .gob
shard and a .rev for every Claude session, about 21k files for 12k
sessions, and Windows Defender scans each file as it is closed.

Sessions not changed within the hour are now written into one
calls-v15/*.pack per pass (MPCALLS1 magic, the frames, a gob index of
path/offset/count, length, CRC32, magic). It is written to a temp file
and renamed, and flushed at the end of a pass, at checkpoints, in Saved
and every 32 MB. A session's own shard is read before the pack, so a
session that grows gets its own shard and its lines are appended there
as before. A bad pack means the source is read again. The hourly prune
sweeps packs no session points at. Working sessions keep a shard and a
.rev as before.

Measured on xiaomi-gpu (Windows 11, Defender on), fixture of 12,016
Claude session files, no magpie cache, first /api/sessions reply, the
runs alternating old and new:
  origin/main build: 31.67 s, 25.26 s, 20.74 s
  this change:        5.92 s,  5.85 s,  5.65 s
  restart with the pack written: 1.97 s and 2.16 s; then 0.25 to 0.31 s.
  The cache held 1 .pack and 4 .gob.

Tests (call_pack_test.go): TestColdSessionsReadWritesOnePack,
TestPackedCallsServeRequests, TestPackedSessionGrows. With the pack
branch turned off by hand the first fails (.gob:63 .rev:62) and the
second finds 0 packs.

Run at 4ace48feb (this change on origin/main 2ab2f6913):
- gofmt -l: clean.
- go test ./... -timeout 45m -count=1 on mote: 101 packages ok
  (internal/sessions 154 s), 3 red, none in code this touches, each
  filed: internal/cli TestHealthcheckFindsTheRunningGatewayWithoutMagpieAddr,
  TestUpdateRestartsTheGatewayItFindsWithoutMagpieAddr and
  TestUpdateFindsAMagpieThatWroteNoRecord (#6223: another session's ssh
  forward listened on mote's 127.0.0.1:3425); internal/gateway
  TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (#7117) and
  TestLaneLimitRoutes (#5150); internal/gui
  TestAppReplacesItsOlderGatewayOnceIdle (#6297) and
  TestSettingsSaveKeepsWhatItDoesNotSend (#7127, red since f6a538ece).
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go
  build: clean.
- internal/gui/tests/sessions-*.test.cjs (46 files): 322 of 322 in
  chromium, 322 of 322 in webkit.
- wsl-run go test ./internal/sessions: ok (25.3 s), at the base before
  the rebase.
- win-run go test ./internal/sessions: 4 reds, the same on origin/main
  07d19510f and filed as #6071 (TestAgySessions, TestAgyRowOnly,
  TestAntigravityAppFolder, TestCCListingKeepsItsNames). go vet clean.

Rebased onto fcbc1a2d0 (three gateway commits, none in
internal/sessions or its doc). At the pushed head: go test
./internal/sessions ok (209 s); go vet of it on darwin, linux (nogui)
and windows clean; go build clean.

Not tried: a real user's profile; the timings use a generated fixture
the size of the report.
2026-11-19 01:22:40 +08:00
yetone 5cf1d3846a sessions: an agent left off in the first "allow selected" is asked about once more, on Sessions and Usage › Requests
baysonfox on X: with magpie installed after Antigravity 2.0, the app's
sessions and calls made without magpie never showed in Usage, while agy
CLI's did. The first consent named the app off beside agy, and a named
agent was never "new" again, so nothing asked about it and nothing on
Usage said why. The reader is fine: the app's calls come from its own
SQLite steps (antigravityRead), read once allowed.

Nothing is turned on by magpie: the gate is the user's privacy choice.
Instead:
- settings.SessionReads gets Kept: agents turned off on their own (a
  sessions/reads post without `all`: Keep off, a Settings › Privacy row,
  `magpie sessions read off <agent>`). A post setting it on takes it out.
- readsNow's New: off, found here and not Kept (was: never named). So an
  agent left off in the first choice's list is asked about once more,
  as one found later already was.
- Usage › Requests shows a line above its rows for those agents
  (readsLater in the usage plugin): Count {names} / Don't count, the
  same {agents} posts as the Sessions page's laterCard. Gone after
  either answer; sessions/reads read at most once a minute.
- Old data: an agent turned off in Settings before Kept existed has no
  entry and is asked once more, for every user with such an agent.

Tests:
- TestSessionReadsUncheckedAgentAskedAgain (count, keep off): sandbox
  HOME with testdata/agy-sessions and the real Antigravity 2.30
  conversation (antigravity-2.30-tools); after the first choice the app
  is off and New, has no rows in /api/usage/requests; Count brings its
  rows in, Keep off keeps none, and neither is asked again. Red on the
  old code (New false after the first choice).
- TestSessionReadsTurnedOffNotAskedAgain: off on its own, under all true
  and all false, is neither on nor New.
- usage-reads-note.test.cjs: the Requests line in Chromium and WebKit,
  en/zh/zh-TW/ja/de at 900/420/390px, both answers, buttons inside the
  line, no sideways scroll; red on the old code (no #ledReads).

Run on mica (mote was full: load 40+, another GUI suite on it), rebased
on 389169f76:
- gofmt -l clean
- go vet on gui, sessions, settings, cli and tui; GOOS=linux -tags nogui
  and GOOS=windows vet on gui, sessions, settings and cli; go build ./...
- go test -count=1 -timeout 45m on internal/gui, sessions, settings, cli
  and tui: all ok except gui's TestGatewayModeListsNoOwnSessions, red
  the same on an untouched 389169f76 copy (#7064)
- GUI, both engines: usage-reads-note, sessions-reads, i18n-keys,
  i18n-en-no-cjk, usage-ledger, usage-request-page, usage-no-reading,
  usage-ledger-fit, ledger-hscroll, usage-phone-head, sessions-usage-off.
  Only usage-ledger's "newest live route needs no return-to-live button"
  was red (en, zh, both engines), red the same on the untouched
  389169f76 copy (#3104). i18n-keys first caught "Leave off" as otel's
  word; renamed to "Don't count".
- After rebasing on dc507aefd: gofmt, vet, the TestSessionReads tests
  and usage-reads-note, i18n-keys, i18n-en-no-cjk and sessions-reads
  again: all ok, 98 of 98 GUI tests.

Broken by hand: recording Kept on every off post (all sent too) turns
TestSessionReadsNewAgent, ...UncheckedAgentAskedAgain and
...TurnedOffNotAskedAgain red.

Not tried: the whole GUI suite (both machines had another GUI suite
running), the full go test ./..., and a real Antigravity 2.0 install
in the GUI; the live Antigravity data was not touched.
2026-11-18 20:59:55 +08:00
yetone d2fa7d8d79 sessions: an Antigravity app conversation shows what was said, not only its title
@yansheng1003 on X: the Sessions page showed an Antigravity 2.0
conversation's title and preview only. HasTranscript left "antigravity"
out, since conversations/<id>.db's step text is encrypted at rest, so
the row had no Show conversation and /api/sessions/transcript said
"this agent's conversations can't be shown".

The app also writes every step in plain text beside the database:
brain/<id>/.system_generated/logs/transcript_full.jsonl in the same
store, in agy CLI's format (user input, planner responses with their
tool_calls, tool results). Antigravity 2.30's language server writes it
in the stable store and in Insiders' (both checked: run in a sandbox
HOME on Windows against a fake model that called read_file).

- transcript.go: antigravity has a transcript; readTranscriptOf reads
  it through agyTranscript (antigravityTranscriptOf), so the viewer,
  TranscriptAt, search, the said index and the Markdown export all get
  it. A conversation with no transcript file is ErrNoTranscript, as
  before.
- antigravity_app.go: antigravityTranscript derives the path from the
  database's (stable, Insiders, a WSL distro's); its size and time are
  folded into the session file's with the -wal's, so a step it adds
  reads the session and the said index again.
- search.go: linesFile is false for antigravity, so the encrypted .db is
  never pre-scanned for the words.
- testdata/antigravity-2.30-tools: that real conversation (db with the
  WAL checkpointed, summary row, brain/ logs).

Tests: TestAntigravityAppTranscript (stable, Insiders, WSL: parts, search
hit and miss, Markdown), TestAntigravityAppNoTranscript,
internal/gui TestSessionAntigravityConversation (/api/sessions marks it,
/api/sessions/transcript gives the five parts).

Run: on mica (mica-run) at base de5fc6700:
- gofmt -l internal/sessions internal/gui: clean.
- go vet ./internal/sessions ./internal/gui, GOOS=linux go vet -tags
  nogui and GOOS=windows go vet on the same, go build .: ok.
- go test -count=1 -timeout 45m ./internal/sessions: ok but for
  TestWSLAgentsGoneListingDrops (load ~48; fixed at its cause in the
  commit before this one); go test ./internal/gui: ok (299s).
- After that fix: go test -run 'WSL|Antigravity|Agy|Gone'
  ./internal/sessions ok; GUI files sessions-talk, -talk-sheet,
  -talk-model, -export, -said, -subagents, -reads, -search, -convert:
  168 of 168 in Chromium and WebKit.
- Old code (de5fc6700 with only the new tests and testdata):
  TestAntigravityAppTranscript red in stable, insiders and wsl ("the
  session isn't marked readable"), TestSessionAntigravityConversation
  red ("listed with no conversation to show ... Transcript:false").
- Windows (win-run on xiaomi-gpu): TestAntigravityAppTranscript (3
  subtests) and TestAntigravityAppNoTranscript pass.
  TestAntigravityAppFolder is red there at the base as well (#5957).
Rebased onto bfddc9cfb, on mote (mote-run) at this tree: gofmt clean,
the three vets and go build ok, go test -count=1 ./internal/sessions
./internal/gui ok (56s, 157s).
Not tried: the real GUI window opening this conversation; the API and
page are covered by the tests above.
2026-11-18 18:55:46 +08:00
yetone 65c9a2e411 sessions: the WSL tests wait for the distro's first listing, however busy the machine
TestWSLAgentsGoneListingDrops went red in a run of internal/sessions on
mica at load ~48: "answered=true: want 7 sessions, got 0". The first
List waits at most wslFirstWait (3s) for the WSL walk, as the Sessions
page should, and on a busy machine the walk outlasts it, so the count
read nothing yet. Every test built on wslDistro counts that first
listing (TestWSLSessionsListed, the Antigravity and Kimi WSL tests), so
wslDistro now gives it a minute; TestWSLFirstWaitIsWaitedOnce still sets
its own 500ms after.

Broken by hand: a 3.5s stall in WSLHomes gave the same red, "got 0",
without this change and passed with it (mica-run, -run
TestWSLAgentsGoneListingDrops). Alone, unstalled, the test passed 5 of
5 on the old and new code.

Run: on mica (mica-run): go test -count=1 -run 'WSL|Antigravity|Agy|Gone'
./internal/sessions ok; gofmt clean. The full internal/sessions run
where it went red is in the next commit's record.
2026-11-18 18:55:46 +08:00
yetone 2416beed69 sessions: a tab's count is the rows it lists, and a Pi subagent's calls are no row delete can't find (lurx98 on X)
lurx98 on X (tweet 2122972281534402597): on the Sessions page the tabs
said Codex 6 and Pi 8. Codex, opened, said 0 and "no sessions yet"; Pi
said 6 from any other tab. Deleting a row titled "Task: 只读事实核对…"
toasted "no such session".

Two causes, both about one count path and the list disagreeing:

- Codex: agentCounts counted every rollout, while the list drops a
  subagent thread whose parent thread is gone (keptSubagents, 82f09e324:
  Codex App leaves them behind when a thread is deleted). Both now ask
  orphanSubagents; agentCounts reads the identities from the parses kept
  (codexIdentitySnapshot), so a rollout never parsed yet still counts
  until something reads it (Usage, the Codex tab).
- Pi: a pi-subagents scout runs as a Pi of its own and names its own
  session id to the gateway. The lead's row covers it (NativeIDs, its
  subIDs), and a tab not shown skips it, but the shown tab deduplicated
  gateway sessions only by its rows' own ids, so the scout's calls were
  a row of their own, titled by its "Task: …" prompt. Its count (rows)
  went up by those. Delete sent that id to the lead's files (the delete
  handler's NativeIDs path), where no session has it: "no such session".
  The shown tab now skips the same native ids as the counts and delete.

Test: TestSessionTabCountsAreTheirRows (internal/gui), built on the real
pi-subagents fixture (Pi 1.4.0, pi-subagents 0.88.1) with the scout's
calls through the gateway, and Codex App rollouts whose parent thread is
gone. It checks each tab lists the rows it counts, from every tab, and
that each listed Pi row deletes.

Run:
- Old code red: with both files reverted, 5 failures (scout listed as a
  row, codex 4 vs 2, pi 3 vs 2, delete "no such session"). Reverting
  only internal/sessions/manage.go: codex 4 vs 2. Reverting only
  internal/gui/sessions_manage.go: the Pi failures and "no such session".
- At 41b4edf87 (on origin/main 03314b25a), through mote-run: gofmt -l
  clean, go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows
  go vet ./..., go build, then go test ./... -count=1 -timeout 45m: 103
  packages ok, no FAIL (gui 203s, sessions 163s, gateway 1045s).
- Rebased onto 54117164c (gateway files only, none of these): go test
  ./internal/gui ./internal/sessions -count=1 ok again at the pushed head.
- No GUI script changed (client.js untouched), so no GUI suite run.

Not tried: the reporter's own files. The Codex fix needs the rollouts
parsed once (as above); and agents whose rows can be hidden
(GatewayHidden, uninstalled agents' Forget) still count hidden rows on
another tab, which the reporter's agents don't have.
2026-11-18 17:30:43 +08:00
yetone 3ec89c5224 codex: the takeover's end waits for the chats on magpie the Codex app has open (milianxinqi on X)
milianxinqi on X, the Codex app: "Model provider mismatch. This chat uses
magpie, but your current provider is OpenAI. Switch to magpie to
continue." ("用的好好的,codex 突然就弹这个了"), with nothing disconnected.

Cause. With the ChatGPT account Codex is signed in to held (out of its
allowance and credits), magpie is Codex's provider (the codex.out
takeover, #540) and new chats start on magpie. When the account has room
again (its window's reset, a switch to another account, or the account
the user keeps Codex on, a5e3972a7), Sync ended the takeover at once:
model_provider out of config.toml, Codex back on OpenAI. The Codex app
keeps the app-server the takeover started (codexAppStep leaves it
running unless Restart the Codex app to follow is on, off by default,
#4550), with its chats loaded and each one's writer lock held, so
bringBack could move none of them and codexRetagOpenThreads never ran
(it runs only before magpie ends the app-server). Every send in an open
chat then met the mismatch, with no step of the user's.

Fix. outStays (agent/codex.go): the takeover's end in Sync, both the
out_own way back and #540's, waits while a Codex holds a chat on magpie
open or wrote to one in the last minute (codexHeldOnMagpie:
sessions.CodexThreadsBusyOnBut, T3 Code's own threads left out, as
codexRetagOpenThreads leaves them), and codexThreadsLater asks for the
Sync that ends it once they are let go; bringBack then moves them onto
OpenAI. Meanwhile magpie serves them on the account, which has room, and
the app on the takeover's app-server shows no account either way. Nothing
waits when the app-server is restarted for the change (Restart the Codex
app to follow on, provider.CodexRestartsApp) or the user turned the
takeover off (Always ChatGPT): that restart moves the open chats first.
The [model_providers.magpie] table already stays after a Disconnect, so
an old thread still opens; a deliberate Disconnect restarts the
app-server (byHand) and retags its chats.

Other paths looked at and left: Disconnect, Unwire, Join and Codex's
account switch go through the same bringBack/retag; RestoreOnQuit (off by
default) runs at quit only; the update restart hands the gateway over on
macOS and Linux and skips it. On Windows a restart runs RestoreOnQuit
when it is on: filed separately.

Tests:
- TestCodexTakeoverWaitsForTheOpenChat (new): takeover, a chat on magpie
  quiet but its lock held, account back: still magpie's provider, the
  chat on magpie, no Sync asked; lock let go: a Sync asked, which ends
  the takeover and moves the chat to openai.
- TestCodexTakeoverEndsAtOnceWhenTheAppFollows (new): with the app
  restarted for the change, nothing waits.
- TestCodexTakeoverThreadComesBackOnceQuiet (nb5p): now the takeover
  stays while the thread is written to, and ends at the later Sync.
Broken by hand: outStays' gate taken out of Sync: the new test and nb5p's
red ("Codex was put on OpenAI under it"), green with it.

Run (mica, mote over its load, at this tree on origin/main 48fffb60c):
- go test -count=1 -timeout 45m ./internal/agent ./internal/sessions
  ./internal/provider: ok (426s, 1917s, 237s).
- go vet of those on darwin, GOOS=windows, GOOS=linux: ok. gofmt -l clean.
- Rebased onto origin/main a2d402afe (provider and sessions changes
  elsewhere): go build ./..., go vet of the three, and the takeover,
  thread-move and retag tests of internal/agent and internal/sessions
  again: ok.

Not tried: the real Codex app through a real reset (needs an account
held then given room); a full ./... run (mica had another session's full
suite and GUI suite running).
2026-11-18 16:33:04 +08:00
yetone 42c43c0020 sessions: an agent found after Allow selected is asked about once (Antigravity 2.0)
baysonfox on X: Antigravity 2.0 desktop sessions showed on the Sessions
page only while the app was connected to magpie; agy CLI's always showed.

Cause: not the file reader. Real Antigravity 2.30 (signed out, no model,
sandbox HOME on the Windows box) writes ~/.gemini/antigravity/
conversations/<id>.db, conversation_summaries.db and brain/, and
internal/sessions parses them. The gate is settings.SessionReads:
"Allow selected" (and the Usage readsNote's "Count …") saves all:false,
so an agent installed after that choice is never read and never asked
about again. Gateway-recorded sessions skip the gate, hence "only when
connected".

Fix: /api/sessions/reads marks a found agent `new` when the choice was
made, it isn't read, isn't named in Agents and is on disk (Found(), which
checks every OS's path). The Sessions page shows one quiet card for those
(laterCard): "Show their sessions" names each on, "Keep off" names each
off, so it isn't asked again. No new endpoint; the card posts the
existing sessions/reads.

Tests: TestSessionReadsNewAgent copies the real 2.30 files
(internal/sessions/testdata/antigravity-2.30, sandbox paths only, no
tokens) beside agy-sessions, with agy allowed by name: antigravity is
off and new, nothing listed; after the answer it is not new, settings
keep all:false/agy:true, and its one session is listed only when shown.
TestSessionReadsNewOnlyWhenNamed: not asked, allow all, all with agy off
mark nothing new. sessions-reads.test.cjs: the card, both answers, posts
and no card after reload, Chromium and WebKit, 5 languages, 900/390px.

Run at d7d62d889, on mote, then rebased onto 48fffb60c (app.js and
settings-groups only, no file in common):
- gofmt -l, node --check client.js/i18n.js: clean
- go vet ./internal/gui ./internal/sessions; GOOS=linux -tags nogui and
  GOOS=windows go vet of the same: ok; go build .: ok
- go test -count=1 ./internal/sessions: ok (282s)
- go test -run 'TestSessionReads|TestCoreScript|TestI18n|TestCSS'
  ./internal/gui: ok
- GUI: sessions*.test.cjs (45 files), usage-reads-note,
  gateway-mode-sessions, i18n-keys, window-back-once: 711/711 pass
Broken by hand: New forced false, TestSessionReadsNewAgent red in both
subtests ("want off and new"). An earlier "Allow" button label was red
in i18n-keys (core word, internal/agent/reach.go), hence the label.
Not run: the whole GUI suite and the full go test ./... (mote and mica
were overloaded, mica's disk full). Not tried: a real Antigravity 2.0
on macOS/Linux; Found() paths for those come from the existing reader.
Not changed: the Usage page's readsNote still shows only before the
choice; Found() doesn't look into WSL distros.
2026-11-18 16:04:10 +08:00
yetone 7707ba9adb sessions: a compaction that doesn't fit its line goes as text, never as magpie's seal (hey_boyce on X)
hey_boyce on X: Codex, talking to OpenAI itself, got 400
invalid_encrypted_content "The encrypted content for item
cmp_magpie_1794916786407450000 could not be verified".

Cause: PortCodexRollouts writes magpie's compaction item (magpie1:
base64 summary) as Codex's own summary message, keeping each line's
length, since a paginated rollout keeps places by byte. A message
longer than the line (a short summary under Codex's ~400-char prefix)
was left as it was, so the magpie1: seal stayed in the rollout, Codex
replayed it to OpenAI every turn, and the thread was stuck. The
incremental pass never looked at such a rollout again.

Change:
- fitShorter: when the full message doesn't fit, the summary goes
  under a short heading, then cut to fit (rune-safe, "…"), then
  with no heading. If nothing fits, a standalone item is retired as
  {"type":"magpie_compaction"}, which Codex reads as unknown and
  never sends.
- In replacement_history an unknown item IS sent (as "other"), and
  OpenAI refuses it ("Invalid value: 'other'"; seen with real
  codex-cli 0.165.0 and 0.169.1). So a compaction or reasoning item
  retired there is left out with its metadata entry, and
  magpie_reasoning items main's PortCodexRolloutsLeft already wrote
  there are taken out (retiredInList). That was a sibling bug: those
  threads failed the same way.
- codex-portable.json gains refit: a state from before makes one
  whole pass again, so rollouts already left with the seal are fixed.
- The gateway's last line: a 400 naming an item of magpie's own
  compaction asks again with its summary message in its place
  (withoutItem), not with the summary dropped.
- codexsummary.Summary decodes the seal; Message uses it.
- docs/subsystems/gateway-routing.md says all of this.

Run (on mica, at this head rebased on a265632da):
- red on the old code, green now: TestPortCodexRolloutsLongerLine
  (short, cut), TestPortCodexRolloutsDropsRetiredFromHistory,
  TestPortCodexRolloutsRefitsOnce,
  TestPortCodexRolloutsLeftRetiresUnsealedReasoning,
  TestRefusedMagpieCompactionGoesAsText (old withoutItem: 2 items,
  the summary gone).
- broken by hand: without `&& was.Refit` RefitsOnce is red.
- real Codex, sandbox HOME with a copy of the owner's ChatGPT auth,
  codex-cli 0.169.1, gpt-6-sol, against OpenAI:
  - the reporter's item (id cmp_magpie_1794916786407450000, summary
    "ok") gave the same 400 word for word. Ported by this code, resume
    answered.
  - an id-less item plus a magpie_reasoning in replacement_history
    (as main left it) failed "Invalid value: 'other'" before. Ported,
    resume answered.
- go test -count=1 -timeout 45m ./internal/codexsummary
  ./internal/sessions ./internal/gateway ./internal/agent: all ok
  (gateway 1026s, agent 221s), log kept in enc-scratch/pkgs.log;
  TestLoopGuard* again after the doc edit: ok.
- rebased on 53db3e389 (stream keepalive; only the doc page is
  shared): the refusal, seal, compaction, LoopGuard and Quiet tests
  in internal/gateway again at this head: ok.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build ./... ok.

Not tried: a summary cut to fit with real Codex (the unit test checks
it is a plain user message, the same shape as the case that was run);
a Codex in WSL; the full ./... suite: mote was over its cores and both mote and
mica were running another session's GUI suite, so only the changed
packages and internal/agent, which ports rollouts, ran (above).
2026-11-18 11:16:54 +08:00
yetone 8e1534f5f9 sessions: read LiveAgent's sessions (#6741)
Usage › Sessions and the Sessions page now list LiveAgent's sessions
with their title, time, model, tokens and cost, and show their
conversation.

- Where: K-brain keeps each session at
  <root>/sessions/<project>/<id>/session.jsonl (older ones right under
  sessions/). sessions/.runs and sessions/.deleted-history are skipped.
- Root: $LIVEAGENT_HOME, then $K_BRAIN_HOME, then
  ~/.liveagent/data-dir.json, then ~/.liveagent. The rule now lives in
  sessions.LiveAgentDirIn, and agent.liveAgentDir calls it, so it has
  one owner.
- Reading: K-brain rewrites the file whole, so it is parsed whole. The
  first line is session_meta (id, title, cwd, running totals).
- Tokens:
  - Each reply's own usage counts on the day it came back.
  - What the totals (model_usage, else usage_in/usage_cached/usage_out)
    hold beyond those replies, such as a compaction's call or a rewound
    reply, counts on the last message's day, together with sub_usage.
  - Cache reads and writes are taken out of prompt_tokens.
- Forks: a fork's copies of its source's messages (seq <= fork_seq) are
  the source's, and count in neither the fork's messages nor its totals.
- Subagents: a subagent's own session (task-<parent>-<task>, task_id
  set) is filed under its parent with its activity, but no tokens,
  because its spend is the parent's sub_usage already.
- Not added:
  - a Calls reader: the gateway's own record of LiveAgent's calls
    carries no session id, so it would count them twice;
  - resume and delete: LiveAgent has no resume command.
- Skills: SkillsManager read (skill://<name>/SKILL.md) and Read of a
  skill path are counted.

Run (mote, mote-run, at d67ccbd3c plus this change before the rebase):
- go test -count=1 -timeout 45m ./internal/sessions ./internal/agent
  ./internal/library ./internal/agentenv ./internal/gui: all ok.
- go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: clean. gofmt -l: clean.
- TestEveryAgentSaysItsSkills has liveagent →
  TestLiveAgentSessions.

Again after the rebase on 3be322fe4 (mote): ./internal/sessions,
./internal/agent, ./internal/library ok; GOOS=linux -tags nogui and
GOOS=windows go vet ./... clean.

Broken by hand (mote), each red:
- Without parserFor's liveagent case: TestLiveAgentSessions (0 listed)
  and TestLiveAgentTranscript.
- Without subtracting a fork's copies: fork1 tokens 600/140/1000 for
  want 400/40.
- Without subtracting the replies already counted: abc123
  3500/550/2000 for want 2500/350/1000.

Fixtures: the issue's literal session_meta, with its placeholders
filled in (12786068 in, 12455808 cached, 103572 out →
330260/103572/12455808). The message, snapshot and compaction lines
follow K-brain's record types as its source writes them.

Not tried: no real LiveAgent install. The files were not written by
LiveAgent itself, and no real session was read. Imported sessions
(ImportHistory) are listed as they are. No GUI file changed, so no
GUI tests were run.
2026-11-17 20:56:30 +08:00
yetone a75a1fffcb provider: agy's Orchestrator (Argon), gemini-pro-orchestrator-g1-pro, is priced as Gemini 4 Argon (mu33410 on X)
mu33410 on X: agy's Orchestrator model showed no cost. 9bcdcfb7d priced
the Antigravity app's Orchestrator ids (gemini-pro-orchestrator-argon,
-carbon, gemini-flash-worker-agy) as the Gemini model each is, but the
agy CLI names Orchestrator (Argon) gemini-pro-orchestrator-g1-pro: the
id `agy models` lists for a Google AI Pro account (agy 1.5.9), kept
verbatim in the agy-cli plugin's test/usage.mjs and test/catalog.mjs.
Its calls, and its rows in Usage and Sessions, had tokens and no price.
It is now in antigravityRoles at gemini-4-argon, the model Antigravity's
docs say Orchestrator (Argon) plans with; at an effort and under an
agy-cli/ route too. Orchestrator (Carbon) is gemini-pro-orchestrator in
agy, already priced as Carbon.

Tests: TestAntigravityOrchestratorIDsPricedAsTheirModel (MakerPrice,
ListPrice, PricedName), TestAntigravityOrchestratorCallsPriced (an agy
call in the ledger, its total and agy's own view) and
TestPriceOfAntigravityOrchestratorRoles take the agy id; g1 and
g1-pro-ultra stay unpriced. Broken by hand: with the old models.go all
three are red on the g1-pro cases, green with the fix (mote).

Run (mica, at this tree on origin/main 074614077): gofmt -l clean;
go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
./... ok; go test -count=1 -timeout 45m ./... : 103 packages ok, no FAIL.
Rebased on origin/main 7c3e68908 (15 files, none of them pricing): internal/provider,
internal/usage and internal/sessions run again there (mica): ok.
No GUI files changed.

Not tried: a real agy Orchestrator conversation on disk. This Mac's agy
1.5.10 conversations used no Orchestrator, so the id agy writes into a
step's gen_metadata is taken from `agy models`, not seen in a database.
The worker agy records for Orchestrator's Hydrogen handoff is unknown;
gemini-flash-worker-agy (the app's) is the only worker id priced.
2026-11-17 18:59:48 +08:00
yetone 64ad53f6c7 sessions: magpie sessions search and show, for agents (yansheng1003 on X)
yansheng1003 asked for a command or skill an agent can call to search
and read its sessions. magpie had the search on the Sessions page and
in the Magpie Sessions MCP server, but not on the command line.

- `magpie sessions search <words…> [--agent] [--days N|today|all]
  [--limit N] [--wait] [--json]`: the Sessions page's search
  (sessions.SearchSaid over said-v1.db; SearchSaidSince adds the --days
  bound), newest first, each hit named agent:id with title, folder,
  time and the words round the match. A one-shot command waits for the
  index (SaidReady, 60s by default, a progress line on a TTY only).
- `magpie sessions show <agent:id|id> [--find] [--from N] [--max-chars N]
  [--json]`: the viewer's reader (TranscriptOf, TranscriptAt) as text,
  from where the words were said; --json is the page's transcript.
- One renderer: the MCP server's search_sessions/read_session text moved
  to sessions.SaidText/SessionText (said_text.go), with how to ask for
  more given by each caller (TextHow). The MCP server's output is
  unchanged (its tests pass as before).
- Consent: neither reads, nor makes the index, until the user has
  answered which agents magpie may read; it prints notAskedLine and
  exits 1. An agent not allowed is ErrNotRead for --agent and show.
- Flags: an unknown flag or a missing value is refused with the usage,
  never taken for words or a session id; `--` ends flags; -h/--help
  prints the subcommand's own usage (help_cli.go).
- Parity: /api/sessions/said and /api/sessions/transcript now map to
  these commands (settings_parity_test.go).
- Library: magpie-sessions is a featured official skill
  (magpie-community/plugins skills/magpie-sessions, pushed as plugins
  cf5b0312), listed after magpie-quota.
- Docs: usage.html "Search what was said" in en, zh and ja; llms-full,
  search indexes and docs-index.sums regenerated (node docs-index.mjs).

Run at 114eb4592 (rebased on a2213b1b6), on mote:
- gofmt -l internal: clean. go vet darwin, GOOS=linux -tags nogui and
  GOOS=windows of internal/cli, sessions, gateway, library: ok (before
  the rebase; upstream's one commit touches none of these).
- go test -count=1: internal/cli -run 'TestSessions|TestEveryRoute|TestHelp'
  ok; internal/library -run TestFeaturedSkills ok; internal/gui -run
  TestEveryRouteIsNamedForTheCLI ok; internal/sessions (whole package)
  ok; internal/gateway -run 'SessionsMCP|Sessions' ok.
- site: node --test search.test.mjs worker.test.mjs, 47 pass.
- Real binary, sandbox HOME holding internal/sessions/testdata's Claude
  and Codex sessions: search before `sessions read on all` printed the
  not-asked line, exit 1; --help printed usage, exit 0; --bogus refused,
  exit 1; then search "login bug" found the Claude session, --json gave
  the Codex hit, show --find and a bare Codex id read their sessions.

Broken by hand: without the consent check TestSessionsSearchNotAsked is
red; without the since filter the --days today case is red.

Not run before the push: the full suite. Both mote (load 31 on 18
cores) and mica (21 to 30 on 12, another session's gateway run) were
over their limits; it runs at this head after the push. Not tried: real
agents' long histories (the index on a large history is the GUI's, as
before), Windows and Linux runs of the command.
2026-11-17 17:33:23 +08:00
yetone 1549ccf743 sessions: agy's and Antigravity's own calls carry their first-token time and duration (guyng35955 on X)
Usage → Requests showed agy's own calls with no time to the first
token, no duration and so no speed. Those calls don't go through the
gateway, which is where other calls are timed, and the readers of agy's
and the Antigravity app's conversations never read the step's times.

Each step's metadata row (exa.cortex_pb.CortexStepMetadata) has them:
1 created_at, 6 viewable_at, 7 finished_generating_at. A model step is
created as its request goes out, so 6 less 1 is the time to the first
token and 7 less 1 the call's duration (stepTimesOf). A response that
two steps share is timed from the first step's start to the last's end.
A step with no end, or times out of order, has none (unknown, not 0).
agy and antigravity call-cache versions go to 2 so cached shards are
read again.

Checked with real agy 1.5.9 in a sandbox HOME against a fake Gemini
endpoint that held its first chunk 2.01s and ended at 4.03s: the row
said 2014ms and 4032ms. That row and transcript are the new fixture
(testdata/agy-times).

Run:
- TestAgyCallsCarryTheirTimes, TestAntigravityAppCallTimes,
  TestAntigravityAppOneResponseTimedWhole, TestStepTimesUnknown: red
  on the old readers (all 0ms), green on these (mote).
- go vet ./internal/sessions ./internal/usage, GOOS=linux and
  GOOS=windows go vet ./internal/sessions, gofmt -l: clean (mote).
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage:
  ok (mote, at 31dcfcc33).

Not run here: the full suite (running after the push) and the GUI suite
(no GUI change). Not tried: a real agy call to Google (the local
account is refused), so the times rest on the fake endpoint's run.
Seven other agents' own calls have the same gap: #6940.
2026-11-17 15:39:43 +08:00
yetone 593517bf00 codex: T3 Code's threads on magpie stay on magpie (xxxxpouqqs on X)
xxxxpouqqs on X: "t3code 每次重新会话都出现类似于 The 'codex-2/gpt-6.1-sol'
model is not supported when using Codex with a ChatGPT account".

Cause: T3 Code's magpie · Codex instance runs Codex in ~/.codex on
magpie with `-c model_provider="magpie"` alone, so config.toml names no
magpie. At the next Sync, bringBack took every thread on magpie for a
leftover and moved it to the provider config.toml names (openai), in
state_5.sqlite and in the rollout. Codex resumes a thread on the
provider it was started on, so reopening a T3 thread sent magpie's
model id to ChatGPT. codexRetagOpenThreads (the Codex app's app-server
restart) moved locked or loaded ones the same way.

Fix:
- t3CodexRunsIn(home, dir): T3's magpie-codex instance runs Codex in
  this home (no homePath, or one naming it; $T3CODE_HOME honoured; an
  unreadable settings file counts as yes).
- bringBack then moves only threads another client started; a thread
  whose originator is T3's stays on magpie (sessions.CodexThreadsBy
  reads originator and model; a failed read moves nothing).
- codexRetagOpenThreads keeps T3's threads the same way
  (RetagLoadedCodexThreadsBut).

Old threads: a T3-started thread an earlier magpie moved to the
current provider with a magpie model id (one with "/") is moved back to
magpie at the next Sync, for every user; a T3 thread started on OpenAI
with OpenAI's own model stays. Nothing to do but update.

Run (worktree at acc358f07 + this change, on mica; mote was over its
cores):
- go test ./internal/agent/ -run 'TestT3|TestCodexThreads|TestCodexTakeover': ok
- broken by hand (`if false && t3CodexRunsIn(...)` in bringBack):
  TestT3CodexThreadsStayOnMagpie red, T3 threads b1 and b3 on "openai"
  and the rollout moved; restored
- go vet darwin, GOOS=linux, GOOS=windows on agent and sessions: ok
- gofmt -l: clean
- go test ./... -timeout 45m: ok, every package (exit 0, 103 packages ok)
- Real use on mote, sandbox HOME, real T3 Code (t3 serve) + real Codex
  0.169 with a fake upstream: the old magpie moved 5 T3 threads to
  openai and the UI resume hit the ChatGPT endpoint with
  codex-2/gpt-6.1-sol ("not supported when using Codex with a ChatGPT
  account"). With this build the next Sync logged "5 thread(s) T3 Code
  started on magpie moved from openai to magpie", and the same thread's
  resume in T3's UI went to the gateway (gpt-6.1-sol, magpie's key).

Not tried: T3's desktop app (only t3 serve), Windows, a real vendor
upstream, an older Codex whose threads table has no originator column
(CodexThreadsBy fails and nothing moves).
2026-11-17 10:27:26 +08:00
yetone ac4a4cf849 sessions: opening Sessions waits on no WSL listing it already has (shangyuan0818 on X)
shangyuan0818 (X, third round, after v0.1.4091 and v0.1.4255): on Windows,
Usage -> Sessions opened only after a fixed ~20s when sessions were long.
The long sessions were not the cause. Goroutine dumps of the reporter's
case on the Windows box showed four waits on WSL on the page's first asks:

- agent.Looks -> Clients -> All -> wslDistros: a blocking wslRefresh,
  `wsl -l -q` (10s timeout) once its list is a minute old, then
  `wsl -l --running -q` (10s) every time. A WSL that answers slowly but
  answers is never marked hung, so each open after a minute idle waited
  for both: about 18s, every time. ClientsIn drops WSL's agents anyway,
  so Clients now reads only this machine's (local()).
- gui agentsHere (the web-mode own-sessions gate) called agent.All the
  same way. It now calls agent.AllKnown: this machine's agents and WSL's
  as last listed (wslDistrosWithin(0)), never waiting on wsl.exe.
- sessions.wslFilesAs waited wslFirstWait (3s) afresh on each read while
  the first listing was pending, so list, stats and overview each waited
  3s in turn. The 3s is now counted once, from when the first listing
  started.
- provider.copilotCLILogin waited copilotWSLWait (2s) on every re-read
  of a distro's Copilot sign-in, every copilotWSLAge (20s), though it
  had an answer. A re-read now answers the last read at once; only the
  first read waits.

Timed on Windows 11 (xiaomi-gpu), sandbox HOME with a 90 MB Claude JSONL
and a 32 MB Codex rollout, a fake wsl.exe whose -l -q answers "Ubuntu"
after 8s and whose --running hangs; /api/sessions list+stats+overview
together, opened 20s after start, then 70s apart:

  b0674b9ec (old):  0.39s, 18.11s, 18.12s
  this commit:      0.38s,  0.07s,  0.07s

With wsl.exe hanging outright and Sessions opened right after start:
old 10.3-10.5s, new 3s (the designed first wait, now waited once). With
no WSL: 0.4s on both.

Tests, each red on the old code by hand:
- TestClientsAskNoWSL (agent): with Clients back on All(), red (waited
  past 5s on the hung wsl.exe); with AllKnown on wslDistros(), red.
- TestWSLFirstWaitIsWaitedOnce (sessions): four reads with the first
  listing hung; with the wait counted per read, red at 2.007s.
- TestCopilotWSLHangHoldsNoRequest (provider): a re-read on a hung WSL
  with copilotWSLWait 10s must answer within 2s; with the kept answer
  disabled, red at 2.002s.

Run at this tree:
- mote: go test -timeout 45m ./... at dac5095c3 (base b0674b9ec): exit 0, 102 packages ok, no FAIL. Rebased onto
  2ec8e6ad0 after it, which changes README files only.
- mica: go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... ok; gofmt -l clean.
- WSL (magpie-desktop): internal/agent, sessions, provider ok.
- Windows: internal/agent, sessions, provider, gui: 66 reds, 64 of them
  red at origin/main 2ec8e6ad0 too (#6068, #1827, #4115, #2808, #4446,
  #5957, #5343, #5344). The other two, TestHermesProfilesAreNotListedAsAgents
  and TestHermesProfilesFollowMagpieModel, call onMachine, not the code
  changed here, pass alone 3 of 3 on this tree, and follow other Hermes
  tests red at main in the package run (#1841: Windows tests share
  APPDATA).

Not tried: a real WSL distro that is slow (the fake wsl.exe stands in
for it), and the reporter's own machine.
2026-11-17 00:21:23 +08:00
yetone 90d54a2675 usage: Factory Droid's own sessions count under Not through magpie (_meouwu on X)
Droid's sessions were on the Sessions page, but Usage's "Not through
magpie" read no Droid calls, so what Droid spent straight at Factory or
a BYOK provider never added up.

Droid writes no tokens into a transcript: a message line has its time,
the message and a reply's modelId. Read from droid 0.231.0's binary
(its session schema) and the real runs in testdata/droid-skills, what a
session spent is only in <id>.settings.json: tokenUsage, its own running
total (input less the cache, output with thinking, cache read and
written), and lastCallTokenUsage, the latest call alone. So each session
is one call of its total, at its last message (the day Sessions already
counts the same total on), under its settings' model; a subagent's is
under the session that called it, a fork's starts at none.

- sessions: calls_droid.go reads a session with its settings whole
  (wholeCallReaders "droid"); droidFiles joins callSources, behind
  Reads("droid") and allowed() like the rest. WSL is not read: the
  Sessions page doesn't list Droid in a distro either.
- No double count: a session whose settings or any reply names magpie's
  own entry (custom:magpie/...) or a custom model whose baseUrl is the
  gateway's port on loopback is left out whole; the gateway counted those
  calls, and a total can't be split by model. A session is judged when
  read, again once it or its settings change.

Tests: TestDroidCalls (the 4 real droid 0.231.0 sessions: tokens, time,
model; custom:mh on localhost:11434 counted, on the gateway's port left
out; Reads off counts none), TestDroidCallsOfSessions (subagent, fork,
no settings, magpie's entry, Factory's own model), and
TestDirectDroidSessionTotals in usage. Both sessions tests are red on
origin/main (0 calls); with the gateway check broken by hand both go red
on the gateway cases.

Run (mote): go test ./internal/sessions
./internal/usage ok; go vet + GOOS=linux/windows go vet of both ok;
gofmt clean; go test ./internal/gui ./internal/agent ok.
Not tried: a real Droid session against Factory's own models (no Factory
account here); no GUI change.
2026-11-16 18:56:32 +08:00
yetone 91b3af8470 usage: Qoder's own calls are under Not through magpie, by the credits they cost (eating_dream on X)
Qoder's and Qoder CN's sessions were on the Sessions page and nowhere in
Usage: callSources never listed their files. They are Claude Code's
lines, and are now read for calls as Claude Code's are (ccCallAgent:
claudeCallLine, the call cache, continuations and revisions).

Qoder writes a reply on its own models ("auto" among them) with every
token count 0 unless QODER_EXPOSE_TOKEN_USAGE is set: the transcript
writer (vUl in qodercli, the same in Qoder.app's worker, qoder-agent-sdk)
zeroes them unless the model is a custom one, from qodercli 1.1.0 on. It
keeps the reply's credits. So such a call carries Credits (new on
sessions.Call, passed to the ledger's Record), counted with no tokens
and no price; "auto" names no model, so nothing is priced for it. A
model of the user's own, whose counts are written, is read and priced
as before. The GUI's direct section already shows credits (ledCredits).

Fixture: testdata/qoder-1.1.89 is lines as qodercli 1.1.89's writer
lays them out (key order, zeroed usage, credits/original_credits/
billable, a reply with no usage), read from its npm bundle; the ids are
made up. The older invented qoder fixtures got message ids of their own
(Calls counts a message id once across agents, and they shared
WorkBuddy's m1/m2).

Run (on mica, at f07e3e067's tree, rebased on 269e54de5):
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage
  ./internal/gui: ok
- GOOS=linux and GOOS=windows go vet of both packages: ok; gofmt -l clean
- red on the old code (origin/main's calls.go, call_cache.go,
  call_continuation.go, call_revisions.go, ledger.go with the new tests):
  TestQoderCalls got 0 calls, TestDirectQoderCallsByCredits Credits 0
  Credited 0

Not tried: no real Qoder transcript was captured (qodercli needs a
signed-in account here); the format comes from the bundle's writer. No
GUI change, so no GUI suite. A reply Qoder writes with no usage at all
is not counted. The tokens of Qoder's own models can't be shown: Qoder
doesn't write them.
2026-11-16 16:51:51 +08:00
yetone 64c4261582 sessions: search what was said in every agent's sessions, from the page and an MCP server
cryingLiu on X asked to search the chat history of every agent magpie
reads sessions from: prompts and replies, from one place.

What the user gets:
- The Sessions page's search also lists, under the agent's own list,
  the other agents' sessions whose conversation says the words, each
  with a snippet. A hit opens the conversation in the sheet at the
  message that said it (transcript?find=), with "N earlier messages
  not shown"; the page itself never scrolls. While the index is still
  being built the head says "Indexing sessions…" or "Indexing N of M
  sessions…", and the page asks again every 3s until it is done.
- Magpie Sessions, a built-in MCP server in Library → MCP (Discover),
  opt in per agent like the other magpie servers. Its tools are
  search_sessions(query, agent?, limit) and read_session(id, around?),
  both returning text. It runs as `magpie mcp sessions` over stdio and
  reaches the gateway's /mcp/magpie/sessions, which serves only local
  callers that are not browsers.

How it works:
- internal/sessions/said_index.go keeps said-v1.db beside sessions.json:
  a contentless SQLite FTS5 index (detail=none) of the words each
  session says. It is built from the sessions list sessions already
  caches and refreshed at most every 10s: a new or rewritten file is
  read once, a grown Claude Code or Codex file only from where it ended,
  and a gone one is forgotten. A query asks the index which sessions
  have every word, then reads only those files for the snippet, for at
  most 6s. A search waits up to 2s for a refresh. While the first
  listing is still running the answer says `listing`, so an empty first
  answer is not read as "no session says it".
- Privacy: only agents sessions.Reads allows are indexed or searched;
  nothing is read until the user has answered the sessions question,
  and in gateway mode no agent's own files are read (the page doesn't
  ask). Reset forgets the index.
- /api/sessions/said for the page; the CLI parity list names it.

Run, at this tree (rebased on origin/main 256910f17):
- gofmt -l clean; go vet on mote for darwin, GOOS=linux -tags nogui
  and GOOS=windows: ok.
- go test -tags nogui ./... -timeout 45m on the WSL Linux box:
  every package ok at c8e445c4b (the tree before the one-hit wording,
  whose gateway tests ran again on mote: ok).
- GUI: the whole suite on mica at this head was still running when
  this was pushed (owner: never hold a verified change behind a full
  suite). Under mica's load, beside another session's full suite, 90
  tests had failed so far, all in files this change doesn't touch
  (accounts, Details, keys, plugins, providers); none in sessions,
  library or i18n. The files this change reaches passed on their own
  (below).
- Focused, green: internal/sessions (Said*, TranscriptAt),
  internal/gateway (SessionsMCP*, own MCP, read-only, key slots),
  internal/library (market, opt in), internal/gui (Said, Sessions,
  gateway mode); GUI sessions-said, sessions-search, library-sessions-mcp,
  vision-mcp-library, library-browser-setup and i18n-keys in chromium
  and webkit, every language, wide and narrow.
- Broken by hand, one at a time, each red and green restored: the
  index's Listing left out (TestSearchSaidWhileTheSessionsAreFound red
  in 2.5s); the page ignoring `listing` (sessions-said 6 of 7 red); the
  MCP's local/browser guard (TestSessionsMCPOnlyForAgentsHere red); the
  server's opt in (TestSessionsServerInDiscover red); every Reads check
  on the search path, the index's and SearchSession's together
  (TestSearchSaidLeavesOutAgentsNotRead red). With those gone the
  gateway-mode GUI test stays green, because the sessions listing
  leaves an unread agent out before the index sees it.
- Real use, in a sandbox HOME with GOPATH, GOMODCACHE and GOCACHE
  pinned, over the real history through symlinks (29 GB Claude Code,
  60 GB Codex, 14,102 sessions), sessions reads set to all in the
  sandbox: first listing ~60s cold (answers say still being found),
  whole index built in 9m50s while queries answered in ~6s each, index
  38 MB, a common word 4.9s and a rare word 1.0s warm, read_session at
  the words of a huge session 1.8s, peak footprint 442 MB for the whole
  process with the sessions cache. Nothing was written under the real
  ~/.claude or ~/.codex.
- The real binary end to end on mote, in a sandbox HOME: `magpie serve`
  on a free port and `magpie mcp sessions` over stdio with
  MAGPIE_GATEWAY, against a Claude Code session written there:
  initialize, tools/list, search_sessions found it with its snippet,
  read_session at the words started 3 messages before them, a word
  nowhere said "No session says", and a POST with a web page's Origin
  was refused 403. That run is how "1 sessions say" was found and
  made "1 session says" (TestSessionsMCPSearch red before, green after).

Not tried: a real agent (Claude Code, Codex) calling the server it was
given from the Library, and the page against a real backend (the GUI
tests fake the API). The index on Windows and Linux ran only through
the Go suite.
2026-11-16 07:19:18 +08:00
yetone ff6f6337f1 sessions: the kept parses are written binary, not JSON
The Sessions and Usage index (sessions.json, ~18k files on a long
history) was JSON. Every start decoded all of it through reflection,
and every save, which happens at most once a minute while a session is
live, marshalled it whole again. It is now a compact binary form
(cache_binary.go):
- A magic and a version header.
- Then length-prefixed records, varints for the numbers.
- Interned names, as the JSON path interned them.
- The rare nested parts (Claude Code's window, a Codex identity,
  StateMore) as JSON blobs.
Records are decoded in parallel.

A JSON index from an older magpie is still read. loadCache saves it
again at once, so it turns binary on the first start even when no
session changed; before, a save came only after a file changed.

A binary file is refused whole, never half read: when it is cut
anywhere, has a byte added, or is of another zone or version. That
means one full read again, as a refused JSON file meant before.
TestCacheBinaryKnowsEveryField fails when state, day or Tokens gains a
field that the binary form doesn't carry.

On the real acctp history, on mote (18,346 files):
- The file is 14.8 MB, down from 23.3 MB.
- Decoding takes 19 ms, down from 69 ms, and allocates 28 MB, down
  from 58 MB.
- Encoding takes 10 ms, down from 98 ms, and allocates 3.1 MB, down
  from 32.5 MB.
- The heap kept after decoding is the same: 24 MB.
- /api/sessions from a w94 build on the binary index and from a w92
  build (before) on the JSON index answer the same bytes (5000
  sessions). Neither rewrote the index.
- The page-open footprint peak was 152 to 214 MB on both builds at
  load 60 to 80. It is too noisy to claim a change.

Run:
- mica-run go test -count=1 -timeout 45m ./internal/sessions
  ./internal/usage ./internal/gui: all ok.
- GOOS=linux and GOOS=windows go vet ./internal/sessions
  ./internal/usage: ok. go vet ./internal/sessions: ok.
- gofmt -l: clean.
- TestCacheBinaryRefusesBadFiles cuts the file at every length, adds a
  byte, changes the zone and the version, and flips every byte; it
  checks that a bad file is never accepted and never panics.

Broken by hand:
- The decoder skipped Provider: TestCacheBinaryIsJSON went red.
- loadCache stopped re-saving a JSON index:
  TestCacheJSONRewrittenOnStart went red, the file still JSON.

At the pushed head (rebased on 500f39886): go test ./internal/sessions
./internal/testenv ok.

Not tried: Windows and Linux runs of the package; the mapping read is
shared code and unchanged there.
2026-11-16 02:58:09 +08:00
yetone 9bcdcfb7d1 provider: Antigravity's Orchestrator ids are priced as the Gemini model each is
guyng35955 on X: an Antigravity local session's calls under
gemini-pro-orchestrator-argon, gemini-pro-orchestrator-carbon and the
worker gemini-flash-worker-agy showed tokens and cache but cost "—". They
are Orchestrator mode's role ids, which no catalog prices.

pricedNamesTo now reads them as the model Antigravity's docs name
(https://antigravity.google/docs/models/): Orchestrator (Argon) plans with
Gemini 4 Argon, Orchestrator (Carbon) with Gemini 4 Carbon, and Gemini 4
Hydrogen does the implementation, so the worker is priced as
gemini-4-hydrogen. gemini-pro-orchestrator (Carbon's id before Argon came,
per the Antigravity Context Window Monitor extension 1.17.1's table) is
Carbon too. Only these four ids, under a route prefix or an effort suffix;
a name only like one stays unpriced. Every cost reads through this one
place: the Sessions list and overview (sessions.priceOf -> PricedName),
the usage ledger, its totals and per-agent view (Pricer -> ListPrice /
MakerPrice). Prices are taken as rows are read, so sessions recorded
before the update are priced once it is installed; nothing is re-parsed.

Google publishes no rate for the role ids themselves; they are priced at
the named model's models.dev list price.

Run (mote, at this tree):
- the three new tests red on origin/main's models.go (every role id
  unpriced), green with the fix; red again with argon mapped to carbon
  by hand
- go test -tags nogui ./internal/provider ./internal/sessions
  ./internal/usage: sessions and usage ok; provider ok but for
  TestRemoveListedAccountLeavesHiddenNamesake (ZCode account removal,
  not reached by this change), which passes alone -count=3 with and
  without this change; filed as #6764 with its output
- go vet, GOOS=linux and GOOS=windows go vet of those packages; gofmt -l
  clean
Not tried: the reporter's own Antigravity database, or a real Orchestrator
mode account (this Mac has no Antigravity app and the account isn't
offered Argon). No GUI change.

Reported-by: guyng35955 on X
2026-11-15 22:17:30 +08:00
yetone 4f40a1061e sessions: a turn of a long Claude session reads none of its copies again (shangyuan0818 on X)
Usage → Sessions took ~20s on Windows for long Claude Code sessions
(tens to ~100 MB each, few rows). A session resumed or forked into new
files leaves whole copies of it, listed as one row, and the live one is
the file they are kept in. Each turn it gained re-read every copy whole,
twice:

- ccFamily dropped the uuids read of a group whose verdict it found on
  disk, so the next change judged the group by reading every file's
  uuids from the start. It now keeps them while the files start alike,
  as ccUUIDMemo's comment says, and reads on from where it stopped.
- ccRest read each copy whole again whenever the keeper changed. It now
  keeps the uuids of a copy's own messages, and while the copy didn't
  change and the keeper only grew and holds none of them, the rest
  stands. A keeper that took one of them has the rest read again
  (TestClaudeKeeperTurnTheBranchHeldIsCountedOnce, red with that check
  turned off: 90 in, want 80).

Timings, Windows (xiaomi-gpu), a 100 MB Claude session from a real one
with its text scrambled, copied under new ids:
- in process, 4 copies, /api/sessions after a turn: 261 ms and 332 ms,
  now 26 ms and 27 ms; after a start and a turn 523 ms, now 239 ms.
- the real dev backend (magpie app, sandbox HOME), 8 copies, the page's
  three calls after a turn: 607 ms, now 31 ms. Cold start 1.9 s both.
These scale with the copies and their size; the reporter's machine is
slower than this one.

Run:
- TestClaudeKeeperTurnReadsNoCopy red on the old code (copies and
  keeper read whole each turn); red with each half undone alone.
- win-run go test ./internal/sessions ./internal/gui: 14 reds, the same
  14 on origin/main 4a4424ea8 run alone (#6071, #6068, #5324, #5928,
  #6059).
- wsl-run go test ./internal/sessions at this head (on 4a4424ea8): ok. TestCCListingKeepsItsNames
  passes on Linux at base and head.
- go vet ./internal/sessions for linux, windows, darwin; gofmt clean.

Not tried: the reporter's own files; WSL-hosted Claude sessions; mote and
mica were over load, so no macOS run. After a start, the first change to
a group still reads each file's uuids once.
2026-11-15 18:56:34 +08:00
yetone 75f872ef19 sessions: a page gone from view lets the parsed session files go in 30 s, not 3 minutes
v0.1.4150's away timer let the Sessions stats and the Requests chunks go
30 s after the app's page went from view, but a web page open 70 s and
closed still held 92-93 MB 45 and 90 s on. A heap taken 45 s after the
close (liveHeap 57 MB, 15 MB at +180 s) showed why: opening the page
starts the warm-up (warmStart), which parses every session file, and
those parses (decodeCache, the listings, Codex identities: ~40 MB live
for the acctp history) go only by the sessions package's own cacheIdle,
3 minutes after their last read.

forgetAwayPage now also calls sessions.ForgetParses, which is
dropIdleCache without the 3-minute wait (dropCache(0)): it still keeps
the parses while a save isn't on disk, the last failed, or a file is
being parsed, and the next read has them back from sessions.json with
no session file read. It runs only when the stats went too, so a range
being read keeps them.

Test: TestForgetParsesLetsGoAtOnce (red with ForgetParses waiting
cacheIdle, broken by hand).
Measured on mote (pageclose2.sh, acctp, page open 70 s and closed,
footprint-overlay build like the release):
  v0.1.4150 (w90): close 122 MB, +45 s 93, +90 s 90, +180 s 55, +600 s 52
  this (w92):      close 125 MB, +45 s 64, +90 s 61, +180 s 56, +600 s 53
A debug build (w91) logged the away timer firing with no read since,
so the 90 MB left was this cache, not a skipped let-go.

Run: go test ./internal/sessions ./internal/gui ./internal/usage on mote
(ok); GOOS=linux go vet -tags nogui and GOOS=windows go vet of the two
packages (ok).
2026-11-14 17:45:41 +08:00
yetone c41fa8e478 sessions: an OpenMausBot conversation can be shown (@qingqingdilaiP on X)
@qingqingdilaiP's OpenMausBot rows in Usage → Sessions (b507b5f69,
v0.1.4146) had a time, an id and ~\.openmausbot\messages.db#<id>, but no
Show conversation: HasTranscript left openmausbot out, so the row had no
transcript flag and /api/sessions/transcript, the Markdown export and the
Sessions filter refused it.

ombTranscript reads the conversation from messages.db (the listing's
path up to its last "#", the session's id as thread_id), on its own
read-only connection, in one read transaction, ordered by at and rowid
as the listing reads it:
- a user text is the person's message;
- a bot text, and an options card's words (MausBot's first message is
  one), are the bot's;
- an activity of a turn's item (tool.itemId, as server/index.js writes
  on item.started) is a tool_use with its input (else its summary, else
  its name: the sample's agents_list_bots kept no input), and its output
  a tool_result;
- an activity with no item (a notice, a queue or engine move, which
  OpenMausBot adds itself) and a turn's digest, which repeats the reply,
  aren't said.

Sibling check: Hermes and Alma, listed the same way (read-only database
rows, 5a4104632, dc3deaf09), have no Show conversation either, nor do
zcode, dsh, cline, grok, droid, workbuddy, workbuddy-ai, codebuddy and
antigravity. Filed as #6633; not changed here.

Tests (testdata/openmausbot, OpenMausBot 0.1.155's own data folder as
b507b5f69 recorded it):
- TestOpenMausBotTranscript: both conversations flagged in List and on
  the Sessions page; Find + TranscriptOf as the GUI route does gives the
  team thread's prompt, "Checking the team.", agents_list_bots, its
  result, the reply, and the fruits thread's 4 texts with no digest;
  WriteMarkdown and SearchSession read the same rows; messages.db's bytes
  unchanged.
- TestOpenMausBotTranscriptToolsAndNotices: rows inserted in the shapes
  OpenMausBot writes (item.started/completed with input and output, a
  cloud-credit-moves notice): the tool shown with its arguments and
  result, the notice not said.
Broken by hand, each red: openmausbot out of HasTranscript (no flag,
"can't be shown"); the itemId check removed (the notice said as a tool).

Run on mote: gofmt -l clean; go vet ./internal/sessions ./internal/gui,
GOOS=windows go vet ./internal/sessions, GOOS=linux go vet -tags nogui
./internal/sessions; go test -count=1 ./internal/sessions ./internal/gui
ok; node --test sessions-talk, sessions-talk-sheet, sessions-talk-model,
sessions-export, sessions-search (Chromium and WebKit, their languages
and widths): 54 of 54 pass (the GUI is unchanged: it shows the button
from the row's transcript flag). On Windows (xiaomi-gpu): go test -run
'OpenMausBot|Alma|Hermes' ./internal/sessions ok.

After a rebase onto 80a315a70 (no internal/sessions change; internal/gui's
cache change): on mica (mote over its cores), go vet and go test -count=1
./internal/sessions ./internal/gui ok, at the pushed tree.

Not tried: the live GUI against a real OpenMausBot on Windows (the
reporter's case); a conversation with images or cards other than options
(secret, signin, connector are left out); not the full ./... suite (the
change is inside internal/sessions, whose only callers here are
internal/gui's routes, both run).
2026-11-14 17:04:45 +08:00
yetone b507b5f692 sessions: OpenMausBot's conversations are read (@qingqingdilaiP on X)
@qingqingdilaiP asked for OpenMausBot's sessions in Sessions. OpenMausBot
(milind-soni/OpenMausBot, npm 0.1.155) is already an agent in magpie,
but its conversations were not read. It keeps its data in $OMB_DATA_DIR,
else ~/.openmausbot on every system (server/config.ts):
- bots.json: bots[].tasks[], one a conversation (threadId, title, "New
  thread" until named, and cwd once a turn pins it);
- messages.db: SQLite in WAL mode (thread_id, at ms, role user|bot, kind
  text|activity|..., text, json; an activity's json holds tool.name, a
  bot text its turnId);
- usage/<YYYY-MM>.jsonl: one row a turn (driverKind, model, input with
  cachedInput and cacheWrite included, output).

internal/sessions/openmausbot.go lists each conversation as a read-only
session, like Alma's and Hermes's rows: prompts, one reply a turn (a
turn says a line before a tool and again after it), tools by name,
title from bots.json (else the first prompt), folder from task.cwd,
times from messages and usage rows. A conversation holding only a bot's
greeting is left out. Its rev joins the thread's count, last time,
bytes, usage rows, title and cwd, so a write to it, or a new title,
reads it again while the database file looks the same. Tokens count
only for API drivers (server/agents-bridge-switch.ts's
CHAT_RUNTIME_DRIVERS): a bot on Claude Code, Codex, Pi or another agent
CLI runs that CLI, which keeps the turn in its own session, so its
tokens are counted there and would be counted twice. Fresh input is
input less cache reads and writes. bots.json and the usage files are
read again only when their size or time change. Dirs() and Reads/access
cover messages.db. Delete refuses it: OpenMausBot keeps the database
open.

Tests (testdata/openmausbot is OpenMausBot 0.1.155's own data folder,
written by the real app in a sandbox on mica with an OpenAI-compatible
fake model, database checkpointed):
- TestOpenMausBotSessions: titles, tokens, times, greeting-only threads
  left out, the Sessions page (2 rows, not deletable, 4 and 2
  messages), Delete refused, stats (1 prompt, 1 reply, agents_list_bots
  once), Dirs(), the database's bytes unchanged.
- TestOpenMausBotCountsCLITurnsOnce: the sample's rows with one turn on
  claudeAgent and one with cache read and write, cwd pinned.
- TestOpenMausBotReadAgainWhenItChanges: a new title alone, then a new
  row with the file's time held.
- skillsCounted: openmausbot says why its skills are not counted (a bot
  reads a SKILL.md with its file tools, and the sample has no such turn).
Broken by hand, each red: CLI rows counted (claude tokens 1202/42),
no turnId dedupe (team 3 messages, 2 replies), no rev check and title
ignored (new title not read), cache left in fresh input (1203), greeting
threads listed (4 rows).

Run: gofmt -l clean. On mote (load ~20 on 18 cores, mica busier with a
GUI run): go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows
go vet ./..., go test -count=1 -timeout 45m ./... at 59c5b59ea (this and the yaml.v3 commit on df2b819c6): 100 packages ok. The first run, at 13cb07fde, was red in internal/sessions' TestEveryAgentSaysItsSkills (openmausbot not in skillsCounted, added here) and the root's TestNoEagerPackageRegexps (main's yaml.v3, the next commit). On Windows
(xiaomi-gpu): go test -run 'OpenMausBot|Alma|Hermes' ./internal/sessions ok.

After a rebase onto ea6470cb7 (01c3efc4f's library change and a GUI
test): vet as above, and go test . ./internal/sessions ./internal/library
./internal/catalog ok. After another onto 79a30eb9c (edit/toml.go and
provider/remote_follow.go perf): go vet ./..., go test . ./internal/sessions
./internal/edit ./internal/provider ok, at the pushed tree.

Not tried: a conversation on a Claude Code or Codex engine in the real
app (its tokens come from that CLI's own session, by design here); the
live GUI (unchanged); OpenMausBot on Windows or Linux. Not covered:
magpie's own engine in OpenMausBot runs Claude Code with its config in
<data>/providers/magpie, a Claude home Sessions doesn't read, so those
turns show nowhere yet.
2026-11-14 15:42:01 +08:00
yetone 50d88f17ce sessions: the Claude subscription bridge's own runs are not local sessions
iwinux on X: a Pi request through a group a Claude subscription serves
was listed twice in the request log, once as "Pi · Claude Code" and once
as "Claude Code · Local session", with the same tokens and cost.

Cause: a bridge run is the real Claude Code. It saves its session in the
account's projects folder, in the caller's folder's project: the user's
own ~/.claude or a saved account's claude-accounts folder, both of which
appdir.ClaudeHomes lists. listCCFiles read it as a session of the user's,
and the ledger's pairing (request id, then session and tokens) didn't
match it with the gateway's record, whose session is the caller's. So
every call was counted twice: request log, usage ledger, cost totals,
the Sessions page. -p runs and interactive (TUI) runs alike, plus a
branch's cut copy and a replayed transcript.

Fix: every session a bridge run saves is named by the new
internal/bridgesid. New is a version 4 UUID whose last six bytes are a
keyed SHA-256 of its first ten, the key a random file of this computer's
(<config>/claude-bridge-session-key, made once by temp file + link). To
Anthropic, which Claude Code sends the session id to, it is as random as
any, so it marks nothing upstream. startRun passes --session-id for a new
run (-p and interactive; the TUI helper keeps a --session-id it is given
and makes a marked one otherwise), replaySession and cutSessionWhere name
their files with it. listCCFiles leaves out a .jsonl, and a session's
sub-agent folder, whose id bridgesid.Is knows, for agent "claude" only.
That one listing feeds calls, the ledger, the request log, Sessions,
traces and WSL distros, so all of them drop the double count. Other
bridged runs (warm-up, askClaude, /usage, WSL -p) use
--no-session-persistence and write no session.

Rows already counted twice: a bridge session already removed (a run's
session is removed when it ends) is gone from the ledger already, as it
is read from the files there are. One still on disk under an old random
id (a live or shelved run resumed under it, or a stopped gateway's
leftover in a caller's folder) can't be told from the user's and stays
counted until it is removed; old ids carry no mark to fix it on read.

Tests: TestNewIsKnown, TestKeyKept, TestKeyMadeOnce (bridgesid);
TestBridgeSessionsAreNotLocal (sessions: a marked session in the user's
folder, its sub-agent file, and one in a saved account's folder give no
calls and no rows; the user's session beside them counts);
TestClaudeRunSessionsAreTheBridges (-p and interactive, a new run and a
replayed transcript) and TestClaudeCutSessionIsTheBridges (gateway).

Broken by hand, on mica: bridged() returning false made
TestBridgeSessionsAreNotLocal red (calls req_m1..m4, want req_m1 alone);
newUUID back in startRun, replaySession and cutSessionWhere made both
gateway tests red (print, interactive and the cut copy).

Run on mica at this head (rebased on 7ea1e6a4b): gofmt -l clean, go vet
./... ok, go build ok; go test -tags nogui ./internal/bridgesid
./internal/sessions ./internal/usage ok; ./internal/gateway -run
'Claude|Subscription|Bridge|Fork|Shelf' ok. At the first base (8a59e7616):
the same vet plus GOOS=linux -tags nogui and GOOS=windows vet ok, the three
builds ok, ./internal/claudetui ./internal/appdir ./internal/masking ok.
The full ./... suite was not run: mica's suite lock had five full suites
queued ahead of it, and this ships now.

Not tried: a real Claude Code run with a real account (mote is down;
the -p --session-id flag is Claude Code's documented one, and the
interactive helper already passed it); Windows and WSL runs.
2026-11-14 14:17:52 +08:00
yetone 667ac8bd6f settings: a look at one setting takes the shared settings, not a copy
settings.Load() copies the whole Settings (clone + deepCopy of every map
and slice) for each caller. 133 places read one field of it and threw
the rest away: the proxy for every outgoing request (netproxy), the
GitHub token, the China mirror switch, a model's output cap, wire or
price on a gateway request. With a real account in the tray, Load's
clone was 26.6 MB of the 318 MB the process allocated in its first
seven minutes, most of it through netproxy.For on each request.

Each of them now reads settings.Shared(), the read-only settings every
caller is given for the same settings.json. Only reads were changed:
a scalar field (string, bool, int, float) or a map field's index
read. A caller that keeps a whole map or slice, or calls a method on
the settings, still takes Load's copy.
2026-11-14 14:02:49 +08:00
yetone c51b0ca9fa sessions: the Antigravity app connected to WSL has its usage read from the distro (@guyng35955 on X)
@guyng35955 on X: on Windows, with the Antigravity app connected to a
WSL Ubuntu, magpie showed no Antigravity usage.

Why. Antigravity 2.x (dist/wsl.js and languageServer.js in its
app.asar) runs a Linux language server in the distro when it is
connected to WSL ($HOME/.antigravity-server/bin/<version>/
language_server, started through wsl.exe with --app_data_dir
antigravity), so the conversations go to the distro's
~/.gemini/antigravity, not %USERPROFILE%\.gemini\antigravity. magpie
read Antigravity's conversations only from this computer's folder:
- sessions.wslAgents had no antigravity (nor agy, whose
  ~/.gemini/antigravity-cli in a distro wasn't read either);
- internal/agent kept a distro for the Sessions page only when one of
  wslKinds or the Copilot CLI's folder was there, so a distro with only
  the app's data never reached sessions.WSLHomes;
- and, found on the Windows box: no SQLite database under
  \\wsl.localhost opens in place. Every form (file: URI, plain path,
  mode=ro, provider.OpenReadOnly) answers SQLITE_BUSY after its 3s
  busy_timeout, since the share doesn't take the locks a WAL database
  needs. So listing the files alone would have shown nothing still.

What changed.
- agent: wslKept keeps a distro with ~/.gemini/antigravity(-insiders),
  and the probe looks for them (no agent row for them).
- sessions: wslAgents reads the app's conversations (insiders under
  their own key) and agy's in a distro; their summary rows name the
  distro's folders as Linux does (agyFolder with goos "linux", so
  /home/me/site, not a Windows path). The distro's calls count in
  Calls (wslFiles("antigravity"), wslCallFiles("agy")). The listing
  kept on disk (sessions-wsl.json) carries each file's row, rev and
  read-only, so a stopped distro keeps its titles and folders. A
  distro's ~/.gemini that is this computer's own (a link) is read once,
  as this computer's (sameDir).
- sessions: openAppStore opens agy's and the app's databases read only
  in place, or, under \\wsl.localhost or \\wsl$, as OpenUntouched does
  (immutable with no -wal, else from a copy of the db and its -wal).
- docs/subsystems/agent-wiring.md says which distros are kept for reads
  only.

Not changed: session-read consent ("allow selected" names agents found
on this computer) doesn't look in WSL, as before for every WSL agent.
OpenCode's and ZCode's SQLite readers aren't used for a distro (not in
wslAgents), so they keep provider.OpenReadOnly.

Run (at the tree rebased on dc85a7ca5; then rebased on c8290df25, which
changes nothing under internal/sessions or internal/agent):
- mote: gofmt -l internal (clean); GOOS=linux go vet -tags nogui ./...
  and GOOS=windows go vet ./... ok; go test -tags nogui -count=1
  -timeout 45m ./internal/sessions/ ./internal/agent/: ok (sessions 104s,
  agent 223s).
- Windows 11 (xiaomi-gpu, win-run): go test -run TestWSL
  ./internal/sessions/ ok.
- Real \\wsl.localhost read on xiaomi-gpu: a fixture conversation
  (WAL) and conversation_summaries.db, and agy's conversations, written
  in the WSL distro magpie-desktop's real ~/.gemini from inside Linux;
  a throwaway test on Windows with WSLHomes at
  \\wsl.localhost\magpie-desktop\home\yeton. Before openAppStore: agy
  listed with no folders, the app's conversation missing, 0
  antigravity calls, listing 6.4s (each open waits 3s for BUSY).
  After: the conversation listed with the distro, its title, folder
  /home/me/site, tokens and 4 calls; agy's folders read; listing
  0.21s. With a writer in the distro holding a title only in the -wal
  (wal_autocheckpoint=0, db held open), Windows read the -wal's title.
  The fixture and binaries were removed after.

Broken by hand:
- the three wslAgents entries and the Calls line out:
  TestWSLAntigravityApp red (no antigravity session from the distro);
- sameDir check out: TestWSLAntigravityLinkedHomeOnce red (listed as
  the distro's);
- the listing's row (m.agy, m.rev) not carried: TestWSLAntigravityApp
  red (no title or folder);
- wslKept without the Antigravity dirs: TestWSLAntigravityHome red
  (no homes).

Not tried: a real Antigravity sign-in connected to WSL (the box's app
isn't signed in, and the connection needs its GUI), so the language
server's own files are this fixture, laid out as its source writes
them; the full suite (five full suites were queued on mote's
suite.lock and two on mica's).
2026-11-14 12:27:25 +08:00
yetone 71a806749d sessions: a paginated Codex rollout moves to a longer provider id by its row (@xMopf7RF on X)
@xMopf7RF on X (tweet 2121441393424113800): the Sessions page's Move
refused an old Codex session with "rollout-2026-03-09T09-25-….jsonl.zst
keeps its history by byte, and "magpie" is longer than the provider it
names: Codex couldn't open it moved", and offered nothing else.

Since 67b12956a a paginated rollout's session_meta is only rewritten at
its own length (Codex keeps places in it by byte), and MoveCodexProvider
refused a longer id outright. But Codex reads a paginated thread's
provider from its row in the state database, never from its file
(codex-rs read_thread; RetagPagedCodexThreads already moves such threads
by the row alone, tried with the real codex 0.166). So now
rewriteCodexProvider leaves such a line as it was and says so (kept),
and moveCodexPaths moves the thread by its row. Every caller gets it:
the Sessions page's Move, Resume's move first, and the sync's
MoveCodexThreads/MoveRecentCodexThreads, which met the same refusal for
a provider shorter than magpie.

With no row to move it by, it can't move at all: it is refused as
sessions.StuckError, every file put back and no trash copy left, and the
API says stuck with the provider it stays on. The page then says why,
that the session stays on that provider unchanged and shows in Codex when
Codex uses it again, and that Delete clears it into magpie's trash, where
it can be restored. New string in zh, zh-TW, ja and de.

Run, at 7951989c6 (on origin/main e0889719c):
- go test -count=1 -run 'TestMoveCodexProvider|TestRetagPaged|TestPortCodex'
  ./internal/sessions/ on mote: ok.
- Old code back (codex_provider.go from e0889719c, StuckError stubbed):
  TestMoveCodexProviderPagedByRow and TestMoveCodexProviderPagedNoRow
  FAIL with the reporter's exact error text; green with the change.
- node --test sessions-codex-provider-stuck, sessions-codex-provider,
  sessions-codex-provider-pick, i18n-keys, i18n-en-no-cjk on mote,
  Chromium and WebKit, five languages, 900px and 420px: 42 of 42 pass.
  The new GUI file with the old client.js: 0 of 20 pass.
- gofmt -l on the changed packages: nothing.
- Full suite (vet x3, builds x3, go test -tags nogui ./... -timeout 45m)
  queued on mote's suite lock; pushed before it ran, per the owner's
  ship-at-once rule. Its result goes in a follow-up.

Not tried: a real Codex resuming a thread moved this way. The row-only
move is the one RetagPagedCodexThreads makes, which was tried with codex
0.166.0 exec resume (docs/subsystems/agent-wiring.md). Not reproduced:
the no-row case with real Codex, where Codex 0.166 keeps a row for every
paginated thread; it is covered by a fixture only.
2026-11-14 11:42:17 +08:00
yetone ab4b1cf38f sessions: a long Codex rollout is read on after a restart, not read again whole
shangyuan0818 on X: on Windows, Usage > Sessions took over ten seconds to
open with one very long session (tens to 100 MB), though there were only
a few sessions.

Cause: a Codex rollout's summary window (state.Codex) and its calls'
window (cxRun) lived in memory only. After a restart, or once the window
had been dropped, the first line a live rollout gained made parseRead,
prepareCalls and readsWhole read the rollout again from its first line:
once for the summary and once for the calls. Claude Code sessions were
already read on through their kept windows (#3493).

Fix: the window of a rollout being written (changed within the hour, the
same files memory keeps windows for) is now kept on disk with the parser
version, a window version, and the size, offset and content hash of the
read that made it. The summary's goes in codex-windows/<hash>.gob next
to sessions.json. It is written with sessions.json, and it is removed
once the cache drops that window. The calls' window goes in the shard's
.rev file next to Claude's. Each is used only when all of those match,
so a window from another read, or from an older layout, is never used;
the file is read whole instead, as before.

Measured (100 MB rollout built from testdata/codex-native-paginated.jsonl,
plus a 100 MB Claude Code session, GET /api/sessions in a sandbox HOME):
  mote (M5), before: after one line appended following a restart, 2.51 s
    (Codex alone 2.25 s). After: 9.7 ms (Codex alone 6.3 ms).
  Windows (xiaomi-gpu), before: 2.61 s. After: 22.8 ms.
  The first read with nothing kept is unchanged: 2.6 s on mote, 2.8 s on
    Windows. Warm and plain-restart opens were already 10 to 30 ms. stats
    and overview stayed at a few ms throughout.
  A real 32 MB rollout: 24 ms after an append, with 2 KB and 4 KB windows.
    A 100 MB rollout with a unique response id per turn: 11 ms, with
    623 KB and 834 KB windows.

Tests: TestCodexSessionReadOnAfterRestart reads a rollout, restarts, then
appends a replayed token_count and a new turn. It checks that neither
reader starts at offset 0, and that calls and the session's tokens,
models and cost match a read from scratch. TestCodexWindowLeavesWithItsSession
covers writing, reading back, refusing another read's window and
removal. TestPlainRolloutReadOnceForSessionsAndCalls (#4369) expected
both readers to start from 0 after a restart; it now expects them to
read on.

Broken by hand, each red: the summary window not read (starts [319830 0]);
the calls window not read ([0 319830]); a summary window emptied of what
it had seen (it panicked in codexUsageState.count, which is why the
version guard was added); a calls window emptied (62 calls vs 61).

Run: gofmt -l clean. GOOS=linux and GOOS=windows go vet -tags nogui ./...
on mote. Full go test -tags nogui -timeout 45m ./... on Linux (wsl-run,
magpie-desktop) at this change on 70bd270ae: every package ok but
internal/usage, whose TestRequestStateKeptAcrossACatalogFetchedAgain is
red the same way alone on origin/main 7b50e1f2c (11 of 20; a same-size
catalog write in one mtime tick, filed as #6572). mote's suite.lock had
five runs queued ahead, so its run of this change is still waiting.
Rebased onto 7b50e1f2c (7 files in internal/provider and internal/usage,
none under internal/sessions); provider, usage and sessions run again
there on Linux: all ok (#6572 passed this time). win-run ./internal/sessions/: only TestAgySessions,
TestAgyRowOnly, TestAntigravityAppFolder and TestCCListingKeepsItsNames
fail, and they fail the same way on origin/main ea9f2639b (#6071).
win-run -run 'Session|Usage|Calls' ./internal/gui/: only
TestGatewayModeStatsNameTheGatewaySessions fails, the same on ea9f2639b
(#6068).

Old data: right after updating, every user's live rollout is read whole
once more on its next change, since no window has been kept yet. From
then on it is read on. Nothing else changes for files not written within
the hour.

Not changed: WorkBuddy, WorkBuddy AI and CodeBuddy calls are still read
whole on every line (556 ms per 100 MB on mote), filed as #6565. Not
tried: the reporter's own machine and files.
2026-11-14 03:28:08 +08:00
yetone f798b4eb7a sessions: keeping a file's calls trims the revision windows only when it holds one
keepCalls and keepCallContinuation trimmed every kept window after each
keep, under callsMu: a sort of the candidates and a map, twice a file.
A request-index build reads ~11.5k session files through four workers,
and the files it reads are disk shards that hold no window (weight 0),
so each trim changed nothing while the workers queued on callsMu for it.
A block and mutex profile of a real-account rebuild showed ~55k
contentions on callsMu (about 5 a file), ~3.5 s of lock handoffs and
~4.3 s in pthread_cond_signal.

Now keepCalls trims only after keeping a file with a window, and
keepCallContinuation only after it adds an entry (its early returns add
none). Every window added is still trimmed at once, so the budgets hold
as before; a window aging out waits for the next keep that adds one.

Run: go test ./internal/sessions ./internal/usage ./internal/gui (ok, on
mica), go vet, GOOS=linux and GOOS=windows go vet ./internal/sessions,
gofmt -l. Real account on mote (75G sandbox HOME, network blocked): a
request-index rebuild forced by a new Anthropic price each run, CPU of
the process 30 s after start, alternating: v0.1.4052 21.25 / 17.68 /
15.95 s, this change 14.81 / 14.14 / 13.43 s (mean 18.3 -> 14.1 s).
Not tried: a test that counts trims; the change is a cost, and every
kept window is still trimmed by the same code.
2026-11-13 21:34:15 +08:00
yetone f5553d7103 sessions: a Pi subagent's calls are its lead session's, on its own model (nzvzbmz78932 on X)
nzvzbmz78932 on X: "在pi子代理中使用了deepseek 但是不显示用量". pi-subagents
(npm 0.88.1) runs each subagent as a Pi of its own, its session in
<lead file's folder>/<run id>/run-<n>/session.jsonl (async and parallel
runs a level deeper), or under extensions/subagent/config.json's
defaultSessionDir, its header's parentSession naming the lead's file.
magpie read only sessions/*/*.jsonl, so those files were never read. The
lead's `subagent` tool result carries the subagents' usage summed, and
piParse counted it on the lead's model and provider: a lead on magpie's
entry made it the gateway's (piGateway), so DeepSeek's calls were on no
page, Usage or Sessions.

- piFilesIn reads every session file under a lead's folder as the
  lead's (non-main, like omp's), and the defaultSessionDir ones through
  their headers' parentSession, up to 8 levels.
- piSubagentsRead: a tool result whose every sessionFile is one of those
  counts nothing, in piParse and piCall; one naming a file not read
  still counts as before.
- The scout's header id is in Session.Subs (pi is idInFile), so a
  subagent on magpie's entry is the lead's row to the gateway too.
- state.codexPath is parsePath, the file read, for piLeadID: a new field
  took state past its 416-byte class (TestStateFitsItsSizeClass).
- parseVersions and callParseVersions pi/raft/cindy raised.

The fixture is a real run: Pi 1.4.0 with pi-subagents 0.88.1 in a
sandbox PI_CODING_AGENT_DIR, a lead and one scout on a relay's
deepseek/deepseek-flash; system prompts dropped, paths rewritten.

Run (mica, at this head):
- go test ./internal/sessions: ok (119s)
- GOOS=linux and GOOS=windows go vet ./internal/sessions: ok; gofmt clean.
- Linux (wsl-run, magpie-desktop): TestPi*, TestOmp*, TestCodex*,
  TestStateFits*: ok
TestPiSubagentCalls: beside the lead and in defaultSessionDir, each with
the lead on the relay and on magpie's entry (the reporter's case).
Broken by hand: without the walk, 3 of 5 calls and 0 of 2 with the lead
on magpie (red); without the tool-result skip, 6 calls, the sum counted
again (red); the Subs check was red while it named the run id.
Not tried: the reporter's own files; a subagent nesting subagents; a
subagent run on magpie's entry against a live gateway.

With f0fb22c6b and 5bc816c1a below it, at this head (mica): go test
./internal/sessions ./internal/agent ./internal/claudecode ok,
./internal/gateway -run TestClaude ok, GOOS=linux and windows go vet of
the four ok, gofmt clean.
2026-11-13 19:07:34 +08:00
yetone 18b46f5c25 sessions: the Kimi desktop app's Work calls reach Usage
CNSA0422 on X: magpie didn't count local usage from the Kimi desktop
app. Its Work agent is Daimon, which runs the Kimi Code runtime it
vendors with its own home under the app's share folder, so its calls
are written as Kimi Code's usage.record lines in a folder magpie never
looked in.

Read from Kimi 3.2.27's own bundle (com.moonshot.kimichat, Daimon
1.0.10, Kimi Code runtime 0.5.1): the app passes KIMI_SHARE_DIR, which
is <userData>/daimon-share or the absolute shareDir in
<userData>/daimon-storage.json; Daimon alone falls back to ~/.kimi.
The sessions are <share>/daimon/runtime/kimi-code/home/sessions/<slug>/
<id>/agents/<agent>/wire.jsonl. userData is kimi-desktop under
~/Library/Application Support, %APPDATA% or ~/.config.

- kimi_work.go finds the shares and adds their wire files to Kimi
  Code's ("kimi"), as MiniMax Code Desktop's count as MiniMax Code's.
  Found() lists kimi when only Work sessions exist.
- A record's model is Daimon's alias (daimon-kimi-code). It is read
  as the alias's model in the runtime's config.toml (k2p6-agent).
- magpie's kimi-desktop plugin points the alias's provider at a bridge
  on 127.0.0.1 that forwards to the gateway, which logs those calls.
  A call whose alias's base_url is a loopback address is skipped, so
  it is not counted twice. config.toml is the current setting only,
  so history read for the first time is judged by it.
- docs/subsystems/gateway-sessions.md says so.

Run (mote): go test ./internal/sessions -count=1, ok;
go vet ./internal/sessions for darwin, windows, linux -tags nogui, ok.
Windows (xiaomi-gpu, win-run): go test ./internal/sessions
-run 'KimiWork|Loopback|KimiCode', ok. gofmt clean.

Broken by hand: kimiCallFiles without the Work files made
TestKimiWorkCalls red (no calls), and so did dropping the loopback skip
(the bridged call counted). Restored, green.

Not tried: a real Kimi Work session. This computer has no Kimi desktop
data, so the fixture's records are the Kimi Code format the bundle's
UsageRecord writes and its config.toml is what modelToToml builds. The
Windows installer was not unpacked: the Windows path is Electron's
userData as the bundle's code reads it. k2p6-agent has no price in the
catalog, so these calls show tokens and no cost.
2026-11-13 15:12:46 +08:00
yetone 11ab58c587 sessions: a kept folder listing is one array (#2278)
readDirectory keeps each folder's listing to tell an unchanged folder
from a changed one. os.ReadDir's entries are a pointer each to a
separate unixDirent plus its name, so a Codex sessions tree of 10k
files held 20k small objects for as long as magpie ran. The kept
listing is now one []keptEntry (dir, name, type) with pointers into
it: one object per entry, and Info() still lstats on demand as
os.ReadDir's does. Windows keeps os.ReadDir's entries (their Info is
already filled and cheap).

Measured on mote, 10k-file folder, HeapAlloc/HeapObjects kept across
readDirectory, 3 runs each:
  before: 1,297,928 B, 19,996 objects (129.8 B/entry)
  after:  1,042,664 B,  9,994 objects (104.3 B/entry)
-20% bytes and half the objects the GC scans each cycle.

Run: go test ./internal/sessions on mote (TestKeptListingIsCompact
checks entries equal os.ReadDir's in Name/IsDir/Type/Info, are
contiguous, and an unchanged folder is not listed again).
Not tried: Windows (path unchanged there).
2026-11-13 14:45:32 +08:00
yetone 6bcdc6468d sessions: agy's own calls name the model its conversation database names (DvnT662 on X)
Usage → Requests showed every call read from a local agy-cli session with
no model (v0.1.3996). The calls reader read only agy's transcript,
brain/<id>/.system_generated/logs/transcript_full.jsonl, which carries
tokens but no model. agy keeps the model in conversations/<id>.db, the
Antigravity app's layout: gen_metadata field 1.19 is the served model,
and a step's metadata field 20.3 names its generator (0 when left out, as
antigravityRead reads it). A generator's "last_step_index" n in 1.20 names
step n+1 for steps the steps table doesn't hold.

- calls_agy.go: agyStepModels reads the db read-only and gives each
  transcript step its model (through agAppModel, so -n deployment
  suffixes go as on the app's rows). The call file's stat folds in the
  db and its -wal, so a model written after the step is read again.
- agy.go: the Sessions page counts each step's tokens under that model
  (still "agy" when the db names none), and its rev folds in the db too.
- parseVersions / callParseVersions "agy": 1, so cached parses are redone.

Fixture: gen 0 is parkavenue9639's real agy 1.5.6 gen_metadata row from
#3147 (matching its transcript step 1, 11519 in / 781 out); steps.tsv is
the real steps.metadata agy 1.5.7 wrote on this Mac. Generator 1 is made
in the test.

Run (mote): go test -count=1 ./internal/sessions ./internal/usage ok;
go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok; gofmt -l clean.

Broken by hand, each red: calls given no model; no last_step_index
fallback; Sessions not moving counted tokens to the model; call files
ignoring the db's stat; Sessions rev ignoring the db.

Not tried: a live successful agy turn (this Mac's only agy account is
refused, so its db has no answered step); agy in WSL; conversations with
a db and no transcript still count nothing (#5432); tok/s and stripping
-trial (#4805).

Refs #3147, #4805, #5432
2026-11-13 13:53:05 +08:00
yetone e630c003cd usage: Devin CLI's own calls are read from its sessions (aohan0905 on X)
Usage counted none of Devin CLI's requests. Devin's CLI (3000.11.234,
run for real in a sandbox HOME) keeps its sessions in
<data>/devin/cli: sessions.db (SQLite: sessions, and message_nodes with
each chat_message), or with DEVIN_SESSION_STORE=files a folder per
session (log.jsonl + meta.json), whose first run copies the database's
sessions in and leaves the database. Each assistant message names its
call: request_id, generation_model (swe-2-high, effort and all),
created_at and metrics (input/output/cache read/cache write tokens,
ttft_ms, total_time_ms), written as two nodes per reply.

- sessions: calls_devin.go lists both stores (a session in both once,
  from the store written last), reads each session whole, one call per
  request_id (Msg devin:<id>), with the cwd. Registered in callSources
  and wholeCallReaders; Found lists "devin" for the consent page.
- provider: DevinModelEffort splits a variant id into model and effort
  (claude-haiku-5-5-low -> claude-haiku-5-5, low), so the catalog prices
  it. swe-2 has no catalog price and shows as unpriced.
- agentenv clears DEVIN_SESSIONS_DIR in test sandboxes.

Fixtures are the real runs' files: 3 sessions in sessions.sql (schema
verbatim, triggers dropped, assistant and user rows only), one session
only in the folder store and one in both, project folder renamed.

Run (mica): go test ./internal/sessions ./internal/provider
./internal/agentenv ./internal/usage ./internal/usageapi ./internal/cli
./internal/gui ok; go vet darwin, linux -tags nogui, windows on the
touched packages ok; gofmt clean. win-run: the Devin tests ok. A built
binary's `magpie usage all` / `--csv all` in a sandbox HOME holding the
real Devin data: 5 calls under Devin, the two claude-haiku-5-5 calls
priced from the catalog ($0.000277, $0.000986), swe-2 unpriced.

Broken by hand: devinCallFiles out of callSources (TestDevinCalls and
TestDevinDBReadAgain red, 0 calls); a session in both stores listed
twice (TestDevinSessionListedOnce red, 9 calls); the per-request dedupe
off (red, a request counted twice); DevinModelEffort returning the id
whole (TestDevinCalls and TestDevinModelEffort red).

Not tried: Devin's folder on Windows (taken as %APPDATA%\devin\cli, as
its credentials.toml; not seen on a real Windows install); a long real
session or subagents; DEVIN_SESSIONS_DIR set (read from the CLI's
behaviour in the sandbox, not from a GUI-started magpie's environment).
2026-11-13 12:26:43 +08:00
yetone e979553ba1 sessions: a start doesn't read Claude Code forks' uuids again to judge them (#2278)
Each start judged every group of Claude Code files that start alike
(ccFamily), then read what each copy or branch holds that its keeper
doesn't (ccRest). Both read every file's message uuids through
scanThin, and what they found was kept in memory only: ~0.2-0.25 s of
CPU on each start for a real history with forks, and a uuid set held
for each file.

What a group came to depends only on its files, so it is kept in
cc-families.json next to sessions.json, by a hash of each member's key,
path, size, change time, first and last message and start; a group none
of whose files changed is not read. A copy's or branch's rest is kept
in cc-rest.json by both files' path, size and change time, encoded the
way the parses are (encodeCache), so another time zone, cache version
or parser version reads it again. Both are written behind mu through a
temp file renamed over the last, in order; Saved and Reset wait for
them. Groups unused for 30 days are dropped.

Run (mote, at this tree):
- go test ./internal/sessions ./internal/usage ./internal/gui: ok
  (128 s, 64 s, 151 s); GOOS=windows and linux go vet
  ./internal/sessions: ok; gofmt clean.
- New TestClaudeFamilyKeptAcrossStarts: a start after one that judged
  the group reads no file's uuids, and a copy that went on with a turn
  is judged again (a branch). TestClaudeBranchRestKeptAcrossStarts: two
  starts count the same 80 tokens in and read no uuids.
- Broken by hand: ccFamilyKept always nil -> the first test red ("read
  the uuids of 3 files"); ccRestLoad never reading -> the second red
  ("start 0 read the uuids of 1 files"). Dropping size and mod from the
  group's hash left the first test green: the changed copy's last
  message changes the hash anyway; size and mod are there for a file
  rewritten in the middle.
- Real accounts (acctp sandbox, pprof of the first 40 s of a start with
  the page open): sessions.Warm 0.78/0.79 s -> 0.52/0.57 s, statsKept
  0.39/0.43 -> 0.18/0.21 s, ccFamily/ccUUIDsOf gone from the profile;
  pageheap: CPU at mark 2.84 -> 2.65 s, Footprint 132 -> 127 MB,
  liveHeap 80.2 -> 78.4 MB. The first start of the new build reads and
  writes them once (2.70 s at 40 s, as before).

Not tried: Windows and Linux real starts; the files are plain JSON in
the cache folder.
2026-11-13 11:18:30 +08:00
yetone c14fa0ce93 Bring back 919780414 and 88d2962e0, which 698ed4adb undid
698ed4adb (a busy port names its holder) was committed from a tree made
before 919780414 and 88d2962e0 landed (09:38, eight minutes before it),
and took both out with no word in its body: quotatable.js, the Usage
Cards / Table switch and its test, and sessions' 16-byte head and
prefix hashes (digest.go) were gone from main from v0.1.3823. This puts
both back as they were, on top of 698ed4adb's own change, which is kept.

Run at this tree, on mote (cherry-pick of both onto origin/main
db0c1b039, no conflicts):
- gofmt -l internal/sessions: clean.
- go vet ./internal/sessions ./internal/gui; GOOS=windows and
  GOOS=linux -tags nogui go vet ./internal/sessions: ok.
- go test -count=1 ./internal/sessions: ok 83.6s.
- go test -run 'Budget|Lazy|I18n' ./internal/gui: ok (the core script
  budget holds with both changes).
- GUI, chromium and webkit: usage-quota-table, gateway-port-holder,
  i18n-keys, i18n-en-no-cjk, old-webkit: 44 of 46. The two reds are
  old-webkit's "compat.js is the first" (headerpresets.js, #6030) and
  "the styles hold up in Safari 15.0" (#5919), red the same on an
  origin/main db0c1b039 copy.
Not run: the full Go and GUI suites.
2026-11-12 09:57:52 +08:00
yetone db0c1b039d sessions: a ZCode session the CLI database lacks is named from the app's task index (Flandern1211 on X)
Titles named a ZCode session only from files in the CLI database
(~/.zcode/cli/db/db.sqlite). A session the app keeps only in its own
tasks-index.sqlite (a request names it without the sess_ prefix) had no file,
so the Context page showed the id's first eight characters. Titles now asks
the task index for each ZCode key still unnamed, by sess_<bare id>, skipping
default titles. b0b995e08 covered only sessions that have a CLI row.

Run (mote): internal/sessions and internal/gui whole packages ok; gofmt clean;
go vet darwin, linux nogui, windows ok.
Broken by hand: the fallback removed -> TestZCodeTitleOfSessionOnlyTheAppKnows
red (empty title).
Not tried: a real ZCode on this machine (its CLI db is absent here; the index
has only two sessions); other agents' desktop indexes were not audited beyond
claude-desktop and PI-Desktop, which Titles already reads. Full suite not run
before the tag.
2026-11-12 09:50:58 +08:00
yetone 698ed4adb5 gateway: a busy port names the program holding it, and Tailscale's serve gets its fix (pluoki on X)
The Gateway page, `magpie serve` and the app log said only "port N is held by another program". pluoki's was `tailscale serve` on the same port number.

proc.PortHolder reads the holder (lsof on the Mac, /proc on Linux, Get-NetTCPConnection on Windows). Tailscale's daemon is root's and often unreadable, so `tailscale serve status --json` is the fallback for the port. gateway.NoteHeld / PortHeld.Sentence say who holds it, and for Tailscale give `tailscale serve --https=<other> http://127.0.0.1:<port>`. Shown in the `magpie serve` standby line and bind error, the app log, `gatewayHeld` in /api/state (Gateway page) and Start's "taken" answer, in en, zh, zh-TW, ja, de. A holder that can't be read says nothing; the old wording stands. Nothing is killed or touched.

Run: gofmt clean; go vet darwin, linux nogui, windows (mica); go test ./internal/proc ok; targeted holder/gateway tests on macOS (mica), Windows (win-run) and Linux (wsl-run); parser tests with real lsof output; GUI gateway-port-holder, gateway-takeover, gateway-older, gateway-skew, gateway-port, i18n-keys, i18n-en-no-cjk in chromium and webkit. Real run on WSL: a holder named tailscaled on the LAN address with magpie on 0.0.0.0 gives the Tailscale sentence at the bind error; a Python holder on loopback gives "held by python3.12 (pid N)".
Broken by hand: each fix reverted in turn, its test went red.
gateway-card.test.cjs is red on origin/main too (#6029). internal/gateway, gui and cli package runs were still going at push; the full suite follows the tag.
Not tried: a real `tailscale serve` (changes live config), a real Windows holder end to end, the bind-error path on macOS (a wildcard bind coexists with a specific one there).
2026-11-12 09:46:34 +08:00
yetone 88d2962e0c sessions: a file's head and prefix hashes are kept as 16 bytes, not hex (#2278)
Each kept file's state held its head hash as 64 hex characters and its
sampled prefix hash as "sample-v1:" and 64 more, two allocations of 64
and 80 bytes beside the state. They are only compared, so they are now
a digest: the first 16 bytes of the same SHA-256, inline in the state's
own 16 bytes where each string header was. The state's size class is
unchanged (416), and the 144 bytes a file are gone.

A cache written before reads as the same files: digest reads the old
hex (with or without "sample-v1:") as its first 32 characters, which
are what headDigest and prefixHash give now, so the first start after
the update reads nothing again. The call shards' gob keeps its string
fields, written and read through the digest, so a shard written before
restores the same too. File names still use hashHead's full hex.

Run, on a sandbox HOME holding the owner's real account history (18,346
session files), the same sessions.json before each run, web mode, at
120 s:
- w14 (main): live heap 88.8 MB, footprint 129 MB, 127 MB after GC,
  CPU 2.35 s
- w15 (this): live heap 86.1 MB, footprint 124 MB, 121 MB after GC,
  CPU 2.48 s; at 30 s 2.31 s of CPU against 2.15 s, so no file was read
  again from the old cache
Broken by hand: digest no longer stripping "sample-v1:" turns
TestDigestReadsTheHashesWrittenBefore and
TestPrefixHashUnchangedAndUnbuffered red.
At the pushed head (rebased on 848269fcf): gofmt clean, go vet for darwin,
windows and linux (nogui) ok, go test ./internal/sessions/ ./internal/usage/
ok on mica. The full suite runs after the push (both test boxes were
loaded).
2026-11-12 09:41:52 +08:00
yetone 67d2df72d9 sessions: a range's stats are aliased once, as made, and kept aliased (#2278)
With any model alias set, every Stats read copied each kept range's
days and every session's summary into a second, aliased Stats, and kept
that copy (aliasedKept) beside the unaliased one. With a long history
(~14k sessions) the copy held ~5 MB of summaries for as long as the
kept ranges lived.

Now statsKept aliases a range's Stats in place right after
statsOfRange made it (aliasOwned: only st's own Days and Sessions
arrays are written; the usage, model and effort slices are replaced,
never written into) and keeps that one. keptStats carries the alias
names it was made under, so a changed alias makes the ranges again,
as a changed price or title already did. aliasedKept, aliasKept and
aliasStats are gone.

Tests: TestSessionsCountAliasedModelsAsOne now checks that the kept
range's summaries are the very ones the read returned. Broken by hand
(a copy of Sessions before keeping): it went red ("an aliased read
keeps a copy of its summaries beside the kept ones"), and so did
alias_kept_test's "range 0 named again with nothing changed".
TestAliasOwnedLeavesSharedSlicesAlone replaces
TestAliasStatsLeavesItsInputAlone.

Run at 846cc2b9b (rebased on 96c65e3e7), on mica: gofmt -l clean; go vet,
GOOS=windows go vet and GOOS=linux go vet -tags nogui ./... ok;
go test -timeout 45m -count=1 ./...: 97 packages ok, none failed.

Real account (mote, sandbox HOME with the owner's history and an alias
set), late.sh at 120s, v0.1.3814 vs this: footprint 127 → 124 MB, live
heap after GC 100.8 → 95.9 MB; aliasStats' 5.01 MB is gone from the
profile.

Not tried: Windows and Linux runs of the package (no OS-specific code).
2026-11-12 08:39:44 +08:00
yetone 040debfb1e sessions: the kept parses' file is mapped, not read onto the heap (#2278)
A start read sessions.json whole onto the heap (24.6 MB on a real
history) and decoded it; then each `named` object was copied again by
gjson.ParseBytes before being read. Nothing decoded keeps a byte of
the file: json.Unmarshal, ccStr and unique.Make all copy, and the keys
are cloned.

On unix the file is now mapped read-only and unmapped once decoded (it
is only replaced by a rename, never written in place); elsewhere it is
read as before. `named` parses its bytes in place.

Run:
- go test ./internal/sessions (mica): ok 63s.
- GOOS=darwin/linux/windows go vet ./internal/sessions: ok.
- Broken by hand: read onto the heap again, TestCacheFileReadWithoutACopy
  is red ("allocates 688976 bytes; want it mapped"); a key left
  pointing into the file (no Clone) faults it with SIGSEGV after the
  unmap. The fixture has plain and escaped names, since an escaped one
  is unescaped into a copy anyway.
- Every custom UnmarshalJSON in internal/sessions read for bytes it
  keeps: none.
- Real account, mote sandbox HOME, start to 50s (pprof alloc_space):
  sessions.loadCache 29.5 MB -> 4.4 MB, os.readFileContents 46.7 MB ->
  22.0 MB. Footprint peak unchanged (163 to 164 MB); it is set later.

Not tried: a real Linux start; Windows reads the file as before.
2026-11-12 07:40:42 +08:00
yetone 152734cd12 dirent: one probe vouches for every folder a poll watches (#2278)
A Sessions poll watched each Codex day folder and each Claude Code
project folder through dirent.Watch, and every call ran its own sync1
probe (a mkdir, an unlink and a wait for the write to be heard). On a
real history that was ~130ms of 1.47s CPU per 40 polls, and the
syscalls around it more. WatchSince(dir, mark) skips the probe when a
probe begun after mark was heard; sessions takes the mark when a hold
begins, so one poll makes one probe. A folder watched for the first
time still probes, since its watch hears only what comes after.

Run, real account (mote, the owner's Claude Code and Codex history,
40 back-to-back /api/sessions polls, sandbox HOME):
- CPU: w10 1.47s -> w11 0.54s; under sync1: 130ms -> 10ms.
- Allocated: 25.98 MB -> 25.08 MB.
Tests (mica): go test ./internal/dirent ./internal/sessions ok at the
pushed head. TestWatchesFromOneMarkProbeOnce is red with covered
forced false ("round 0: 3 probes from one mark") and green on this.
./internal/gui: TestPanelHiddenByWailsMarksPageOutOfSight fails under
-count=3 on an origin/main copy (4ae833f84) too and passes -count=1;
recorded on #6203.
2026-11-12 06:29:11 +08:00
yetone 390341f9ed appdir: the homes look tells folders apart by inode, not EvalSymlinks (#2278)
ClaudeHomesIn and CodexHomesIn run on every Sessions poll, and keyed
each folder they found by filepath.EvalSymlinks, which Lstats every part
of the name: ~3 MB of garbage per 40 polls on a real home. On unix a
folder is now keyed by its device and inode, which a link to it shares;
a folder that can't be looked at is keyed by its name, and other systems
keep EvalSymlinks. The folder checks use DirStat, moved here from
internal/sessions so both share one.

Run (mica, at this tree): go vet for darwin and windows of appdir,
sessions, provider and gui, for linux of the first three (gui needs cgo
there); GOOS=freebsd go build; go test ./internal/appdir ./internal/sessions
./internal/provider ok. TestHomesLookAllocatesLittle: 55 and 68
allocations a look now, 387 and 400 on the old code, which fails it.

Real account (mote, 40 polls of /api/sessions): w9 31.28 MB allocated
with os.lstatNolog 3 MB; w10 25.98 MB, lstat gone from the top list.
CPU over 30s 1.47s, within noise of w8's 1.29s at mote's load.
2026-11-12 05:44:12 +08:00
yetone f8248ccd70 sessions: an unchanged folder's look allocates nothing (#2278)
readDirectory looked at each folder with os.Stat on every Sessions poll
to see whether its cached listing still held. os.Stat builds a FileInfo
and a name each time, ~6 MB per 40 polls on a real history. dirStat reads
the same mod time, size and kind with unix.Stat into a stack Stat_t;
other systems keep os.Stat.

Run (mica, at this tree): go vet ./internal/sessions for darwin, linux,
windows; GOOS=freebsd go build ./internal/sessions; go test ./internal/sessions
ok (61.8s). TestDirStatAsOSStat passes; with the old discovery.go it fails
("an unchanged folder's look allocated 2 times").

Real account (mote, 40 polls of /api/sessions): w8 34.16 MB allocated,
os.statNolog 6 MB; w9 31.28 MB, os.statNolog not in the top list.
2026-11-12 05:36:00 +08:00
yetone 10c3315312 sessions: an unchanged listing is the last one, not a new list (#2278)
Every 15 s Sessions poll built every Claude Code file's and Codex
rollout's list again, and merged and filtered them into more new
lists, while nothing on disk had changed. On the owner's real history
that was ~120 MB of garbage per 40 polls in listedRollouts,
claudeFiles, listCCFiles and filesKept.

Each lister now keeps its last list (listsKept). A listing walks the
folders as before and compares each file with the kept list's file at
the same place; while they match nothing is allocated, and the kept
list itself is returned. On the first difference it copies the matched
part and goes on, so a grown, new or gone file is listed as a fresh
listing has it, and the kept list is never written. listCCFiles reuses
its walk's scratch slice per lister. distinctPaths and
distinctCodexFiles return their input when nothing is dropped and never
filter in place; codexFilesIn's twin filter clones before deleting.
rolloutsSeen's day entry is its part of the kept list (clipped), not a
clone. The idle cache drop forgets all of it.

Measured on mote with the owner's real account (75 GB history),
40 /api/sessions polls, `magpie heap` before and after, alloc_space
diff:
  before (w6): 155.7 MB; listedRollouts 42.8, claudeFiles 32.2 (71.1
  cum), listCCFiles 31.0, filesKept.distinct 18.0
  after  (w7):  34.8 MB; none of the listers in the top; distinct 4.5,
  provider.All 9.7 (next)
CPU over 30 s of polling: 1.79 s -> 1.37 s.

Tests: lists_kept_test.go, red on the old code (an unchanged listing
made a list of its own; distinctPaths wrote its input), green now.
TestClaudeFilesMadeAtTheirSize expects the clipped kept list.
Run on mica at this tree (rebased on 0cff3429f, sessions vet + test again ok): go vet ./internal/sessions for darwin, linux
and windows, ./internal/gui for darwin; go test ./internal/sessions ok
(64 s); go test ./internal/gui ok but TestPanelHiddenByWailsMarksPageOutOfSight
(#6203, flaky on mica, passes alone). -race of sessions: #4360 and
#6213, both red on the old code too, no stack in the changed code.
Not tried: Windows and Linux runs of the new test (the codex subtest is
darwin-only).
2026-11-12 04:52:19 +08:00
yetone facc092d00 sessions: a ZCode name poll stamps a copy, not the kept file list
v0.1.3800 (729be88e1) has allFilesForTitles give back the list it keeps
from poll to poll, and other polls read it meanwhile. Titles then
wrote each asked ZCode session's message count and time into that list
in place (zcodeTitleStamps): a data race with any poll reading it, and
the kept list no longer matched the rows, so it was made again on the
next pass. The stamps now go in a copy made at the first one that
changes a file; a poll with nothing to stamp copies nothing.

Audited the other users of allFiles/allFilesForTitles and the
in-place writes in internal/sessions (&files[i], .w(), sort.Slice):
the rest write into lists of their own (byKey copies, traceLineFiles
concatenates, callSources goes through distinctOf).

Run (mica): go test -count=1 -timeout 45m ./internal/sessions/ ok;
go test -race -count=3 -run 'TestZCode|TestFilesKept|Titles' ok; vet
ok; gofmt clean. Broken by hand: stamping in place again makes
TestZCodeTitleStampsLeaveKeptListAlone red ("the kept list was
stamped in place: size 1, mod 1790496500000").
Not run: the full ./... and GUI suites (one package touched).
2026-11-12 02:44:19 +08:00
yetone 0b4b249e54 sessions: an unchanged Sessions poll keeps the last file list
Every 15 s poll made the whole deduped file list again (~1.5 MB on a
real history, distinctOf's 58 MB over 40 polls). allFiles and
allFilesForTitles now compare each pass with the last list, held
weakly so a magpie with the page shut keeps none of it, and give the
same array back while nothing differs. A changed or gone file makes a
new list; the old one is never written into (cap == len). An empty
pass is an empty slice, never nil: refresh reads nil as "not listed"
and kept the parses of deleted files (TestGoneAgentLeavesNoSession
went red on the first try, caught before commit).

Run (mica): go test -count=1 -timeout 45m ./internal/sessions/
./internal/dirent/ ok; go vet of both ok; gofmt clean.
Broken by hand: the nil return makes TestFilesKeptWhileTheSame ("an
empty pass: nil") and TestGoneAgentLeavesNoSession ("5 parses kept")
red; a fresh slice on every pass makes TestFilesKeptWhileTheSame red.
Real account on mote, 40 unchanged /api/sessions polls, alloc_space:
179.5 MB (v0.1.3794 build) -> 147.9 MB; distinctOf gone, the kept
list's own compare 12 MB. /api/sessions body sha identical on both.
Not run: the full ./... suite (mote over its cores; this touches the
sessions package only) and the GUI suite.
2026-11-12 02:30:15 +08:00