Commit Graph
335 Commits
Author SHA1 Message Date
yetone d7978141bb sessions: WSL sessions go when the last agent in a distro is uninstalled (_SekiBetu_ on X)
wslList kept every distro's listing, cold, whenever WSLHomes named no
distro. That is also what it names once the last agent in WSL is taken away,
so the sessions of a removed agent stayed listed for good, unopenable and
undeletable. internal/agent now says whether wsl.exe answered the list of
distros (sessions.WSLListed); an answer with no distro an agent is in drops
the listings, no answer keeps them as before.

Run (win-run, xiaomi-gpu; mote refused SSH all session): the new
TestWSLAgentsGoneListingDrops and TestGoneAgentLeavesNoSession (native
Claude and Codex folders deleted: nothing listed, no parse kept; green on
the old code, so macOS/Linux/Windows native lists were already right),
go test ./internal/sessions ./internal/agent, go vet on both.
Broken by hand: with the WSLListed check turned off the new test is red
(7 sessions listed after the agents were taken away).
Not tried: a real WSL distro with a real uninstall; GUI; full suite.
2026-11-11 12:22:45 +08:00
yetone 28ac12bc90 sessions: a pass's prices build the providers once, not once a model
A model's price looks its provider up among every provider
(BasePriceIn → byIDOrWas → All), and with nothing held each look built
every provider again from their files and accounts. keptStill checks
every kept price on each 10 s refresh of the Sessions page, so this was
the largest allocator left there: provider.All 59 MB cumulative, 40.5 MB
of it from sessions.priceOf, in 4 minutes. pricer now holds the
providers for a price it hasn't seen, and what a hold built stays for
heldFor (1 s) after it, so the rest of the pass reuses it.

Run:
- TestPricerBuildsTheProvidersOnce (new) counts provider.AllBuilt
  across six models priced with the real priceOf. Fixed: pass. Broken
  by hand (Hold removed, in a copy): "built every provider 6 times".
- mote: go test ./internal/sessions ./internal/provider
  ./internal/usage ./internal/gui ok; GOOS=windows go vet and GOOS=linux
  go vet -tags nogui ./internal/sessions clean; gofmt clean.
- Real accounts (mote, sandbox HOME copy, ad4.sh: /api/sessions/stats
  for days 0, 7 and 30 every 10 s with X-Magpie-Had, heap at 120 s and
  360 s): total allocated in the 4 minutes 294.3 MB (t68) → 210.1 MB
  (t69); provider.All cum 59.3 → 18.3 MB, allProviders 50.6 → 11.7 MB,
  sessions.priceOf 41.1 → 14.2 MB.

Not tried: Windows and Linux runs of the package (vet only).
2026-11-11 10:03:28 +08:00
yetone 71a68639b0 sessions: every Claude folder's files are listed into a slice made at their size
With more than one Claude folder (CLAUDE_CONFIG_DIR per account),
claudeFiles appended each folder's files to a slice grown file by file.
It runs on every pass over the session files, and the Sessions page's
ranges are refreshed every 10 s, so on the owner's real history it was
the largest single allocation of that refresh. The folders are listed
first now, and the answer made once at their total; with no Claude
folder the answer is nil, as before.

Run: TestClaudeFilesMadeAtTheirSize (new) passes; on the old code it
fails ("listed into room for 76, want the 41 listed"). go test
./internal/sessions ./internal/gui and go vet (darwin, GOOS=windows,
GOOS=linux -tags nogui) ok at 9cd4ef6a1 plus this change. Real account
(mote, ~/r2278/acct, /api/sessions/stats polled every 10 s for days 0,
7 and 30 with X-Magpie-Had, as the page does; 4 minutes of
alloc_space diffed): claudeFiles 41.7 MB flat / 57.5 MB cum before,
17.7 / 39.6 MB after.
2026-11-11 09:47:02 +08:00
yetone 9cd4ef6a19 sessions: an aliased range is named once per change, not on every 10 s read
While the Sessions page is open, the GUI reads the 7, 30 and all-days
ranges again every 10 s. Those ranges are kept (keptStats), so a read
with nothing changed costs almost nothing, except when a model is
counted under another name (a usage alias, or a shared group's spelled
name). Then aliasStats copied every day's usage and every session's
summary of each range on each read: ~5 MB a read for the owner's real
history, which was then thrown away because nothing had changed.

aliasKept keeps each range's aliased Stats with the kept Stats it came
from and the names (provider.UsageNamesKey). When the kept Stats are the
same slices and the names haven't changed, it returns the same answer.
Kept Stats are never written, and MergeExternalStats copies before it
writes, so the answer can be shared. The memo is dropped with the kept
ranges (forgetKeptStats), so it never outlives them. UsageAliasKeyed
reads settings once for both the alias and its key.

Run: TestAliasedRangeMadeOncePerNames (new) passes. With the memo
skipped it fails at "named again with nothing changed". With the key
and source check removed it fails at "the old names' range given after
the names changed". go test ./internal/sessions ./internal/provider
./internal/gui and GOOS=windows / GOOS=linux -tags nogui vet: ok at
328dc97e2 plus this change.
Real account (mote, ~/r2278/acct, /api/sessions/stats polled every 10 s
for days 0, 7 and 30, 4 minutes of
alloc_space diffed): aliasStats 75.1 MB before (v0.1.3664 build), not
in the profile after; everything allocated 519.7 -> 467.3 MB. Not
tried: Windows and Linux runs (nothing here is per OS).
2026-11-11 09:30:53 +08:00
yetone 58e541faa9 sessions: a session file whose stat fails for any reason but absence keeps its last size and time (@simonzyzy on X) 2026-11-11 09:04:52 +08:00
yetone e12244aca4 sessions: a folder that can't be read keeps its last listing, not none (@simonzyzy on X)
readDirectory took a failed stat or listing of a project folder as an
empty folder. A refusal that passes (too many files open under a long
history's parse, a sharing violation, a stalled network home) took every
session in the folder off the Sessions page, and refresh let go their
parses with them; a later poll read the folder again and parsed them
anew, so sessions vanished and came back. A failed read is unknown: the
last good listing stands. A folder that is gone still lists as none.

Run (mote-run): TestUnreadableDirectoryKeepsItsLastListing red on the
old code (listed 0 entries, want its last 2), green with the change;
go test ./internal/sessions ok; gofmt clean; go vet on darwin, linux
nogui and windows for internal/sessions clean.
Not tried: the full suite before the tag (started after it); a real
EMFILE; a per-file stat that fails for a moment (statFiles still drops
that one file, filed in the report as open).
2026-11-11 08:44:55 +08:00
yetone bf0a1252fa codex: the chat open in the Codex app follows a provider switch (hubo31377762 on X)
Switching Codex between magpie and OpenAI left the chat that was open
unusable. The Codex app holds the writer lock of every chat it has loaded, so
no move touched that chat's row, and Codex 0.167 refuses to resume a chat whose
provider isn't the configured one (modelProviderMismatch openai to magpie,
modelProviderNotConfigured magpie to openai). Reopening it did not help.

Just before magpie ends the Codex app's app-server for the route change, the
held chats are now moved to the provider Codex is on: a paginated one by its
row, a legacy plain rollout in place at equal id length (openai and magpie),
packed legacy rollouts and other lengths left to the next sync
(provider.CodexBeforeAppEnd, agent.codexRetagOpenThreads,
sessions.RetagLoadedCodexThreads). The end is a clean SIGTERM and Codex writes
nothing back.

Run (mote-run): gofmt -l on the three packages; go vet for darwin, windows and
linux with nogui over ./internal/...; go test internal/sessions, provider and
agent. Real codex 0.167.1 app-server in a sandbox CODEX_HOME, both ways: no
retag gives modelProviderMismatch (openai to magpie) and
modelProviderNotConfigured (magpie to openai); with the row retagged and the
app-server SIGTERMed, thread/resume succeeds on the new provider in both.

Broken by hand: the hook call removed and the retag call emptied; both new
tests go red (open chat stays on the old provider, order is [end] only).

Not tried: the Codex app GUI itself, Windows runs, a packed legacy thread held
open (left to the next sync). A resumed thread's sandbox falling back to
config.toml's default happens with no provider change and is #6028.
2026-11-11 07:33:20 +08:00
yetone 26d1c5619a sessions: every Claude Code folder is read, not only one (@fivesmallq on X)
Accounts run with their own CLAUDE_CONFIG_DIR (~/.claude-work beside
~/.claude) had only one folder's sessions and token use counted. Claude
folders are now found as Codex's are (appdir.ClaudeHomes): the one in use,
siblings named claude*/.claude* (or one level down) that hold projects/, and
the folders of Claude accounts saved in magpie. The sessions list, calls
(Usage), traces, the read-permission check, Dirs and a deleted session's
companion folders (file-history etc., taken from the session's own folder)
all go through it. A session id in two folders is kept once.

No setting to add folders by hand and no GUI change: discovery needs no
configuration; a folder with another name is not found.

Run (mote): go test appdir, sessions, cli, usage ok; gofmt clean; go vet on
darwin, linux and windows for appdir and sessions. New tests
(TestClaudeHomesIn, TestCallsReadEveryClaudeFolder,
TestListReadsEveryClaudeFolderOnce) fail on the old code for the second
folder's sessions. Broke by hand: dropping the key dedupe in claudeFiles
still passes, since the list and calls dedupe by key later; it is kept as a
guard, not tested alone.
Not tried: real second Claude account, Windows/WSL, GUI.
2026-11-11 07:24:28 +08:00
yetone 0bb991b0da sessions: Claude Code's copied-session ids are kept as 16 bytes, and folder listings go with the idle parses
On a real history (~15k Claude Code sessions), the idle heap after one
visit to the Sessions page still held two things:

- ccUUIDMemo's set of message uuids per file, as map[string]bool with
  the strings gjson copied out: ~5.1 MB. It is now a uuidSet,
  map[[16]byte]struct{}: an 8-4-4-4-12 uuid (any case) is parsed into
  its 16 bytes, anything else is hashed with FNV-128a.
- ccListed, every Claude Code folder's last listing (path and key per
  file): ~2 MB, kept for the life of the process. dropIdleCache now
  clears it with the other memos it lets go; the next listing builds it
  again from the folder.

Run on mote (go1.26.8):
- go test -count=1 ./internal/catalog ./internal/sessions
  ./internal/provider ./internal/agent ./internal/codexcat: ok
  (before the ccListed line); ./internal/sessions again after: ok.
- gofmt -l, go vet and GOOS=windows go vet for internal/sessions: clean.
- Broken by hand: with ccListed.Clear() commented out,
  TestIdleParsesLetGoAndComeBackFromDisk fails ("3 Claude Code
  listings kept").

Not tried: the real-account idle measurement of this change alone; it
runs with the catalog change's measurement.
2026-11-11 05:58:14 +08:00
yetone ccc96b4a73 sessions: Codex's identities, rollout listings and folder listings go with the idle parses
When nobody has read the session parses for three minutes they are let
go (v0.1.3540), but the end heap of a real history still held ~10 MB made
from them or from the folders, kept for the life of the process:

- Codex's thread identities (codexIdentityMemo, ~3.5 MB);
- each Codex day folder's rollouts as last listed (rolloutsSeen, ~1.5 MB);
- every folder's listing given back to dirent (~4 MB of names and
  entries).

dropIdleCache now lets them go too, and dirent.Forget empties the kept
listings. Each is made again on the next read, from the parses and the
folders, with no session file parsed. CC's per-file UUIDs (ccUUIDMemo)
stay: letting them go would read every Claude Code file again.

Run:
- mote (macOS): go test ./internal/sessions ./internal/dirent
  ./internal/gui ./internal/usage ok; GOOS=linux and windows go vet ok.
- Broken by hand (the three drops and Forget's body removed): red, "idle:
  1 Codex identity lists and 2 folders' rollouts kept" and "9 kept after
  Forget". On Linux dirent.Stats lists nothing, so the test asks for
  rollouts kept before the drop only on macOS.
- Real accounts (a copy of the owner's history on mote, 300 s each, the
  web app opened cold, order t53 t54 t54 t53): idle footprint 117 / 120 MB
  before, 103 / 85 MB after; end heap 53.3 / 50.9 MB before, 43.4 /
  44.6 MB after. Peak unchanged (it is the start).

Not tried: Windows and Linux at runtime (the change is the same code).
2026-11-10 18:52:36 +08:00
yetoneandNorethSea 4921bf5a97 usage, sessions: one model option for a found routing group's two ids (#5892, Norethcy on X)
A found routing group is called by its public id (auto/<model>) and is
kept as group/auto-<slug>; calls recorded under either were counted as two
models, so Usage › Sessions' model filter listed the same group twice and
the ledger, summaries and session lists split its calls.

Ported from NorethSea's 30d6261cd on their fork: UsageAlias names a found
group by its public id before the user's alias (both spellings, old
session files too), sessions' lists, the ledger keyer, the summary cache's
key and Codex's model/effort read through it, and a cache keyed on the
group names (UsageNamesKey) is read again when a group is renamed. A user's
own provider named "auto" keeps auto/<model> (autoRefsOn).

Changed in review: the patch's ledger filter compared every record with
provider.SameRef, which reads the providers (customIDs, a stat of
providers.json) for each record a filter passes over. FilterOf, the one
place a Filter is made from a query, now canonicalizes the model once, and
keepsRecord asks the providers only for an auto/ record under a group/
filter (sameGroupModel).

Run (mote's sshd reset every connection all afternoon, so on the Linux box
through wsl-run; the package run at base 720200092, and the -run tests,
quota-holds and i18n-keys again at this head on 208b89422; rebased since onto 44732325e,
a gateway test only):
- go test -count=1 -tags nogui ./internal/gui ./internal/provider
  ./internal/sessions ./internal/usage ./internal/usageapi: ok
- go vet -tags nogui (linux), GOOS=darwin CGO_ENABLED=0 go vet (provider,
  usage, usageapi, sessions), and go vet on Windows (win-run, those and
  internal/gui): clean. gofmt -l: clean.
- GUI: usage-ledger-model-pick, usage-ledger, quota-fit-batched,
  i18n-keys in chromium and webkit. usage-ledger's "newest live route
  needs no return-to-live button" (and zh "request routing links") is red
  the same on origin/main 987eac0aa on that box: #3104, #4078.

Broken by hand:
- keepsRecord back to r.Model != f.Model: TestUsageFoundGroupNames and
  TestLedgerFoundGroupNames red.
- usageGroupNames returning nothing: TestUsageFoundGroupNames (provider,
  usage), TestSessionsFoundGroupNames, TestCodexEffortFoundGroupNames,
  TestLedgerFoundGroupNames red.

Not tried: a macOS run (mote unreachable), the darwin gui package's vet,
and the reporter's own usage log.

Co-authored-by: NorethSea <963979204@qq.com>
2026-11-10 18:01:13 +08:00
yetone 710a290e26 sessions: every session file's parse is let go three minutes after its last read
The parses of every session file (the sessions index, kept on disk as
sessions.json) stayed in memory for the life of the process after one
visit to the Sessions or Usage page, or the start's warm-up: ~23.5 MB of
a 68 MB idle heap for a real history of 24.6 MB on disk. Now, once
nothing has read them for cacheIdle (3 min), they are let go and the next
read loads them from sessions.json, with no session file read again.

They stay while a refresh is reading files, while glances are overlaid,
while a save is not on disk yet (it is hurried first), and when the last
save failed (writeCache now records that), so a let-go never means
parsing a long history again.

Measured on mote (macOS) with a copy of the real accounts, idle, no
asks, 330 s, t51 = origin/main before this, t52 = this:
  footprint at the end  111 MB -> 96-100 MB
  Go heap at the end    68.05 MB -> 46.15 MB (decodeCache's 23.5 MB -> 0)
Reads after 200 s idle (t52 had let go; t51 had not):
  /api/sessions          0.28 s -> 0.54 s
  /api/sessions/stats    0.19 s -> 0.36 s
  process CPU over the run 4.03 s -> 4.40 s
A warm read is unchanged (0.24 s / 0.01 s).

Run: go vet ./internal/sessions (darwin; windows and linux with
CGO_ENABLED=0); go test ./internal/sessions ./internal/gui
./internal/usage on mote, all ok. TestIdleParsesLetGoAndComeBackFromDisk
broken by hand twice: dropping the failed-save guard (red: "let go while
the last save had failed") and not clearing the cache (red: "idle parses
kept"). Not run: the full suite; Windows and Linux runs of the package.
2026-11-10 15:46:24 +08:00
yetone e7fe52fdc3 minimax: follow the data folder MiniMax Code Desktop moved, not ~/.minimax (YujunT46308 on X)
YujunT46308 on X (magpie 0.1.3519, MiniMax Code 3.1.13 CN): with the
app's data folder moved to another parent (localRuntimeDataParentDir),
magpie went on writing ~/.minimax/config.yaml, which the app no longer
reads.

How MiniMax Code 3.1.13 finds it, read from its own app.asar
(dist/main/modules/local-runtime/data-dir.js,
resolveLocalRuntimeDataDirSelection; @mavis/config's config.js for the
runtime): MINIMAX_DATA_DIR, then MAVIS_DATA_DIR, then the desktop
setting, then ~/.minimax. Settings' data-folder move keeps the parent as
config.localRuntimeDataParentDir in its electron-store file
(storage.ipc.js: minimax-agent-cn-config.json for the China build,
minimax-agent-config.json for the global one) in Electron userData,
named by app-identity.js: "MiniMax" (CN) / "MiniMax Agent". The data
folder is <parent>/.minimax.

What changed:
- appdir.MiniMaxDirIn resolves the folder in that order, reading the
  store under ~/Library/Application Support on a Mac and %APPDATA% on
  Windows. A missing, unreadable or unparseable store, or a parent that
  isn't an absolute string, is ~/.minimax, as electron-store itself
  reads a file it can't parse as its defaults.
- internal/agent's MiniMaxDir (detection, connect, restore, Sync, Check)
  and internal/sessions' MiniMaxDir (Usage's calls) both use it; the
  Library's skills follow a.Dir. WSL's mcode still uses the distro's
  ~/.minimax (no desktop app there).
- MAVIS_DATA_DIR joins agentenv's variables, so tests sandbox it.
- agent-wiring.md and reference.md say where the folder comes from.

Run:
- On mote, the real MiniMax Code 3.1.13 CN arm64 dmg: launched with no
  setting, userData was ~/Library/Application Support/MiniMax holding
  minimax-agent-cn-config.json; with config.localRuntimeDataParentDir
  set to a folder, the next launch created <parent>/.minimax/config.yaml.
  appdir.MiniMaxDir() against that real store printed <parent>/.minimax.
  (The test data I made on mote was removed after.)
- mote-run go test -count=1 ./internal/appdir ./internal/agentenv
  ./internal/sessions ./internal/library: ok. ./internal/agent -run
  'MiniMax|Minimax|WSL|Env|Spelled|Handwired': ok.
- win-run go test -run MiniMax ./internal/appdir ./internal/agent
  ./internal/sessions: ok, TestMiniMaxDirIn and
  TestMiniMaxCodeMovedByDesktop ran (not skipped) with %APPDATA% paths.
- gofmt -l clean; go vet of the touched packages for darwin, windows
  and linux (nogui, CGO off) ok.

Broken by hand: with the desktop store read turned off,
TestMiniMaxDirIn and TestMiniMaxCodeMovedByDesktop go red (the folder
reads as ~/.minimax).

Not tried: the Windows desktop app itself (userData %APPDATA%\MiniMax
is Electron's appData plus the app name, the same rule seen on the
Mac); the global build's store with a real install; a store mid-rollback
(the app's guard writes the restored parent back to the same key on its
next launch). A user who also runs the mcode CLI without
MINIMAX_DATA_DIR has it on ~/.minimax, which magpie now leaves alone
while the desktop folder is moved.
2026-11-10 14:43:44 +08:00
yetone 53280aa08e sessions: the stats caches are let go two minutes after the page stops asking
The Sessions page polls /api/sessions/stats every 15 s. Each range it asked
for kept its Stats, the overview and tag sums, about 15 MB on a 14k-session
history, for as long as magpie ran, with the window closed too. Now a timer
armed on every ask drops them two minutes after the last one (not while a
read is busy), with the sessions package's kept ranges, then returns the
memory to the OS. The parsed files stay, so asking again sums them up
again without reading a file.

Measured on mote with a copy of the real accounts (14k sessions), the
statsIdle delay set to 20 s in a measuring build only:
- footprint after six stats asks: t47 (origin/main) 140 MB, t48 151 MB;
- 45 s later: t47 130 MB, t48 116 MB;
- asking again after the release: days=0 0.34 s (was 0.06 s while kept),
  days=30 0.17 s.

Run on mote: go vet ./internal/gui ./internal/sessions; go test
./internal/gui ./internal/sessions ok. TestIdleStatsLetGo is red with
`statsMemo.m = nil` taken out ("2 ranges ... kept; want none").
The timer is off under go test, so other gui tests keep their memos.
Not tried: the GUI page itself; the full suite.
2026-11-10 13:58:41 +08:00
yetone e4197144a8 perf: every package's package-level regexps compile on first use
v0.1.3516 made gateway's and redact's patterns lazy. The other 299
package-level regexp.MustCompile calls, in 148 files across agent,
provider, gui, library, codexcat, sessions, usage, plugin and the rest,
now go through lazyre.New too, so a launch that never reaches them
(`magpie statusline`, run by Claude Code on every message) doesn't
compile them. Fields, maps and params that held them are *lazyre.RE.

Measured on mote (M5 Pro), sandbox HOME, v0.1.3516-equivalent build
(t42) against this one (t43):
- GODEBUG=inittrace=1 sum: 7.39 MB / 69,837 allocs -> 4.62 MB / 46,765
- `magpie statusline`, 3 runs each: instructions retired ~212M -> ~176M,
  peak memory footprint 19.2-19.4 MB -> 16.8-17.0 MB

Run: go vet ./... (darwin) ok; GOOS=windows go vet on each of the 30
changed packages ok; GOOS=linux go vet ok except ., internal/cli and
internal/gui, which stop in wails v3's cgo files when cross-compiled
(the same at main). New TestAllLazyPatternsCompile at the root compiles
all 574 registered patterns (ok), so a bad pattern fails a test rather
than a first use.
Not run before push: the changed packages' own test suites; they run
on mote after it.
2026-11-10 12:54:39 +08:00
yetone 1cfea01695 sessions: Codex's per-poll name and twin sets are kept from poll to poll (#2278)
Each Sessions poll lists every Codex rollout (~13k here) and made two
maps over them anew: distinctCodexFiles' first file of each name, and
codexFilesIn's set of plain rollouts a compressed twin defers to. Both
are now taken from a shelf, as pathSets are, and given back cleared;
the shelf lets them go after it idles.

Run on mote (M5 Pro, macOS 27), with a copy of the real accounts:
- go vet ./internal/sessions; go test ./internal/sessions: ok.
- TestDistinctCodexFilesKeepsItsSet (new): a call over 4,000 rollouts
  makes at most 4 allocations. Broken by hand (a new map each call): 47,
  red. The twin set has no test of its own; it uses pathSet as is.
- /api/sessions and /api/sessions/stats?days=30 from a fresh start, real
  history: byte-identical to v0.1.3503's code.
- 40 /api/sessions polls with X-Magpie-Had: 185.5 MB allocated before,
  152.4 MB with this; distinctCodexFiles is gone from the profile.
2026-11-10 11:18:14 +08:00
yetone 7c0a103eb1 sessions: a file's modification time is unix nanoseconds, 80 bytes a file (#2278)
A Sessions poll copies every session file's `file` into several slices
(distinctOf, listedRollouts, listCCFiles, distinctCodexFiles), and
rolloutsSeen keeps one of every Codex rollout. Its time.Time was 24 of
its 96 bytes. mod is now a modTime (int64 nanoseconds, 0 for none) with
the few methods the package used; a time.Time going in is modOf(t), one
coming out is .Time(). UnixNano keeps the zero time's own value, so a
parse kept on disk for a file with no time still matches.

Run on mote (M5 Pro, macOS 27), with a copy of the real accounts:
- go vet ./...; GOOS=linux and GOOS=windows go vet ./internal/sessions: ok.
- go test ./internal/sessions ./internal/gui ./internal/usage: ok.
- TestFileFitsEightyBytes (new) holds the size and the round trip of a
  time and of none.
- /api/sessions and /api/sessions/stats?days=30 from a fresh start, real
  history (~23k files): byte-identical to v0.1.3499's code (8,068,574 and
  623,801 bytes).
- 40 /api/sessions polls with X-Magpie-Had: 208 MB allocated before,
  185.5 MB with this.
2026-11-10 10:48:04 +08:00
yetone dae104bfac capre: a length check, not an unrolled repeat, holds nine patterns
Go's regexp unrolls a bounded repeat into that many copies of its
class: [A-Za-z0-9.-]{0,254} (the session terminal's bundle id) was
89kB of program, kept from start to exit, and Codex's item-id refusal
`.{0,1000}?` 88kB. Measured one by one over magpie's 540 package-level
patterns (1.5MB in all), the nine largest bounded ones were ~440kB.

capre.MustCompile(expr, max) is the pattern with * or +, matching only
a string of max characters at most (rune count, so the (?i) Kelvin
sign and invalid bytes count as the regexp counted them). The nine:
settings' bundle id, library's name and agent id (now name@wsl:distro
cut in two), Anthropic tool names, the trace page's name and find,
access's MCP server, OpenClaw's profile and Codex's provider id. The
item-id refusal is a function: the tail within 1000 characters of a
head.

Run on mote (go1.26.8):
- go test ./internal/capre ./internal/access ./internal/settings
  ./internal/library ./internal/sessions ./internal/agent ./internal/gui
  . : ok; ./internal/gateway -run 'ItemID|Undeclared|ToolName|Refus': ok
- TestCappedMatchesBounded holds each old pattern against its new one
  over 14 units x 19 lengths (0..300, at each bound +-1); with the
  length check taken out it is red (1586 mismatches).
  TestItemIDRefusalAsTheRegexp holds the function against the old
  regexp at 998..1002 characters of x, é, 日, \xff, \n; with 1001 it is
  red. TestCappedIsSmall: 1304 bytes held, 49680 bounded.
- go vet native, GOOS=linux and GOOS=windows over the touched packages
  (gui natively: its Linux build needs cgo); gofmt -l clean.
- Real build, GODEBUG=inittrace=1: magpie's own inits allocate
  11.93MB -> 10.61MB.
- Idle on the real-account copy, 180s heap: regexp programs (sampled)
  4.54MB -> 3.01MB.

Not tried: the full ./... suite; the gateway package beyond the run
above.
2026-11-09 21:47:24 +08:00
yetone 8d80f6bc0a sessions: the kept stats and listing hold an untitled id once, not a map entry
keptStats and keptList noted every answer Codex's titles gave in a
map[id]string, to ask each again before the kept ranges are given out.
Nearly every id has no title, and the map held 3.12MB on an 18k-file
history. titleAnswers keeps the named ones in a map and the untitled ids
in a slice, sorted, without repeats or slack once settled; still() asks
each again as before. Both caches use it.

Run (mote, real-account copy, idle 180s, network blocked):
- statsKept.keptTitle.func4 3.12MB -> under the profile's cut;
  total inuse 107.40MB -> 104.23MB.
- TestStatsKeptBetweenPolls now also names a Codex thread after the
  ranges were kept and checks the title reaches them.
  TestTitleAnswersSettled checks repeats and slack go.
- Broken by hand (still() skipping untitled ids, settle not compacting):
  TestListKeptBetweenPolls, TestStatsKeptBetweenPolls and
  TestTitleAnswersSettled red; green on this code.
- go test ./internal/sessions/ ok; go vet darwin, linux, windows ok;
  gofmt clean.

Not tried: the full suite (only internal/sessions reads these caches).
2026-11-09 21:18:44 +08:00
yetone 67d06c24ea sessions: a file's state fits the 416-byte size class, not 448
A state was 424 bytes, so each one decodeCache and parseRead make took a
448-byte slot. HeadSize is the length of a head of headLen (256) bytes
at most; as an int32 beside CdRead it saves 8 bytes, and a state is 416,
32 bytes less held per session file (~0.58MB for 18k files).

Run (mote, real-account copy, idle 180s, network blocked):
- decodeCache's inuse 26.01MB -> 23MB, reflect.unsafe_New 15.51MB ->
  12MB. The profile samples every 512KB, so more than the ~0.58MB the
  size class accounts for is sampling, not this change.
- TestStateFitsItsSizeClass: green; red on the old int by hand ("a state
  is 424 bytes, over the 416-byte size class").
- go test ./internal/sessions/ ok; go vet darwin, linux, windows ok;
  gofmt clean. The cache's JSON keeps head_size as a number, so an old
  cache reads as before.

Not tried: the full suite (state is unexported, only internal/sessions
reads it).
2026-11-09 21:04:19 +08:00
yetone cd0ba05c21 sessions: each day's usage and active rows are made to size
statsOfRange grew every day's Usage and Active rows by append, and the
overview keeps three ranges (7, 30, every day), each holding the slack
of every doubling. The rows are now counted per date first and made at
their length.

Run (mote, real-account copy, idle 180s, network blocked):
- statsOfRange's own inuse 9.90MB -> 8.37MB (-1.54MB in the diff
  against the v0.1.3411 build's profile).
- TestStatsDayRowsHoldNoSlack: green; red on the old code by hand
  ("usage 5 of 8, active 5 of 8").
- go test ./internal/sessions/ ok; go vet darwin, linux, windows ok;
  gofmt clean.

Not tried: the full suite (one package changed, nothing outside it reads
the rows' capacity).
2026-11-09 20:50:24 +08:00
yetone 195d79939e dirent: a listing's entry keeps its time as nanoseconds, 40 bytes not 56
Stat.Mod was a time.Time (24 bytes), so an Entry was 56 bytes. The
listings kept for a long history hold up to ~130k entries (keptEntries),
and on the owner's real cache they were the idle heap's 7.7 MB under
dirent.entry. Mod is now unix nanoseconds (int64) with ModTime() for the
three callers that want a time; getattrlistbulk's seconds and
nanoseconds are summed as time.Unix does. An Entry is now 40 bytes.

Run on mote at this head:
- go test ./internal/sessions ./internal/dirent: ok
- GOOS=darwin/linux/windows go vet ./internal/dirent ./internal/sessions:
  ok
- gofmt -l: clean
- Broken by hand: a 16-byte pad in Stat makes TestEntrySize red
  ("an Entry is 56 bytes, want 40").
- Real-account copy (~/r2278/acct), idle heap at 180s: dirent.Stats
  7.68 MB -> 4.20 MB (dirent.entry flat 5.68 -> 1.70 MB); Footprint
  148 MB.
2026-11-09 20:19:28 +08:00
yetone 36ddd57619 sessions: the overview's active hours keep only the hours with time
Each range statsFor keeps holds an Active for every day, agent and
folder, and each had a 24-int64 Hours (192 bytes), mostly zeros: 4.5 MB
of statsOfRange's 13.5 MB in the idle heap on the owner's real cache
(18,331 files). Active.Hours is now the same sparse hours a day keeps
(hour<<58|seconds), and the act sums in statsOfRange use it too. Its JSON
is the 24 numbers of seconds it was, which the Usage page's heatmap reads
(a.hours.forEach).

Run on mote at this head:
- go test ./internal/sessions: ok
- GOOS=darwin/linux/windows go vet ./internal/sessions: ok; gofmt clean
- TestStatsHoursAndSessions now reads the hours through JSON, as the
  page does. Broken by hand (ms not turned into seconds): red, "the 20th
  by hour: [... 180000]".
- Real-account copy (~/r2278/acct), idle heap at 180s: inuse 110.65 MB
  (v0.1.3402's tree) -> 100.21 MB at this head (sampled; 4.5 MB of it
  was the hours' own lists).
2026-11-09 19:22:48 +08:00
yetone f8186c6915 sessions: a day keeps only the hours it has time in
A day's hours were a [24]int64 (192 bytes) whether or not it had any.
The owner's real cache has 18,331 files and 19,191 days; 13,406 days had
hours, but only 19,107 hours across them had any time, so ~2.6 MB of
zeros sat in the idle heap for good.

hours is now a sorted []uint64 of hour<<58|ms, one entry per hour with
time. Its JSON is still the 24-number array, so sessions.json reads and
writes as before; an all-zero array read back keeps one zero entry so
the day still counts as having hours.

Run on mote at this head:
- go test ./internal/sessions: ok
- GOOS=darwin/linux/windows go vet ./internal/sessions: ok
- gofmt -l: clean
- Broken by hand: without hours.MarshalJSON, TestHoursKeepTheCacheShape
  is red (the packed entries went out as raw numbers).
- Real-account copy (~/r2278/acct): idle heap at 180s, t1 (v0.1.3398's
  tree) vs this: inuse 112.94 MB -> 110.65 MB (-2.3 MB; the 2.6 MB
  estimate less sampling noise).
2026-11-09 19:16:55 +08:00
yetone fc8e98ba47 edit: Codex's thousands of [projects] tables are left out of the reads that don't want them (#2278)
Codex writes a [projects."…"] table for every project it is trusted in;
the owner's config.toml has 10,933 of them in 1.5 MB. go-toml's decoder
checks each table against its siblings one at a time, so every decode
of the file cost ~0.3s of CPU, and six readers decoded it again each
time Codex wrote it, plus a whole-file check before each write magpie
made to it.

- edit.TOMLWithout drops [projects…] tables in a single unstable.Parser
  pass. The agent's codexTopOf, sessions' readCodexConfig, provider's
  readCodexStoreSetting, library's rtk sandbox, hooks rekey and MCP
  entries read through it. None of them reads projects. A file that
  doesn't parse is passed through unchanged, so it still fails.
- validateTOML checks definitions with the rest of the file and the
  projects decoded apart, 128 projects to a decode. A bare [projects]
  table, a dotted projects.… key outside the tables, or any error
  decodes the whole file, so the error is the one it gives.

Run on mote (M5 Pro):
- BenchmarkCodexConfigDecode (10,933 projects): 283ms -> 7.6ms a decode.
- BenchmarkValidateCodexConfig: 52ms (the whole decode was 283ms).
- Startup CPU profile, first 70s, the real-account copy (the real
  1,524,099-byte config.toml): 2.76s -> 2.26s of samples; go-toml
  0.32s -> none sampled.
- go test ./internal/edit ./internal/sessions ./internal/provider
  ./internal/library ./internal/agent: all ok.
- go vet of the same five on darwin, GOOS=linux and GOOS=windows; gofmt -l clean.

Broken by hand:
- Decoding the batches into struct{} instead of a map:
  TestValidateTOMLDefinitionsInGroups went red ("a key twice", "a
  subtable then its key"), so the check keeps maps.

Not tried:
- the whole suite. Only the five packages that read the file were run.
- Now that projects is left out, a project table defined twice no longer
  fails these readers' decode. Codex itself refuses such a file.
2026-11-09 19:07:06 +08:00
yetone 7cabf0da98 sessions: one place says which ids a ZCode request names, and drafts are one group (#5754)
On top of Flandern1211's cherry-picked fix (the commit before this one).
GatewayKeys gave the bare id of a ZCode session (sess_<id> in ZCode's
database, <id> in the gateway's record), but NativeIDs kept its own copy
of the keys: the management page still counted every ZCode session sent
through the gateway as a gateway-only session, its delete listed them,
and its search read them a second time. requestIDs is now the one place
that says which ids a request names a session by; GatewayKeys (Sessions
list, its spend, the stats' native set, viaOf, the manage search) and
NativeIDs (the manage page's count and delete) both read it.

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

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

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

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

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

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

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

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

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

Not changed: the scratch group is worked out on the page (client.js), so
Usage's folder filter still lists the draft folders by their paths; the
group is ZCode's only, and other agents' per-session folders are left as
they were.
2026-11-09 18:49:15 +08:00
yetone b8270850df sessions: a kept parse's rarely set fields live in a StateMore made only when one is set (#2278)
Each of the ~18k files the Sessions cache keeps had a 760-byte state, and
~330 bytes of it were fields almost no file sets: the Codex spawn and agent
maps, Named/Custom/First, the dsh and Claude conversation lists, Root/Leaf,
Compacts, and the six per-agent tails (Grok, Droid, Kimi, Agy, Dsh, Cline).
On the owner's real cache (18,331 files) Root and Leaf are set in 150,
Named in 117, Compacts in 78, First in 35. They move to an embedded
*StateMore, nil unless something is in it: reads go through more() (a
shared empty one when nil), writes through own(). The JSON is the same
(embedded fields are inlined), so the cache version stays.

- parseWith drops an extra that only had empty values written to it, and
  share() drops one the decode made empty.
- clone() deep-copies the extra, so growing a clone leaves the kept state
  alone. Copies that never write (withoutRevisions, the Agent rename)
  share it, as they shared the maps before.

Run on mote at this tree:
- gofmt -l internal/sessions: clean. go vet ./internal/sessions/ on
  darwin, GOOS=linux and GOOS=windows: ok.
- go test -count=1 ./internal/sessions/: ok (26s).
- Every selector was checked by renaming the embedding to a named field
  and compiling with -gcflags=-e until only the struct literals were left,
  so no field is reached through a nil *StateMore.
- New tests in state_more_test.go: zero() knows every field (reflect), a
  read makes no extra and a write never reaches the shared empty one, a
  clone owns its extra, and a cache round trip keeps no empty extra.
  Broken by hand: dropping Cline from zero() and sharing the extra in
  clone() each turn their test red; restored.
- Real-account idle heap (copy of the owner's config and 24.6MB sessions
  cache, gateway idle 180s, heap after GC): decodeCache's retained heap
  35.0MB -> 22.5MB, reflect.unsafe_New 20.0MB -> 10.5MB. The total
  (128.7MB -> 133.6MB) moves by more than that between runs of one binary
  (118-140MB), from late passes that happened to be live.

Not tried: the full ./... suite (state is unexported; only internal/sessions
uses it, and the whole binary builds).
2026-11-09 18:08:28 +08:00
yetone 2a64b4bcb7 library: a skill router, one magpie-skills skill listing an agent's skills
Like the MCP router, for skills. With the Skills tab's new "Skill
router" switch on (off by default), each agent's skills folder gets
one skill of magpie's, magpie-skills, in place of a link of each skill
ticked for it. Its SKILL.md lists them, each with its description and
the path of its SKILL.md, and the agent reads that file when a task
fits. An agent then carries one skill's description in its prompt
however many the Library gives it.

- The entry is a link to <settings dir>/skill-router/<hash of the
  folder>/, which holds SKILL.md and a hidden .skills/<name> link of
  each listed skill (hidden, so Codex, OpenCode and Pi don't find a
  skill twice). Its description stays within 1024 bytes (Codex's
  limit), cut on a whole character.
- Every skill is listed unless it is kept direct (a button on the
  skill, or `magpie library skill router <name> direct`; carried by a
  sync), is only for the user to type (disable-model-invocation), is
  in ~/.agents/skills, is blocked, or the agent has its own by that
  name. Those keep their own links.
- An agent whose folder can't take it keeps every link, and the page
  says why: given copies, a live agent picking its own, the shared
  ~/.agents/skills, a Library skill called magpie-skills, or a
  magpie-skills of the user's (never written over).
- Claude Code 2.1.316 asks before reading outside its project, its
  skills folder too, so magpie adds Read rules for the entry and the
  folders behind it to permissions.allow, records them, and takes out
  only its own when they go (as permissions.deny does).
- The switch is this computer's alone; `magpie library skill router
  on|off` sets it from the CLI.
- Sessions count a routed read of .skills/<name>/SKILL.md as <name>
  (Claude Code, Alma, Droid), and calling up magpie-skills itself as no
  skill, so a use counts once.
- docs/subsystems/skill-router.md, with a row in the index.

Run at this tree (rebased on origin/main 8f74442e4), on mote unless
named:
- go test -tags nogui ./internal/library ./internal/sessions -count=1: ok
- go test -tags nogui ./internal/cli ./internal/gui: ok at bca122bf9;
  ./internal/gui again at 8f74442e4 (app.js changed there): ok
- node --test of every library-*, *skill*, i18n* and gui-* GUI file
  (96 files), in the Linux VM (wsl-run): mote's browsers didn't start
  while another session's simulators ran. 1678 pass, 11 fail at
  bca122bf9, every red also red on origin/main and filed: library-all
  WebKit (#4967), skill-where WebKit 400px (#5154), i18n-keys' plugin
  words (below), and library-own-folder under load, fixed here. The
  files this change touches, add-partners-shine and i18n-keys again
  at 8f74442e4: 111 pass, i18n-keys the 1 red.
- The router's row under the skill list moved four GUI tests'
  footing, fixed in the tests: remove-all-skills counted it as a skill
  (now rows of lists other than a hub's, as list-sort does);
  found-skill-pick-remove and library-pick-remove's reach only wheeled
  down from above the target, so a Select pushed under the sticky tabs
  or below the fold was never reached (now toward it, over the list,
  and the scroll at rest before the click, WebKit's settled a pixel
  late); library-own-folder's Playwright click scrolled the now
  taller page under load (now a click where the button is). Each red
  on the branch before, 22/22 or 14/14 after, twice.
- skill-router.test.cjs: 22/22 (chromium and webkit, 1100 and 420px,
  en zh zh-TW ja de)
- go vet -tags nogui, GOOS=linux and GOOS=windows: ok
- win-run (xiaomi-gpu) go test ./internal/library: ok but
  TestGoneAgentListedToTakeOut and TestCheckMixedServerEachSide, red the
  same at origin/main 6b0b7a96e and filed in #4115 (run at that
  base; nothing in internal/library has changed on main since). The
  router tests' expected rules were /C:/…; Claude Code's form is
  //c/… (claudePath), which the code wrote, so the tests now ask
  claudePath too.
- Broken by hand: routable returning true is red in TestSkillRouter (a
  skill for the user to type is listed); with the routerSkill check
  out of the sessions reader, TestClaudeRoutedSkillCounted is red.
- Real Codex 0.165.0, sandbox HOME, through the live gateway with no
  sign-in copied: a binary built from this change at 6b0b7a96e ran `library skill
  hand-over`, `skill agents secret-word codex` and `skill router on`;
  `codex exec "What is the project's secret word?"` read
  magpie-skills/SKILL.md, then .skills/secret-word/SKILL.md at the path
  given, and answered PELICAN-7319. `router off` put the skill's link
  back and removed the router's folder.
- Real Claude Code 2.1.316, sandbox HOME, through the live gateway on
  auto/gpt-5.6-luna: that binary wrote the router and two
  Read rules into settings.json (the user's "model" kept). "Check your
  skills for one that fits, then greet me." ran Skill magpie-skills,
  then Read .skills/greet-user/SKILL.md without asking, and answered
  with the skill's words. Without the rules that Read was refused
  (tried earlier with hand-written settings). Not tried on the Claude
  subscription route with this binary: there the live gateway drops a
  skill's body, which the gateway commit before this one fixes.

Known: Alma reads Claude Code's and Codex's folders too, so it may find
several magpie-skills (#5722, not tried with a real Alma).
i18n-keys is red on 3 keys that aren't this change's, the same
on origin/main (#5327, #5332, #5482, #5426).
2026-11-09 08:38:02 +08:00
yetoneandFlandern1211 16e79fc6b0 dsh: a request still answering shows under its fork, not its source (#5542)
The Routing page's live card for a dsh fork's request showed under the
source until the reply was written: it has no reply id yet, and the
opening it is keyed by is the one the fork copied. The messages of the
request's turn are in the branch's own session file before the request
goes out, so they name it:

- gateway: Route.LastConvs, the ids of the user messages the request's
  turn carries, newest first (dshLastConvs, dsh only, at most 4);
- sessions: TurnConvs, the ids of the newest turn's user messages, reset
  at turn/start, not kept from a fork's seed, at most 4 (dshTurnKept);
  dsh's parse version goes to 3;
- gui: ownerBy asks the reply id, then the turn's messages, then the
  opening (ownerOfRoute on the Routing page).

Changed from Flandern1211's patch (957caf84) in review:
- the turn lookup has the reply id's guard (forkedFrom): a "继续" in
  another conversation's newest turn no longer takes a route;
- in dsh's captured requests (sessions/testdata/dsh-gateway) the newest
  user message is the runtime context, the same for every session of a
  folder, so it names no one: the gateway reads the whole run of the
  turn's user messages (typed + context), and passes over Messages'
  tool_result steps, where the patch returned nil;
- looseKeys asks for a turn's keys only while the route answers and for
  convsKept, not for every older route: those keys are never listed
  once a newer turn starts, and would relist every agent's sessions on
  each 2s poll;
- one spelling per message and at most 4 kept (a v3 file has no
  turn/start, so TurnConvs grew with every message, 3 ids each);
- no TurnConvs on Context's records (it counts done calls, named by
  reply), LastConvs dropped from the history (saveRoute) and from what
  the page is sent;
- dshLastConvs reads messages by their members, not decoded: 0.49 ms
  on a 2.2 MB body of 800 tool steps (convOf 0.30 ms), 1.10 ms before.

Run on mote at 2be7aaeea (this change on 9730e0199; then rebased over
ec7a18d12, which changes GUI strings and .cjs tests only, no Go):
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/
  ./internal/gateway/ ./internal/agent/: ok (sessions 30s, gui 158s,
  gateway 952s, agent 262s).
- CGO_ENABLED=0 GOOS=linux and GOOS=windows go vet -tags nogui of the
  three packages: clean; gofmt -l internal: clean.
- No GUI asset changed, so no .cjs run.

Broken by hand, each red: LastConvs not set in serve
(TestDshRoutesCarryTheSessionConvs on the real captured requests), no
turn/start reset, no cap, no guard on the turn lookup, no looseKeys
bound, no LastConvs keys in looseKeys (end-to-end Routing test stays on
the source), no strip of the page's routes, no tool_result skip, no
strip in saveRoute.

Not tried: a real dsh fork live (no dsh session files on this Mac or
mote); the contributor measured their version on magpie web.

Co-authored-by: Flandern1211 <163982805+Flandern1211@users.noreply.github.com>
2026-11-08 22:25:58 +08:00
yetone 371b2b63a0 sessions: gateway mode lists the sessions the gateway counted
Usage › Sessions lists only the stats' keys, and the keys named only the
agent files this computer reads. A Docker magpie in gateway mode reads none,
so the sessions that came through the gateway were counted and not listed.
MergeExternalStats now puts them in the keys too, in the list's order.

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

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

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

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

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

Co-authored-by: Ruijia Zhang <ruijiazhang76@gmail.com>
Reported-by: zhang9083 (Discord #feedback)
2026-11-08 00:33:08 +08:00
yetone e9bde2520d codex: OpenAI's threads follow Codex onto magpie from a provider of the user's, and a move the budget stopped asks for the next sync (Lice9735 on X)
Lice9735 on X, Windows, magpie 0.1.3233, Codex app 26.1104: an old chat
(10-13) answered "模型提供商不匹配 — 此聊天使用的是 OpenAI,但你当前
的提供商是 magpie。请切换至 OpenAI 以继续", only a new chat worked,
after d620ff6b5 and d2c29abe7. Their config.toml has a provider table
of their own, openai-http.

Cause. The banner is the app-server's modelProviderMismatch on
thread/resume (app 26.1103: providerBlock is set only from that error;
codex 0.167 load_for_resume compares the stored thread's provider, the
row for a paginated thread, the rollout's session_meta for a legacy
one, with config.toml's). With Codex on a provider of the user's at the
takeover, the stash's codex.provider is that provider, and bringOver
moved only its threads: OpenAI's stayed on openai by design ("whose
threads bringBack would hand them to"). The Codex app lists them and
refuses each one on magpie. A second gap on the same path: the
rewriting moves (MovePackedCodexThreads, MoveRecentCodexThreads) go
128 MB a sync, newest first, and the rest waited for a sync nothing
asked for, which can be hours away.

- bringOver, with Codex on a provider of the user's before magpie (not
  OpenAI, magpie or cc-switch-official, and no profile naming OpenAI),
  moves OpenAI's threads to magpie too: in place, a paginated one by its
  row, the last 30 days rewritten. They are recorded in codex.lent with
  that provider as To, as lendOwn records its own: the Disconnect gives
  every magpie thread to that provider (bringBack), where Codex resumes
  them, and giveLent gives these back to OpenAI once Codex is on OpenAI
  again. One the app holds open waits (codexThreadsLater on openai).
- MovePackedCodexThreads and MoveRecentCodexThreads say more when the
  budget stopped them with a thread left, and bringOver, bringBeside and
  lendOwn ask for the next sync at once (codexThreadsAgain). The three
  share one mover now (codexOnto); bringBeside also waits on a held
  thread as the other two do. packedBudget is a var, for the test.
- Tests: TestCodexOpenAIThreadsFollowMagpieFromOwnProvider (new: an
  openai-http table named "OpenAI", a plain and a packed OpenAI thread,
  moved, lent, to openai-http at the Disconnect, back to OpenAI after;
  none while a profile names openai), TestCodexThreadsLeftByTheBudgetAskAgain
  (new), TestMovePackedCodexThreads checks more. TestCodexThreadsFollowMagpieIn's
  two user-provider subtests now expect OpenAI's thread on magpie, then
  on that provider after the Disconnect.
- docs/subsystems/agent-wiring.md says so.

Run:
- Real codex-cli 0.166.0 on mote, sandbox HOME and CODEX_HOME, a fake
  Responses server: a thread started on the built-in openai (API key,
  openai_base_url), a second after switching to model_provider
  openai-http (name "OpenAI"); both paginated. On openai-http the first
  was refused ("This chat uses openai, but your current provider is
  openai-http"). A throwaway test (not committed) ran magpie's takeover
  (Set fake/m1, Sync) on a copy of that home: with origin/main's code
  the openai row stayed and `codex exec resume` on magpie (the copy's
  base URLs pointed at the fake) failed with exactly "This chat uses
  openai, but your current provider is magpie"
  (modelProviderMismatch); with this change the row was magpie,
  codex.lent {"to":"openai-http",...}, and the resume answered.
- New and changed tests red on origin/main 191f3c0af (the openai thread
  on "openai", want "magpie"; after the Disconnect "openai", want the
  user's provider).
- Broken by hand: bringOver's `if more` dropped ->
  TestCodexThreadsLeftByTheBudgetAskAgain red ("0 sync(s) asked for");
  `more = true` turned false -> TestMovePackedCodexThreads red.
- mote: gofmt -l clean; GOOS=windows go vet and GOOS=linux go vet
  -tags nogui of internal/agent and internal/sessions ok;
  go test ./internal/sessions ./internal/agent ok at this head
  (this change on e6cdeac9c; rebased after onto 5dbdfc1bd, which
  changes internal/provider only), agent 292.2s, sessions 47.4s. Pushed and tagged
  without waiting for the full `go test -timeout 45m ./...`, per the
  owner's rule to ship each verified fix at once; it runs on mote after
  another session's suite, and a red it shows is filed or fixed in a
  follow-up.
- win-run (xiaomi-gpu), go test ./internal/sessions ./internal/agent
  (at the commit's parent before a rebase onto abe7b0063, which touches
  neither package): every test this change adds or touches passes; 29
  reds, 28 of them red the same at origin/main 191f3c0af run alone
  there. The 29th, TestHermesProfilesFollowMagpieModel, passes alone
  3/3 on this tree and is in #4115.

Not tried: the Codex app itself (the CLI's app-server gives the same
error the app shows); Windows with a real Codex; a legacy (non-paginated)
thread with a real Codex, covered by the unit tests only; a history
over 128 MB with real files. The chat the app has loaded at the switch
goes on once the app lets it go: fully quit the Codex app and reopen it
after magpie updates.
2026-11-07 18:08:39 +08:00
Flandern1211 d052fec0e3 dsh: a fork without a parent gets its own row, named by its replies (#5542)
#5491 names a dsh fork's completed requests by the reply id dsh writes
with them, over the conversation's opening only where the two agree: the
reply's session owns the opening, or is a fork of its owner, which the
fork header's parentSession says (Session.ForkOf).

dsh 0.2.2's ordinary fork writes isSeeded and session/end-seed but no
parentSession. ForkOf is empty, the guard refuses the reply id's own
session, and the fork's requests stay under its source on Routing and
Context; the fork's own row never appears (Flandern1211: 7 of 17
top-level seeded sessions on one computer are such forks).

end-seed now keeps the conversation ids its copied events opened
(SeedConvs) instead of dropping them with the seed's counts. That is the
fork's own file saying it copied that opening, and forkedFrom accepts it
when the fork names no parent, only to admit a reply id that is already
one session's. A route with no reply id still goes by the opening, and a
reply id two sessions share stays ambiguous. dsh's parse version rises
so kept parses are read again; the Routing integration fixture leaves
parentSession out, as current dsh does.

Flandern1211's fix/dsh-fork-without-parent @ ead1abcce, as written; one
conflict taken (parseVersions has antigravity 2 on main). ggbdpq's port
on #5542 (0d7e18d1e) is the same change.

Not ported: the follow-up fix/dsh-fork-unmatched @ 1bce689ed (Context
page leaves a fork-shared opening's unread route out of both cards).
Review findings are on #5542.

Run at aca932bf7 (this change on 5c5160c94), on mote; the pushed head
adds only e20517a88 under it, a one-line Qoder mover min:
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./..., go build ./..., GOOS=linux go build -tags nogui ./...,
  GOOS=windows go build ./...: all ok.
- go test -tags nogui -count=1 ./internal/sessions/ ./internal/gui/
  ./internal/gateway/: ok (18.8s, 82.8s, 783.9s).
- gofmt -l on the six files: nothing.

Broken by hand (mote, -run 'Dsh|Fork|Routing|Context'):
- end-seed dropping SeedConvs: TestDshForkWithoutAParentKeepsItsSeedOpenings
  red ("seed openings [], want [magpie-e2f7b8e6… …]") and
  TestRoutingTellsAForkByItsReply red ("route 1: session
  \"session-source\", want \"session-fork\"").
- forkedFrom ignoring the seed: TestDshForkWithoutAParentIsNamedByItsReply
  red ("reply \"chatcmpl-fork\", opening \"magpie-open\": \"source\",
  want \"fork\"") and TestRoutingTellsAForkByItsReply red.
- assembleListed not carrying SeedConvs onto the Session:
  TestRoutingTellsAForkByItsReply red.
- Review check: the source's routes from before reply ids were kept (no
  ResponseID) still make the source's Context card, 3 of 3 requests.

Not tried: a replay of real dsh session files (the reporter's numbers
are on #5542; ~/.dsh here is a live config and was not read); dsh's
parse version bump is not pinned by a test of its own (the generic
re-read on a raise is, in cache_decode_test.go).

Reported-by: Flandern1211
Co-authored-by: Flandern1211 <163982805+Flandern1211@users.noreply.github.com>
2026-11-07 13:54:24 +08:00
yetone a1774d1235 sessions: an Antigravity app conversation's folder is its summary row's workspace
The Antigravity app's Sessions tab put every conversation under "No
folder". Since 24dc1651b the app reader reads each conversation's row of
~/.gemini/antigravity/conversation_summaries.db for its title, and the
row's workspace_uris (a JSON list of file:// URIs) was already parsed into
the row's folder for agy, but parseAntigravity never set it as the
session's folder. It now does: the first local workspace URI, the same
rule as agy (agyFolder, including Windows drive and UNC forms). A row with
"[]", and a conversation with no row, still have no folder.

The antigravity parse version goes to 2: a parse kept in the Sessions
cache has the same row revision (agyRev already holds the folder) and
would otherwise keep its empty folder until the conversation changed.

Sibling, agy (the Antigravity CLI tab): already sets the folder from the
same column, for transcripts and row-only conversations (TestAgy*); no
change. A transcript with no row has no folder there, as before.

Shapes: workspace_uris and raw_summary as this Mac's agy writes them
(read only; ["file:///<project>"]); the fixture's paths are made up.

Run (mote): go test -tags nogui ./internal/sessions ./internal/usage ok;
GOOS=linux go vet -tags nogui and GOOS=windows go vet ./internal/sessions
ok; gofmt clean; GUI sessions-folder-list, -paging and -delete in
Chromium (34 pass) and WebKit (17 pass).

Broken by hand: with the old antigravity_app.go and sessions.go,
TestAntigravityAppFolder reads "" for both conversations with a workspace,
and TestAntigravityAppParseBeforeFolderReadAgain keeps the old parse.

Not tried: a real Antigravity app summaries database with workspace rows
(this Mac's app data folder has no conversations); the reporter's own
data; Windows paths beyond agyFolder's existing unit test.

Reported-by: xxooioo (Discord)
2026-11-07 09:42:37 +08:00
yetone 24dc1651b0 sessions: Antigravity's conversations take their title from conversation_summaries.db
The Antigravity desktop app's Sessions tab read every row as "(no
prompt)". The app keeps its step payloads encrypted, and the reader only
read their metadata, so no title was ever found. The app's language
server (the same code as agy) writes a row per conversation into
~/.gemini/antigravity/conversation_summaries.db: title once one is made,
and preview (the first request) from the start. The app reader now reads
that row, the same way agy's reader does, with title as the session's
name and preview as its prompt, and reparses when the row changes.

Sibling, agy: a row-only conversation with no title yet (the real row on
this Mac, agy 1.4.12: title "", preview "hi") was not listed at all; it
now shows its preview. A summaries database made before preview was a
column is still read (falls back to title only). The rows cache is kept
per database, since both readers now read one each.

Run (mote): go test -tags nogui ./internal/sessions ./internal/usage ok;
GOOS=linux go vet -tags nogui and GOOS=windows go vet ./internal/sessions
ok; gofmt clean. DDL in the test is from Antigravity 2.29.0's
language_server, started in a sandbox HOME on mote, which created
conversation_summaries.db on first start.

Broken by hand: with the old agy.go, antigravity_app.go and sessions.go,
TestAntigravityAppTitle fails ("before a title: \"\", want the preview")
and TestAgyRowOnlyPreview finds no session. With the preview-less
fallback query removed, TestAgyRowsWithoutPreview fails (rows map[] ok
false).

Not tried: a real Antigravity app database with summary rows (this Mac's
app data has none to read, and its files were only read); app versions
older than 2.29.0, which may keep summaries in agyhub_summaries_proto.pb
instead. workspace_uris is not used as the app session's folder.

Reported-by: xxooioo (Discord)
2026-11-07 08:43:16 +08:00
yetone 2f660ca86b sessions, usage: Antigravity's gemini-4-argon-d is gemini-4-argon, not a second unpriced model
oioio's Antigravity database names gemini-4-argon's generator
"gemini-4-argon-d". agAppModel took only "-n" off a gemini-* id (Google's
gemini-3.8-flash-n, b2432754e), so the Usage panel showed gemini-4-argon
twice and the -d one had no price. usage.GeminiServing had the same
"-n"-only rule, so the gateway's log would call gemini-4-argon answered
as gemini-4-argon-d a swap.

Both now ask sessions.GeminiDeployment: a gemini-* id with one lowercase
letter after its last hyphen is that model's deployment. Google's own
ids never end in a lone letter (-lite, -nano, -pro, -001, -exp), and
other makers' ids (gpt-5-d, claude-sonnet-4-5-n) stay as written. The
rule is by shape, not by the catalog: a catalog lookup at parse time
would freeze a "-d" into the kept parses whenever models.json wasn't
there yet. antigravity's parseVersions and callParseVersions go to 1,
so parses and call shards kept with gemini-4-argon-d are read again on
update; nothing else is reread.

Run (mote, at this tree):
- go test -tags nogui ./internal/sessions ./internal/usage: ok.
- go vet, GOOS=windows go vet, GOOS=linux go vet -tags nogui on both
  packages; gofmt -l prints nothing.
- Broken by hand: GeminiDeployment put back to the old -n-only rule.
  TestAntigravityAppDeploymentName failed ("gemini-4-argon-d":
  "gemini-4-argon-d", want "gemini-4-argon", fields 19, 21, 22) and
  TestSwappedGeminiServingName failed ("gemini-4-argon answered as
  gemini-4-argon-d is the model asked for"); both pass with the change.
- Full suite runs after the push (go test -tags nogui -timeout 45m ./...).

Not tried: oioio's own database (only the model name was posted), and
a real gateway request that Google answers as gemini-4-argon-d.

Reported-by: oioio (Discord)
2026-11-07 00:22:13 +08:00
yetone 6302f88bf0 sessions: a Codex prompt's title is read from its head, not its whole text decoded
cxFastPrompt decoded each user message's whole text with json.Unmarshal
to take its first 160 runes for a title. A pasted log or file made all
of it again (512MB on a cold read of a year of real Codex history,
5% of everything allocated). cxTextPrompt now decodes the first ~1KB
when that settles the title. A text with nothing to unescape is read
where it is, and only the title is a string of its own. The rest is
only checked to be what json.Unmarshal takes. Whatever the head doesn't
settle is still decoded whole: a title short of 160 runes, spaces to the
end, a cut that isn't clean, or an unclosed string. title is split into
titleCut, which says whether words were left past it.

Run on mote:
- TestCxTextPromptAsTheWholeText holds it to the old path (strAt then
  cxPrompt), title for title. It covers 4000 random texts of 50 to 20k
  bytes with escapes, surrogates, bytes not UTF-8, space runs, Codex's
  own texts and refusals late in the string, plus 16 cases made by hand.
- TestCxTextPromptDecodesItsHead: a 5.3MB prompt's title makes 5.2KB,
  was 9.8MB. A plain prompt makes no allocation beyond title's own.
- Broken by hand, each red: no check of the rest, a cut at any byte, a
  head that doesn't hold the title, plain without the UTF-8 or control
  byte check, whole decode, no plain view.
- Cold run of real history copies, 120s: cxFastPrompt over claudeLine
  (the workload's measure) 0.094, was 0.311 at v0.1.3164's base.
- gofmt; go vet ./internal/sessions for darwin, linux and windows;
  go test -count=1 ./internal/sessions at the pushed head. The full
  suite was not run.
2026-11-06 19:53:13 +08:00
yetone 94d4866b5e sessions: a Claude session's calls list grows to the rate its file was read at
claudeCall appended each call to st.Calls, and append grows a long list
by about a quarter at a time, so a session's calls were copied through
lists holding ~5.2 times them on the way to its length: 616 MB of a
120s cold start's allocations on mote over real history copies, the
largest single line in it.

When the list is full and past 256 calls, growCalls makes room for the
calls the rest of the file is likely to hold at the rate read so far
(calls / bytes read, times the file's size, an eighth more), at most
twice the calls so far, so a misjudged rate costs no more than a short
list's doubling. A file read from its cache's offset counts from there
the same way; a packed file, whose offsets run past its size, is left to
append.

TestClaudeCallsListGrownToTheFile reads 20k replies through
claudeCallLine: the lists on the way hold 2.84 times the calls (bar
3.5), the last 1.14 times; by hand, growCalls returning at once, 5.2
times, red. A file whose second half is ten times as long per call ends
at 1.44 times, under the bar of twice.

Measured on mote, 120s cold, rc5 (the parent) against rc6 (this change)
under load 67-112: heap peak 244 MB and 243 MB, the same. The list's
growth over the Sessions read of the same lines (claudeLine) 616/1234 =
0.50 -> (535 + growCalls' 192)/1778 = 0.41: most of a real history's
sessions stay under 256 calls, which append still grows.

Run at the rebased head on mote: gofmt; go vet ./internal/sessions for
darwin, linux and windows; go test -count=1 ./internal/sessions ok.
Not run: the full suite (last at v0.1.3152's change, 85 packages ok).
2026-11-06 19:36:59 +08:00
yetone 8c97edc802 sessions: a calls write goes to its file a frame at a time, its patch list made once
writeCalls held a whole write in one bytes.Buffer, grown by doublings,
before any of it went to the file, and the frame's patch list grew by
append from empty whenever a collection had emptied its pool, as it does
all through a first start. In a 120s cold start on mote over real
history copies (#2278 recipe), the list's growth was 148 MB and the
buffer's 150 MB of writeCalls' 556 MB.

Now each frame is encoded into one pooled buffer and written to the file
at once, so a write holds at most one frame (~1 MB, where a 52k-call
session held 8 MB), and the list is grown once to the first frame's size.
A write that fails after its first frame leaves frames ending in More,
which loadCalls already reads as a write cut off: the file is read again.

Measured, rc4 (303a31dd6's tree) against rc5 (this change), 120s cold on
mote: the list's line is gone from the profile, bytes.growSlice 150 ->
70 MB while rc5 did 1.39x the writes (gob's encoder buffers 240 -> 334
MB); writeCalls 556 -> 583 MB for that 1.39x, ~25% less a write. What is
left is each frame's gob encoder's own buffer, which a frame decoded on
its own needs.

TestCallsWriteAfterACollection writes 10240 calls after two collections:
4.9 MB, bar 6 MB. By hand: the list not grown at once 7.4 MB red, the
whole write held 6.8 MB red; the old code 9.3 MB. It reads the file back
call for call.

Run at the rebased head on mote: gofmt; go vet ./internal/sessions for
darwin, linux and windows; go test -count=1 ./internal/sessions ok.
Not run: the full suite (last at v0.1.3152's change, 85 packages ok).
2026-11-06 19:28:44 +08:00
yetone 303a31dd6b sessions: a Claude prompt's content and a reply's usage are read in place
The Sessions read of a Claude history decoded a prompt line whole, so
its content (pasted text, images) was copied into a json.RawMessage
for each line, then copied again as the prompt's text; and each reply's
usage object, a few numbers, went through a json.Unmarshal of its own.

- claudeFull decodes its line as the calls' read does (ccDecode, now
  ccDecodeLess for any line): content nulled, given as the bytes of the
  line that hold it. Nothing keeps those bytes: the prompt's text and
  title are copies, as before.
- ccReply reads its usage with ccDecodeUsage, in place through gjson.
  What it can't be sure of reading as json.Unmarshal does (a known key
  in another case, a number that isn't a plain integer, a value of
  another type, cache_creation twice, invalid JSON) goes to
  json.Unmarshal.

Measured on mote, cold start over a copy of real Claude and Codex
histories (acold.sh, 120s), against v0.1.3155's build at the same base:
  ccReply 540MB -> 395MB, claudeFull 450MB -> 412MB,
  encoding/json.(*RawMessage).UnmarshalJSON 209MB -> gone.
mote's load was 74 to 126 from other sessions' runs, so the 120s
totals and peaks moved between runs of one binary (footprint peak
193-228MB, heap peak 164-194MB for this build; 180-181MB and
163-176MB for the base); neither is claimed as a change.

Tests:
- TestCCUsageDecodedAsJSONUnmarshal: the same fields or the same
  refusal as json.Unmarshal for 30 hand-made shapes and 3000 random
  objects. Red by hand with the case-folded key check taken out.
- TestCCUsageReadInPlace: Claude Code's usage read with at most 1
  allocation (its cache_creation); 7 by hand with json.Unmarshal.
- TestClaudePromptContentNotCopied: a 1 MB prompt line read whole
  makes 1.05 MB (its text once), bar 1.5x the line; 2.09 MB by hand
  with the old decode. The content given is the line's own bytes, and
  the title, prompt count, cwd and session id are read as before.

Run on mote at the pushed tree: go vet and go test ./internal/sessions.
Not run: the full suite (last at v0.1.3152's change: 85 packages ok,
reds only #3949 and #5481).
2026-11-06 19:08:15 +08:00
yetone d6f59f9fd0 sessions: a Claude message is looked up without making its key again
Every line of a Claude reply looked its message up by "message:"+id, a
new string each time, though only the line that adds the message keeps
it. The key is now built in a stack buffer for the lookup, made a
string only when a message is added, and a second branch of a message
takes the key its first one made.

Measured on mote, cold start over a copy of real Claude and Codex
histories (acold.sh, 120s), against v0.1.3152 built at the same base:
  message() 157MB -> 142MB, footprint peak 186MB -> 180MB,
  heap peak 169MB -> 163MB, GCs 129 -> 122; total allocated the same
  within noise (3.67GB vs 3.70GB). Most replies are one line, so most
  lookups add the message.

Test: TestClaudeMessageLookupAllocations: a message's later line makes
0 allocations; a second branch shares the first's key string; a
request-only message is keyed by its request. Red by hand with the old
lookup ("made 1 allocations, want 0").

Run on mote at the pushed tree: go vet and go test ./internal/sessions.
Not run: the full suite (last run at v0.1.3152's change, 85 packages
ok, reds only #3949 and #5481).
2026-11-06 18:50:13 +08:00
yetone 9a0aab32c1 sessions: a Claude reply evicted from the window is used again for the next
A Claude history's read keeps a window of recent messages to fold
revisions together. Each message made a contribution, a branch map and
its tool and block maps, and dropped them when it left the window: on a
cold start of a real history copy that was ~750MB of message() and
~690MB of ccTool's maps. An evicted contribution and its emptied branch
map now go on a short free list (16 contributions, maps over 64 entries
dropped) and the next message takes them, cleared.

Measured on mote, cold start over a copy of real Claude and Codex
histories (acold.sh, 120s), against v0.1.3128's build:
  allocated 8.96GB -> 8.79GB, GCs 277 -> 266,
  footprint peak 197MB -> 189MB, heap peak 194MB -> 186MB.
message() 750MB -> 565MB, ccTool 689MB -> 466MB.

Tried and dropped: doubling the calls list by hand saved ~0.5GB of
allocation but raised the footprint peak to 265MB (lists held at up to
twice their size while read), so the calls list grows as before.

Tests:
- TestClaudeEvictedContributionsLeaveNothing: 3 windows of replies
  through both reads; every live contribution holds only its own
  message's tools and blocks, usage, calls, replies and output totals
  are right, a replayed reply makes no call. Red by hand without the
  maps' clear ("holds another message's tool") and without recycling
  ("nothing evicted was kept").
- TestClaudeHistoryReadAllocations: 3156 bytes a reply once the window
  is full, bar 4200; 5348 without recycling (red by hand).

Full suite on mote (gofmt, vet darwin/linux/windows, go test -timeout 45m ./...):
85 packages ok; red only TestMainWindowCorners (#3949) and
TestRenewLoginsKeepsClaudeReading (#5481), both filed and red on main.
internal/sessions run again at the rebased head.
2026-11-06 18:38:51 +08:00
yetoneandFlandern1211 e8df78f33e routing: a dsh fork's requests are named by the reply its client was given (#5491)
dsh's chat and messages routes send no session id, so Routing and Context
found a dsh session by the hash of the conversation's opening. A fork
repeats its source's opening, so every request the fork made showed under
the source, and the fork's name never appeared.

Flandern1211's patch, ported:
- The gateway keeps the id of the reply it gave the client
  (Route.ResponseID). It is set from clientResponseID in the same update
  that marks the route done, so a poll that sees Done also sees the id,
  with no race against the usage ledger. When magpie translates, it is
  the id after translation, e.g. chatcmpl-…, not the upstream's msg_….
- sessions reads dsh's replayState.response.responseId into
  Session.ResponseIDs. Only main files are read, only replies served by
  the gateway, and only the fork's own replies after its session/end-seed
  (seedLength for version 1).
- Routing (pricedRoutes) and Context (joinConvs) look up a finished
  request by its reply id first, then by its opening. A request logged
  before this keeps the opening's session.

Changed from the patch:
- A reply id names a session over the opening only when the opening is
  that session's own, or a session it was forked from, or the opening is
  unknown. Vendors' ids can repeat: an encoder keeps the upstream's id,
  and Ollama's is chatcmpl-<0..999>. Without the guard, two unrelated
  conversations could swap names. Session.ForkOf comes from the fork
  header's parentSession, isSeeded and delegationDepth 0, which is how
  dsh's buildForkSeed writes it. ownerOf walks that chain, so a fork of a
  fork works too.
- Poll cost: dsh never writes down some reply ids (a title call, a
  refused turn). Under the patch, each such id made Routing list every
  session again every 2s, for as long as the route was on the page. Now
  an id is waited for only up to a minute (convsKept) after its request
  ended (looseKeys). After that the regular one-minute rebuild covers it.
- A page whose loose routes carry only a reply id still builds the map
  (looseRoute).
- The patch's synthetic fork headers gain parentSession, as dsh writes
  them.
- docs/subsystems/gateway-routing.md describes the reply-id join.

Tests:
- TestDshForkNamedByTheReplyTheGatewayGave sends dsh 0.2.0-rc.2's real
  captured completions request (testdata/dsh-gateway) through
  gateway.New() twice, to an Anthropic-only upstream, so the reply is
  translated. It writes the source's real session file with the first
  client id, and a fork shaped like dsh's buildForkSeed output with the
  second. It then checks that pricedRoutes and contextOf put each request
  under its own session, and an old route without an id under the source.
- TestDshForkOfARealSessionListsItsOwnReplies forks the real fixture
  session: the fork lists only its own reply and ForkOf, the source
  keeps [c1].
- TestDshReplyIDOfAnotherConversationNamesNoOne covers the guard.
- TestRoutingWaitsForAReplyIDOnlyAWhile covers the poll bound.
- The patch's own tests: TestDoneRouteKeepsTheClientResponseID (json and
  stream), TestDshResponseIDs*, TestRoutingTellsAForkByItsReply,
  TestContextTellsAForkByItsReply.

Run on mote (mote-run), at this tree on origin/main be5e8f29f. The vet and
go test lines below were run again after rebasing on e6b9d1199, which
changed only the README and library (ok):
- gofmt -l internal/ printed nothing.
- go vet ./internal/... . is clean.
- GOOS=linux go vet -tags nogui and GOOS=windows go vet of
  internal/{sessions,gui,gateway} are ok.
- go test ./internal/sessions ./internal/gateway ./internal/gui -run
  'Dsh|ResponseID|Fork|Routing|Context|Conv' -count=1: ok.
- GUI: routing-by-key, routing-ctx-sessions, routing-request-metrics,
  routing-sessions, routing-session-folder, sessions-empty-range,
  ctx-route, context-map and panel-routing pass in chromium (120/120)
  and webkit (120/120).

Broken by hand, each red, then restored:
- guard off: TestDshReplyIDOfAnotherConversationNamesNoOne;
- poll bound off: TestRoutingWaitsForAReplyIDOnlyAWhile;
- end-seed keeps the inherited reply ids: TestDshResponseIDsSkipTheSeed,
  TestDshResponseIDsEndSeedAcrossReads and
  TestDshForkOfARealSessionListsItsOwnReplies;
- ForkOf not set: TestDshForkOfARealSessionListsItsOwnReplies,
  TestDshForkNamedByTheReplyTheGatewayGave,
  TestRoutingTellsAForkByItsReply and TestContextTellsAForkByItsReply;
- gateway keeps no id: TestDoneRouteKeepsTheClientResponseID and
  TestDshForkNamedByTheReplyTheGatewayGave.

Not tried:
- a real dsh fork against a running magpie. The session shapes come from
  the real rc.2 fixture and dsh's fork source.
- A request still running, or a failed one, still shows under the source
  until it has a reply id. The patch says the same.
- Delegated subagent files (delegationDepth > 0) are not read for reply
  ids; they stay under their parent as before.
- Not changed: the gateway's turn clock (sessionTurnKey) also falls back
  to the opening's hash, so a fork and its source running at once share
  one. Filed as #5496.

The full suite runs after the push.

Co-authored-by: Flandern1211 <163982805+Flandern1211@users.noreply.github.com>
Reported-by: flandern1211_58540 (Discord)
2026-11-06 17:22:52 +08:00
yetone 81d6a3294b sessions: a first start's read of Claude Code history makes 39% less garbage (#2278)
A first start (or one after the session caches are gone) reads every
Claude Code transcript to count calls. On a real 21 GB history this
allocated 14.6 GB and ran 460 GCs. Three things made most of what was
thrown away right after:

- ccWithoutContent made a new copy of each reply line with its content
  set to null (82 MB), and gjson.GetBytes copied the content to find it
  (27 MB). ccDecode now builds the stripped line in a pooled buffer and
  finds the content through an unsafe.String view, with no copy.
- ccStr.UnmarshalJSON went through json.Unmarshal for each string, which
  made a decoder for each one (29 MB). A string with no escapes and valid
  UTF-8 is now taken as its bytes. Anything else still goes to
  json.Unmarshal, which writes U+FFFD for bad bytes.
- writeCalls made a new Patches list for each frame (1 GB). It now reuses
  one list from a pool and clears it before putting it back, so the pool
  keeps no reference to the call state.

Measured on mote with the real 21 GB history copied into a sandbox HOME,
with the session caches deleted before each run, over 120s:
  v0.1.3118: 14.6 GB allocated, 460 GCs, CPU 3:17, footprint peak 195 MB
  this:       8.96 GB allocated, 277 GCs, CPU 3:19, footprint peak 197 MB
The footprint peak is what is live (the caches), so it does not change.

Tests:
- TestCCDecodeAsUnmarshal holds ccDecode to json.Unmarshal of the whole
  line. Its cases are escaped content, non-UTF-8 bytes, content first,
  an error line, not JSON, and an empty line.
- TestCCDecodeAllocations allows at most 1300 bytes for a 41 KB reply
  line.
- TestCallsWriteKeepsNoPatchListPerFrame allows at most 6 MB for a
  6144-call write.
Both allocation tests turn GC off while they measure, because a GC
empties the pool; they passed 5 of 5. Broken by hand: with the line
pool removed, the decode test made 1984 bytes and went red. With the
Patches list made per frame again, the write test made 13056 KB and
went red.

Full suite on mote at 3f53fa1f3 plus this change: gofmt clean, go vet ok (darwin, linux nogui, windows), go test -timeout 45m ./...: 86 packages ok; internal/gui red only in TestMainWindowCorners/macOS_26_SDK, the known #3949 (macOS 27 corners), not touched here.
2026-11-06 14:58:40 +08:00
yetone d2c29abe73 codex: a chat the Codex app had open as magpie became its provider moves once the app lets it go (crypto0xfish on Discord)
crypto0xfish on Discord, the Codex app: "Model provider mismatch. This
chat uses OpenAI, but your current provider is magpie. Switch to OpenAI
to continue."

magpie makes itself Codex's provider (model_provider = "magpie") when
Codex has no ChatGPT sign-in, is signed in with an API key, the user
picks magpie API, or the ChatGPT account is used up (the takeover).
bringOver then moves OpenAI's threads to magpie, a paginated one by its
row (RetagPagedCodexThreads), skipping any a Codex holds open (its
writer lock) or wrote to in the last minute, "for the next sync". The
Codex app holds the lock of every thread it has loaded, the chat on
screen among them, however long ago it was written (tried below), and
nothing asked for that next sync: Sync runs on catalog changes, which
can be hours away. So the chat open at the switch stayed on OpenAI;
the app refuses it while loaded (app-server
check_thread_model_provider_for_input compares the loaded thread's
provider with config.toml at each turn), and after the app let it go it
was refused again on resume by its row, until something else synced.
681a472ca fixed the same gap for bringBack by time alone and named the
held-lock case as not tried.

- sessions.CodexThreadsBusyOn also counts a thread on the provider
  whose writer lock a Codex holds (codexLockedIDs: the lock files in
  thread-writer-locks, each tried and let go under Codex's coordination
  lock, none made or removed).
- codexThreadsLater(dir, p) now looks every 15s, for up to 12h, and asks
  for the Sync once nothing on p is busy or held; one wait per home and
  provider. bringBack keeps calling it for magpie; bringOver calls it
  for the provider it moved from, and lendOwn for openai (the same skip,
  OpenAI's threads onto a provider of the user's).
- Tests: TestCodexOpenThreadFollowsMagpieOnceLetGo (new: a paginated
  OpenAI thread held open stays at the takeover, no Sync is asked while
  held, one is once let go, and that Sync moves it to magpie);
  TestCodexTakeoverThreadComesBackOnceQuiet now expects the Sync only
  after the thread is quiet. TestMain turns the wait off so no goroutine
  outlives a test; the two tests end theirs in Cleanup.
- docs/subsystems/agent-wiring.md says so.

The chat loaded at the moment of the switch can't be helped from
outside: the app goes on with it once it reloads it (quit and reopen).
Codex's identity line, base_instructions and every value of the user's
are untouched.

Run on mote at this tree (base cff530079):
- gofmt -l: clean; go build ./...: ok;
- go vet ./internal/agent ./internal/sessions for darwin, linux -tags
  nogui and windows: clean;
- the two tests with -race -count=3: ok;
- go test ./internal/agent ./internal/sessions: ok.
On Windows (win-run): the two tests and TestCodexPagedThreadsFollowByRow: ok.

Broken by hand: bringOver's call turned off (`if false &&`), the new test
fails "no later Sync asked for"; the lock check in CodexThreadsBusyOn
turned off, it fails the same way. Restored, both pass.

Real Codex: codex-cli 0.165.0's app-server in a sandbox CODEX_HOME, a
thread started and a turn sent (to a dead fake provider). With the thread
loaded and its rollout quiet 73s, its lock was held, a probe built from
this tree said CodexThreadsBusyOn true and RetagPagedCodexThreads moved
nothing; after the app-server exited and a quiet minute, busy was false
and the retag moved the row.

Not tried: the real Codex desktop app (whether leaving a chat for another
lets its lock go within a minute, or only quitting does), and a live
switch with a real used-up or API-key account. The reporter's own setup
(why Codex was on magpie for them) is not known.

Reported-by: crypto0xfish
2026-11-06 11:26:41 +08:00
yetoneandyygutn 783537e810 sessions: the Antigravity app's own conversations count on Usage and Sessions (#2190)
xxooioo (Discord) asked for the Antigravity desktop app's calls made
without magpie's gateway on Usage and Sessions. The app keeps each
conversation as a SQLite database, ~/.gemini/antigravity/conversations/
<id>.db (WAL). Messages are encrypted, but steps.metadata is plain
protobuf: 1 the step's start, 9 the call's usage (2 input, 3 output,
4 cache write, 5 cache read, 11 response id), 20.3 the gen_metadata idx
of its generator, whose message names the model (field 19, else 21/22).

The reader opens the database read only, in one read transaction; a
response id seen twice is one call at its last step. Each conversation is
a read-only session under agent "antigravity", gated by Reads like every
other agent and added to Found. A call the app sent through magpie is
matched to the gateway's record by tokens and time the way agy's steps
are (agyLocal now covers "antigravity"), so it is counted once.
"gemini-3.8-flash-n", the model the rows name, is counted as
gemini-3.8-flash (b2432754e).

Fixture: the four steps.metadata rows yygutn posted on #2190, byte for
byte (testdata/antigravity/steps.tsv), under the schema he posted; the
decoded tokens and times match his figures. The gen_metadata rows wrap
the posted field-19 bytes in a field-1 message, since the rest of that
row was not posted.

Run on mote: go test -count=1 ./internal/sessions/ ./internal/usage/
./internal/agent/ ok; ./internal/gui/ ok but TestMainWindowCorners
(#3949, macOS 27, untouched); gofmt -l clean; GOOS=linux and
GOOS=windows go vet of sessions and usage clean (./... for linux stops in
Wails' cgo files, as without this change). skillsCounted says why the
app's skills aren't counted (step payloads are encrypted).
Broken by hand: agyLocal back to "agy" only fails
TestAntigravityAppCallThroughMagpieCountedOnce; the wholeCallReaders key
renamed fails TestAntigravityAppCalls (0 calls).
Not tried: a real app database (the app isn't installed on any test
machine); whether a call through the gateway records the same tokens;
conversation titles (not read; agyhub_summaries_proto.pb unknown).

Co-authored-by: yygutn <yygutn@gmail.com>
2026-11-06 10:07:06 +08:00
yetoneandFlandern1211 5ca9f0f9d7 sessions: a ZCode fork's card shows its own title (#5365)
ZCode files a fork as sess_<id> with its parent's id in parent_id
(task_type=fork), and ocRoots groups it under the parent's key. A
request names the fork by its own id, but Titles only looked up
sess_subagent_agent_<id> children, so a fork's Routing card fell back
to the folder name though its row has a title of its own.

The child index in Titles now holds every ZCode session with a parent,
by its sid and its bare id (zcodeBareID), so a fork is named from its
own file the way a subagent is. A top-level session is still named by
its own group only. The parent's title is unchanged.

Changed from the patch: the index holds child sessions only (the patch
indexed every ZCode session, so a top-level session's empty group title
could be filled from the cache fallback), and the "session_" prefix the
patch also stripped is dropped, since no ZCode id has it.

Run (mote, sandbox HOME via the package's TestMain):
- go test -tags nogui -run 'TestZCode|TestSessionTitles' ./internal/sessions/: ok.
- go test -tags nogui ./internal/sessions/: ok (20.7s).
- go test -tags nogui -run TestSessionTitlesNameOtherAgents ./internal/gui/: ok.
- GOOS=linux go vet -tags nogui and GOOS=windows go vet ./internal/sessions/: ok; gofmt -l clean.
- Windows box (win-run): -run 'TestZCode|TestSessionTitles' ./internal/sessions/: ok.
Broken by hand: with origin/main's sessions.go, TestZCodeForkTitlesByRequestID
fails: fork by request id: "", want "Fork of The parent session's title".
Not tried: a real ZCode database here (none on this machine); the
reporter ran the patch against theirs on Windows and got the fork's own
title and the parent's.

#5365, Flandern1211 (report, patch, test).

Co-authored-by: Flandern1211 <163982805+Flandern1211@users.noreply.github.com>
2026-11-06 09:54:05 +08:00
yetone ef176e21f6 sessions: a Claude Code session moved with /cd is listed under its new folder
usrname1833 on Discord (#feedback, 11-05): after Claude Code's /cd the
session's file is in the new folder's .claude/projects directory, while
magpie kept showing the session under the folder it was started in.

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

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

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

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

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

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

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

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

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

Reported by usrname1833 on Discord.
2026-11-06 07:32:04 +08:00
yetone 52563d1cdf sessions: a ZCode name poll reads its sessions' messages for their stamp, as the listing does (#5365)
226fc8ea3 lists ZCode's sessions for Titles from their rows alone, with
size 0 and the row's time_updated as the file's stamp. Two things followed
from that stamp:

- ZCode writes a message without touching its session's row, so a session
  still under its default title, first read before its prompt was in, was
  never named by that prompt while only the Routing page polled.
- The cache kept size 0 and the row's time, where the Sessions page's
  listing (zcodeFiles) keeps the message count and the last message's
  time, so each read the session whole again after the other.

zcodeTitleStamps gives the sessions a poll asks for (their key wanted,
subagents under it too) the same count and last activity, from a
COUNT/MAX over each one's own messages by session_id, not the join over
every session's. A session whose messages can't be read keeps its row's
stamp, as before.

Co-authored-by: Flandern1211 <163982805+Flandern1211@users.noreply.github.com>

Run (mote, via mote-run):
- go test ./internal/sessions -run TestZCode -count=1 at 226fc8ea3 alone:
  TestZCodeTitlesSeeNewMessages red (after the prompt: "") and
  TestZCodeTitlesKeepTheListingsStamp red (kept size 0 mod
  1790496000000000000, listing has size 3 mod 1790496030000000000). With
  this change both green. On origin/main 1b0340fdb both pass (the poll
  read the join), while 226fc8ea3's TestZCodeSubagentTitlesByRequestID and
  TestZCodeTitlesWithoutMessageTable are red there.
- go test -timeout 45m ./internal/sessions ./internal/gui -count=1: sessions
  ok; gui ok but TestMainWindowCorners/macOS_26_SDK, #3949 (mote is
  macOS 27), untouched here.
- GOOS=linux and GOOS=windows go vet ./internal/sessions: ok. gofmt clean.

Not tried: a real ZCode database (none on this Mac or the Windows box);
the per-session COUNT/MAX is not timed against the reporter's 1 GB one.
It filters message by session_id, as parseOpenCode's own reads do.
2026-11-05 17:53:42 +08:00