Commit Graph
318 Commits
Author SHA1 Message Date
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
Flandern1211 24e1a21095 sessions: list ZCode's rows, not its messages, for a title poll
Titles listed every agent's files, and zcodeFiles joins the message table to give each session its size and last activity. On a ZCode database of 1,022 sessions and about 1 GB of messages that join took ~20 s, while the Routing page asks again every 15 s: its cards showed the folder for a while, and a poll that came back empty dropped a name it had.

Titles now lists ZCode's sessions from their own rows (zcodeTitleFiles: id, parent, time_updated) and names them through the same assembleListed/parseOpenCode path as before. A ZCode subagent, which ocRoots files under its parent's key, is named from its own file's cached row when the key asked for matches no group.

Run:
- go test ./internal/sessions -run 'TestZCodeTitlesByRequestID|TestZCodeSubagentTitlesByRequestID|TestZCodeTitlesWithoutMessageTable|TestZCodeDefaultTitleFallsBackToFirstPrompt|TestSessionTitles|TestZCodeCalls' -count=1: ok.
- go test ./internal/gui -run TestSessionTitlesNameOtherAgents -count=1: ok.
- Broken by hand: with zcodeFiles (the message join) in place, TestZCodeTitlesWithoutMessageTable fails with an empty title; with the subagent fallback removed, TestZCodeSubagentTitlesByRequestID fails; with the sess_ alias removed, TestZCodeTitlesByRequestID fails.
- Real ZCode database on Windows: Titles for three live sessions went from 20.4 s to 780 ms cold and 74 ms warm; a ZCode and dsh poll took 80-160 ms.
- go build ./...: ok. The full sessions package has the same three Windows-only failures as before this change (TestAgySessions, TestAgyRowOnly, TestCCListingKeepsItsNames).
2026-11-05 17:53:42 +08:00
yetone d620ff6b54 codex: an old OpenAI thread follows Codex onto magpie by its row, and back at the Disconnect (Parry_Moody, Cyrus)
Parry_Moody and Cyrus on Discord: Codex on OpenAI through an API key
before magpie, and for two days the Codex app answered every older
conversation "继续聊天未成功: This chat uses openai, but your current
provider is magpie. Switch to openai to continue."

Cause, from Codex's source (rust-v0.167.0-alpha.3.1, same in 0.166.0):
every thread Codex 0.166 starts is paginated (history_mode 'paginated'
in its state-DB row), and for those thread-store read_thread takes the
provider from the row, never the rollout ("Paginated history may contain
only a suffix, so its display metadata lives in SQLite"). The app sends
thread/resume with modelProvider null (ChatGPT.app 26.1021, Kct in
app-shared), so the row alone decides, and load_for_resume refuses a row
other than the current provider. bringOver moved threads by rewriting
files: plain ones in place, packed ones only from the last 30 days and
128 MB a sync. An older or packed OpenAI thread kept an openai row.

Now sessions.RetagPagedCodexThreads moves every paginated thread on a
provider by its row alone: any age, packed or not, an id of any length,
no file read, written or copied. Each thread is held by its writer lock
(an open one stays: its writer would write the provider back), one
written to in the last minute waits, 200 rows a transaction. It runs
after the in-place relabel in bringOver, bringBack (so a Disconnect no
longer copies a whole paginated history to the trash), bringOfficial and
bringBeside, and giveBeside by ids (RetagPagedCodexThreadIDs). Legacy
threads keep the file path. The Sessions page lists a paginated thread
on its row's provider (codexPagedProviders, memoised on the DB and WAL
stamp), so it isn't offered a Move it had.

Run:
- real codex-cli 0.166.0 (npm latest) on mote in a sandbox CODEX_HOME,
  a fake Responses server: a thread started with OpenAI (API key,
  openai_base_url) is paginated, row openai; with model_provider magpie
  `codex exec resume` failed with exactly "This chat uses openai, but
  your current provider is magpie" (modelProviderMismatch). After
  magpie's RetagPagedCodexThreads on that home (a throwaway test calling
  it, not committed) it resumed and answered; the rollout still names
  openai. Reversed (magpie -> openai) with config back on OpenAI, it
  resumed again. The first retag try moved nothing: the rollout had been
  written <1 minute before, the ActiveWindow skip, as intended.
- mote: gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  for ./internal/sessions ./internal/agent; go test ./internal/sessions
  ./internal/agent: ok (sessions 20.1s, agent 194.4s) on mote, plus go vet on darwin, linux -tags nogui and windows

Broken by hand:
- RetagPagedCodexThreads returning nil (the old behaviour):
  TestCodexPagedThreadsFollowByRow red (250 packed 90-day-old threads
  "on openai, want magpie"), TestRetagPagedCodexThreads red.
- the writer-lock hold skipped: TestCodexPagedThreadsFollowByRow red,
  the open thread moved to magpie.

Not tried: the Codex app GUI itself (the app goes through the same
app-server thread/resume, whose modelProvider it sends null); Windows
and Linux runs (vet only). Codex rebuilds a row from its rollout when a
search listing reconciles it, which puts a retagged thread back on its
file's provider until the next sync; not seen, read from the source.
A legacy thread packed over 30 days still waits for Sessions' Move.
2026-11-05 16:11:14 +08:00
yetone 681a472cab agent: a Codex thread started during the takeover comes back to OpenAI once it is quiet, not hours later (nb5p on Discord)
nb5p on Discord (v0.1.3001, Codex app): after Send greyed out, Retry in
Codex did nothing. The model picker and Send spun, the same dialog came
back a few seconds later, and the model field read "model unavailable".

With the ChatGPT account Codex is signed in to used up, magpie makes
itself Codex's provider (codex.out), so a turn sent then starts a thread
saved with model_provider "magpie". When the account has room again,
Sync puts Codex back on OpenAI, and its deferred bringBack moves magpie's
threads to OpenAI. It skips a thread written to in the last minute,
which is the one the user was in, and leaves it "for the next Sync".
Nothing schedules one, though: Sync runs on a catalog change, which can
be hours away. The app then can't resume that thread on the provider it
is now on ("This chat uses magpie, but your current provider is
openai", the string still in the Codex the app bundles), so each Retry
failed the same way.

bringBack now asks whether a thread is still on magpie because it was
being written to (sessions.CodexThreadsBusyOn: the state databases' rows
on magpie whose rollout changed within ActiveWindow). If one is, it asks
for one more Sync after ActiveWindow+5s. Only one wait is pending at a
time.

docs/subsystems/agent-wiring.md says so beside bringBack.

Test: TestCodexTakeoverThreadComesBackOnceQuiet. The takeover is on, and
a thread on magpie is written to now. The account comes back, and the
thread stays on magpie while it is written to. A later Sync is asked
for, and that Sync, with the thread quiet, moves it to openai. No other
Sync is asked for after that.

Broken by hand: with the bringBack hook turned off (`if false && ...`),
it fails with "no later Sync asked for" (5.3s). Restored, it passes.

Run on mote at this tree (base 8eb219354, origin/main fetched, nothing
new):
- the new test with -race -count=3: ok;
- go vet ./internal/agent ./internal/sessions for darwin, for linux
  -tags nogui and for windows: clean;
- go build ./...: ok;
- gofmt -l: clean;
- go test ./internal/agent ./internal/sessions: ok.
The full suite at the pushed head is in the report.

Not tried: the real Codex app at the moment an account runs out and
comes back. The resume failure is read from the Codex source and the
string in the app's bundled codex, not seen live. A thread the app keeps
writing to for minutes on end waits one more round each time; that case
was not timed. Nor was a thread the app keeps open with its writer lock
held after it goes quiet: MoveCodexThreads refuses that one too, and
CodexThreadsBusyOn looks at the time only, so no further Sync is asked
for it.
2026-11-05 08:23:05 +08:00
yetone 83137bcbe9 sessions: TestCCListingKeepsItsNames counts the names' allocations, not Linux's stats (#4925)
Red on ubuntu CI at 4a9cfb52e (run 41865226839) and on the Linux box
alone: "listing 3000 unchanged files took 12159 allocations", bar 3n =
9000.

Cause: dirent.Stats reads a folder's stats in one call on macOS
(getattrlistbulk) and has no such call elsewhere, so on Linux statFiles
stats each file alone through statOne (os.Stat), two allocations a
file: 6000 for the test's 3000 files. The names are kept the same on
both systems. A probe of the second listing (not committed) gave Linux
12115 allocations, 6110 with statOne answered without allocating, and
macOS 6128 and 6124; one os.Stat is 2 allocations on each. The 3n bar
was set on macOS and charged Linux's stats to the names.

Change (test only): the measured listing's statOne is answered from a
table of os.Stat read before it, so what is counted is the listing's
own work on every system. The bar is unchanged.

What was run, at this tree on origin/main fd85c0a1e:
- Linux (wsl-run, magpie-desktop, go1.26.8, -tags nogui): the old
  test red, 12159 allocations. The new test ok. The new test with
  ccNames.of never taking the last listing's names (broken by hand):
  red, 12159.
- macOS (mote): the new test ok; with the names broken by hand red,
  12198.
- go test -count=3 ./internal/sessions: ok on Linux (-tags nogui) and
  macOS. gofmt -l clean; go vet, GOOS=linux go vet -tags nogui,
  GOOS=windows go vet of internal/sessions: clean.
Not tried: Windows (no bulk stat there either, so it would have been
red the same way; Windows CI only compiles tests).
Not changed: Linux still pays os.Stat's two allocations a session file
each poll; that cost is the system's stat, not this test's guarantee.
2026-11-05 01:08:08 +08:00
yetone 387b386c84 codex: threads of the provider an older beside wiring took down move to OpenAI (yikelizi9438 on Discord)
yikelizi9438 (Windows, the Codex app): models wouldn't load, "This chat
uses custom, but your current provider is openai. Switch to custom to
continue", and "Model unavailable" in the composer. "custom" is CC
Switch's provider id; magpie never names one so. Before #4347
(e02bc8c49, v0.1.2652) a magpie model picked beside the ChatGPT sign-in
took the user's model_provider down, kept in stash codex.provider for
the Disconnect, leaving Codex on OpenAI by openai_base_url. Codex 0.166
resumes a thread only on the provider it is on now
(modelProviderMismatch), so every thread started on custom was refused.
#4347 stopped new configs reaching that state, and d6e3a36ff moves such
threads only when magpie is Codex's provider, so a config already left
so stayed broken after the update.

Now Sync's bringBeside: with Codex on OpenAI routed by the base URL, no
top-level model_provider, and a provider of the user's in the stash
(not openai, magpie, cc-switch-official or a CC Switch OpenAI mirror,
none a profile names), that provider's threads move to openai as
bringOver moves them onto magpie: in place at OpenAI's length, the last
30 days rewritten with a copy kept otherwise. The ids moved are kept
(codex.brought). The Disconnect, which puts the provider back, returns
exactly those (sessions.MoveCodexThreadIDs, only ones still on openai);
OpenAI's own threads stay. If magpie becomes Codex's provider instead,
they go on to magpie (followBeside), where bringBack returns them at the
Disconnect. A reset forgets the record (Codex stays on OpenAI).

Run: TestCodexBesideBringsTakenProvidersThreads red on origin/main
f280b12e5 ("thread ... on \"custom\", want \"openai\""), green here
(mote-run). Broken by hand: with Unwire's giveBeside("") commented out
the test goes red at the Disconnect ("on \"openai\", want \"custom\"").
mote-run: gofmt -l clean; GOOS=windows and GOOS=linux go vet -tags nogui
of internal/agent and internal/sessions; go test -tags nogui
./internal/agent/ ./internal/sessions/ ./internal/gui/ ok (agent 282s, sessions 31s, gui 95s).
win-run (xiaomi-gpu): TestCodexBeside|TestCodexThreads|
TestMoveRecentCodexThreads|TestMovePackedCodexThreads ok.

Not tried: a real Windows Codex app with the reporter's config (their
magpie version and config.toml are unknown; if CC Switch itself switched
them to its official card, the stash has no provider and nothing moves:
the Sessions page's "Move to openai" does it by hand). The followBeside
path has no test of its own.
2026-11-04 23:16:23 +08:00
yetone d6e3a36ffc codex: threads of the provider Codex was on before magpie follow it onto magpie (hxy920830 on X)
hxy920830 on X: "magpie希望codex接入的时候自定义供应商名称,我现在名称被替换成了
magpie,原来的会话可以看到,但是加载不出来模型了". Codex had been on a
provider of the user's own (a relay's [model_providers.<id>] table, or CC
Switch's "custom"). Wired with no ChatGPT sign-in, magpie sets
model_provider = "magpie". bringOver moved only OpenAI's threads onto
magpie, so the relay's threads stayed on their provider. From Codex 0.166
(codex-rs app-server config_manager.rs load_for_resume) a thread resumes
only on the provider Codex is on now. The app lists them (thread/list
with model_providers [] lists every provider) but opening one stops at
modelProviderMismatch: "This chat uses <id>, but your current provider is
magpie". Nothing a user can set changes that, so a setting to rename the
provider wouldn't be needed. The threads should just open.

bringOver now moves the threads of the provider Codex was on before magpie
(stash codex.provider, "openai" when none was set), not only OpenAI's:
- an id of magpie's length ("custom") is relabelled in place
  (RelabelCodexThreads), then packed ones from the last 30 days
  (MovePackedCodexThreads), as OpenAI's already were;
- any other id ("myrelay") can't be written in place, so the threads of
  the last 30 days, plain or packed, are rewritten with a copy kept in
  the trash, newest first, 128 MB a sync (new
  sessions.MoveRecentCodexThreads, sharing MovePackedCodexThreads' body
  with packedOnly off). Older ones are left for Sessions' Move/Resume.
#887's guarantee still holds where it matters. Threads of any other
provider stay put. OpenAI's stay when Codex was on another provider. No
threads move for a provider a profile names (the user picks it with -p),
for cc-switch-official (bringOfficial handles it), or for a distro's
Codex. The Disconnect puts the user's model_provider back and bringBack
returns the threads to it, and CC Switch switching back to that provider
does the same. If Codex leaves magpie for a different provider,
bringBack hands them to that one, as it already did with OpenAI's moved
threads. profileNamed moved up so bringOver can use it.
docs/subsystems/agent-wiring.md says so.

Tests:
- TestCodexThreadsFollowMagpieIn "on a provider of the user's before"
  used to assert that the custom thread stays. Now it moves to magpie in
  place, with no copy, and goes back to custom at Unwire, with
  model_provider custom restored.
- New subtest "on a relay's table of another length": myrelay's plain
  and packed threads move with a copy kept, a 40-day-old one stays,
  OpenAI's stays, and everything goes back at Unwire.
- New subtest "on a provider a profile names": the thread stays.
- New TestMoveRecentCodexThreads: newest first, a copy each, an old
  thread and another provider's stay, and the packed-only move still
  leaves a plain thread.

Run at this tree (on origin/main 823e7c250), on mote through mote-run:
- gofmt -l internal/agent internal/sessions: clean.
- GOOS=windows go vet, GOOS=linux go vet -tags nogui and go vet (darwin)
  of ./internal/agent ./internal/sessions: ok.
- go test -count=1 -timeout 45m ./internal/agent ./internal/sessions: ok
  (296s, 85s). An earlier run before the last tweak (plain file must be
  regular) was ok as well.

Broken by hand:
- bringOver back to OpenAI-only plus packedOnly forced: three of the four
  new assertions in TestCodexThreadsFollowMagpieIn and
  TestMoveRecentCodexThreads fail ("thread ...c3 on "custom", want
  "magpie"", "moved [only the packed one], want the plain then the packed
  one").
- the profileNamed guard dropped: "on a provider a profile names" fails.

Not tried: a real Codex 0.166 app or CLI resuming a moved relay thread
(this reasons from the codex-rs source for rust-v0.166.0, and earlier
commits record real 0.166 resuming moved threads); a real CC Switch
switch; the whole ./... suite (mote was at load ~75-100 with two other
sessions' full suites); a Windows or WSL run.
2026-11-04 22:52:05 +08:00
yetone 532d054bee sessions: every Cursor row has a delete, and the right-hand column lines up
ysm119 (Discord), Sessions page, Cursor tab: some rows had a delete and
some had none, and the time / "N sessions" column stood at a different x
from row to row.

Causes:
- Delete: listAgentWith set Deletable = Deletable(agent) && !ReadOnly, so
  every editor-transcript row (read only) came back deletable:false, and
  client.js drew .sm-del only for deletable rows.
- Alignment: a folder adds its ⋯ only when it has actions, and a session
  row's Resume / terminal / Continue in / delete come and go per row, so
  .sm-when, .cost and .num moved with them. "Copied" is wider than
  "Resume", and at <=600px the cost line wrapped at different places.

Change:
- rowDeletable decides per row. An editor transcript the editor no longer
  keeps (no state.vscdb, or it was read and has no composer for that id)
  is "loose" and deletable: Delete trashes only its <id>/ folder or
  <id>.jsonl/.txt, never state.vscdb. A chat the editor keeps, or a store
  that can't be read, stays undeletable with undeletable:"cursor-editor".
- In an agent magpie deletes from, every row has its delete. One it can't
  delete is aria-disabled, says why in its title, and a click shows the
  reason in the status line and sends nothing (en, zh, zh-TW, ja, de).
- A row without Resume, Continue in or a terminal, and a folder without
  its ⋯, keep that room with an inert, aria-hidden slot. Resume reserves
  the wider of Resume and Copied; at <=600px the cost keeps a min width.
- docs/subsystems/gui-shell.md says so.

Run (on mote via mote-run, base f44fa2ef6; origin/main 93d5c76c0's 3
commits since touch none of these files):
- go test ./internal/sessions: ok. go test ./internal/gui: ok except
  TestMainWindowCorners/macOS_26_SDK, an AppKit titlebar red on macOS 27
  already filed as #3949.
- gofmt -l clean; go vet native, GOOS=linux -tags nogui, GOOS=windows ok.
- New sessions-cursor-align.test.cjs: 10/10 (chromium + webkit x en, zh,
  zh-TW, ja, de; widths 1100/660/420, hover, Copied).
- Sessions GUI set (sessions-*, session-*, gateway-conversations,
  gateway-mode-sessions, account-mask-sessions, header-session-hint,
  routing-session*, routing-ctx-sessions, usage-session*, i18n-keys,
  gui-de, gui-ja, gui-zh-tw): 728/728, and 728/728 again after the
  rebase onto 93d5c76c0 (which changed app.css and i18n.js).

Broken by hand:
- rowDeletable forced to "read only": all 3 new Go tests red.
- sessionPaths' editor-path branch off: TestCursorLooseFlatTranscript red
  (it trashed agent-transcripts/ itself).
- Old client.js/sessions.css/i18n.js: new GUI test 10/10 red. Folder slot
  alone removed: red at 1100 (when 1071 vs 1037). Lanes removed: cost
  edges differ. Before the Copied and de 420 fixes, those cases were red.

Not tried: a real Cursor editor or a real ~/.cursor (every delete ran on
fixture copies in a sandbox HOME); the Windows and Linux apps; deleting a
chat from Cursor's own UI and seeing magpie's list follow.
2026-11-04 21:15:33 +08:00
yetone f44fa2ef6a sessions: gateway mode lists only the gateway's sessions, never this computer's agents' files
paultian on Discord: magpie web in gateway mode, on a machine with Claude
Code and Codex installed, listed that machine's own sessions beside the
ones other computers sent through it. Owner's call (via the lead): keep
Sessions in gateway mode, scope it.

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

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

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

Not tried: a real magpie web on a server with real agents on other
computers; the Go test on Windows and Linux boxes; the 30s memo under
real use.
2026-11-04 20:20:41 +08:00
yetoneandFlandern e7b0c398ee sessions: find a ZCode title by its gateway id (#5195)
ZCode sends its session id to the gateway without the sess_ prefix stored
in its database. Routing asks Titles with that bare id, gets no title, and
falls back to the folder name even though the Sessions page can show the
real title.

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

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

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

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

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

Co-authored-by: Flandern <3180066912wzw@gmail.com>
2026-11-04 18:33:07 +08:00
yetone 0ee424e3ee codex: a thread Codex 0.166 won't resume for its provider moves with Codex (毅, AcMilan on Discord)
Codex 0.166 (openai/codex#57840) refuses to resume a thread whose saved
provider isn't the configured one: "This chat uses openai, but your
current provider is magpie. Switch to openai to continue." (毅), and
"This chat uses cc-switch-official, but your current provider is
openai" (AcMilan). The rollout's session_meta provider wins over the
state DB row, and no -c override gets past it (openai/codex#58865).

Cause on magpie's side: bringOver relabelled only plain rollouts in
place. A thread Codex had packed to .jsonl.zst (a week after its last
turn) stayed on openai, so with magpie as provider it can't resume.
cc-switch-official is the id CC Switch 3.17-3.20 gave the official
account; CC Switch 4 moves those threads back to openai itself (#7948
there), but a user who left CC Switch keeps them stranded.

- sessions.MovePackedCodexThreads: packed threads on `from` updated in
  the last 30 days, newest first, up to 128 MB per sync, each moved by
  the existing packed rewrite with its copy kept in the trash. Rows
  are checked against the file (plain absent, .zst present, meta on
  `from`, same home). A state DB without updated_at moves nothing.
- bringOver calls it after RelabelCodexThreads; bringBack already
  moves packed threads back.
- bringOfficial: while magpie wires Codex and Codex is on openai or
  magpie, cc-switch-official threads move there, unless the user's
  top-level model_provider or a profile names cc-switch-official.
- Other providers and packed threads older than 30 days are left; the
  Sessions page's Move or Resume takes them.

Run (mote, at the pushed base c7bbd3faf):
- gofmt -l clean; go vet darwin, GOOS=linux, GOOS=windows on
  internal/agent and internal/sessions: ok.
- go test ./internal/agent ./internal/sessions: ok.
- Real codex-cli 0.166.0 app-server in a sandbox CODEX_HOME with a
  fake Responses server: an openai thread packed, Codex on magpie,
  thread/resume gave 毅's error word for word; RelabelCodexThreads
  alone left it; after MovePackedCodexThreads the resume said
  provider magpie and a turn started. A cc-switch-official thread with
  Codex on openai gave AcMilan's error; after the move it resumed on
  openai and a turn started.

Broken by hand (each red, then restored):
- budget check off: TestMovePackedCodexThreads red (both moved).
- the packed call in bringOver removed: TestCodexThreadsFollowMagpieIn
  red (packed thread stayed on openai).
- defer bringOfficial removed: TestCodexMovesCCSwitchOfficialThreads red.

Not tried: the Codex App GUI itself; agent Sync against a real Codex
(unit tests only); Windows and Linux runs; threads on other provider
ids, which 0.166 also refuses (left to the Sessions page).
2026-11-04 15:12:08 +08:00
yetoneandSKYhuangjing 2741b749f9 sessions: a codex fork's rollout-<n> turn does not end the copied head (#5090)
ownTurn ended a Codex fork's copied head at the first turn id the parent's
file didn't hold (fb1f4856a). codex-rs names a turn that has no id of its
own "rollout-<n>" (the rollout canonicalizer's implicit turns; the
thread-history builder), and a copied head can carry one the parent's file
lacks. It was taken for the fork's first own turn, so every copied
checkpoint after it was booked as the fork's call: July and August usage
that was the parent's history over again. Reporter: SKYhuangjing, whose
fork branch codex-fork-head-marker (acb034645) this ports.

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

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

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

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

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

Co-authored-by: SKYhuangjing <13705011+SKYhuangjing@users.noreply.github.com>
2026-11-04 09:10:52 +08:00
JoeyWu-tech 55a190f195 gateway: conversations opened on one fixed message no longer share an id (#3938)
keeyangyy (#3938): with no session header, conversationID named a
conversation by the raw bytes of its first user message alone. Some
agents open every conversation on a message they write themselves and
send what the user typed as the next user message:

  {"role":"user","content":"<environment_context>cwd=/w/proj ...</environment_context>"},
  {"role":"user","content":"the question the user actually typed"}

That message is the same in every conversation started in one folder,
so all of them had one id: under Stays = session each new one was kept
on the account that answered the first, and rotate never moved on.

conversationOpening now says what is hashed, from the first user
message on (Chat and Anthropic messages, Responses input, Gemini
contents, where an omitted role is the user's):

- A first user message that holds anything of the user's own is hashed
  alone, as the request has it, exactly as before: their words
  (userWords, which already tells an <environment_context> or
  <user_instructions> block or an instruction file from what the user
  typed), an image, a file or a recording (userOpens). So is one that
  holds a tool's result.
- One the agent wrote alone is hashed with the user messages after it,
  in order, through the first that holds the user's own. A system or
  developer message between them is passed over.
- A reply, a call, its output, reasoning, a tool's result (Gemini's
  function result too), an item without a role (Chat, Responses) or
  one that can't be read ends the opening. With nothing of the user's
  before it, the first message is hashed alone, as before.

Every later turn repeats the opening before the first reply, so the id
holds through the conversation. A Responses input that is one string
is hashed as before.

An opening of several messages is hashed as writeOpening reads them,
one after another: every object's members in key order with no space
between, no cache_control at any depth, and a content of one text part
as that part's text. An agent marks its newest user message for the
cache and moves the mark on next turn, so the typed message's bytes
change at turn 2; some spell a marked message as a list of one part and
an unmarked one as a plain string (dsh does). Hashed as sent, an
opening of several would get a new id at its second turn, and on
/v1/messages under rotate that turn would go to the other key as a new
conversation (below). writeOpening reads the messages where they are:
the id of a 1.1 MB body whose opening holds a screenshot allocates
about 10 KB (TestOpeningHashReadsInPlace).

Every conversation whose first user message is the user's own keeps
the id it has, so no stick record needs moving. One that opened on an
agent's message and is under way when this lands gets an id of its own
on its next turn and is routed once as a new conversation: it may move
to another account, and its cache there starts over. The record they
all shared stays under the old id.

A tool's result (Anthropic clients send it as a user message) ends the
opening: it answers a call the model made, so the opening is over. A
history that starts with one was cut by its client (magpie takes such
orphans, TestMessagesOrphanToolResultWithoutACallBecomesText). Its
opening is gone, and whatever was taken in after the cut would move the
id each time the client cuts again, so its first message is hashed
alone, as before.

Not the issue's "first two user messages", nor every user message up
to the first reply: in an ordinary conversation the second user message
is the next turn, so the id would move when it arrives, and every
record would need the migration the issue describes. And a run of
every user message takes in what dsh sends after the typed prompt, its
runtime context, where the Context page finds dsh's sessions by the
typed prompt's hash alone; TestDshSessionConvsAreTheGatewayIDs and
TestDshRoutesCarryTheSessionConvs go red under such a run (below).

What reads the id moves with it: stickKey (session, turn and strict
affinity, and rotate's spread of new conversations), the Routing
trace's conv (convOf), a sealed task's lead (leadProvider,
loggedAnswerers), extraBody's ${sessionId}, Kilo's task and session
headers (KiloClient), X-Magpie-Conversation to plugins and OpenCode's
x-opencode-session fallback (openCodeSeed). A group rule's key reads
conversationID without a body, beside firstWords, which already passes
over the agent's blocks, so it doesn't change. One reader rebuilds the
id itself: sessions' dshConvs, which the Context page joins dsh's
sessions by (joinConvs). It hashes dsh's typed prompt, a first user
message of the user's own, which is still hashed alone, so its ids stay
the same. Nothing else in sessions, gui or elsewhere rebuilds a
"magpie-" id. The comments that named the first user message, and the
Gateway routing and Providers and accounts pages, say what the id is
now.

Siblings left for a decision, each in an issue filed with this
patch: #3988, ChatGPT accounts (conversationKey in
internal/provider/codex_request.go, for a client that sends no
prompt_cache_key), and #3989, Antigravity accounts (antigravitySession
in internal/provider/google.go). Both hash the first user message in the
provider package, and userWords is the gateway's.

Not changed: a fixed first message that userWords doesn't read as the
agent's is still hashed alone, so the conversations an agent opens on
it still share one id. A first user message hashed alone is hashed as
the request has it, cache mark and all, so a client without a session
header that marks that message on its first turn only gets a new id at
its second, as before. An agent that answers its own first message
with a fixed reply before the user's turn ends the opening at that
reply, so its first message is hashed alone too.

What was run (tree 523c770b, on origin/main a5315c70, go1.26.8,
linux/amd64, Linux 5.15), outside graftcp, umask 077:
- This commit's tree alone: not run. It is a6037f68 rebased: its
  internal/ diff is the same (one patch-id), and
  docs/subsystems/gateway-routing.md was merged by hand beside main's
  new One try row. At the next commit's tree (71364f08), which adds a
  line to userWords' list and tests: this commit's tests, every break
  below again, -race, vet and the full suite, recorded in the next
  commit.

The rest is what was run for a6037f68, at tree e8fc1eee on origin/main
e9dd8e83, the same code (not this tree):
- New: TestConversationsOnOneEnvironmentMessageAreApart, on Chat,
  Messages, Responses and Gemini bodies, the last with and without
  roles. The issue's two conversations from one folder get two ids,
  neither the environment message's own, and each keeps its id on its
  next turn. A conversation that opens in the user's words has
  "magpie-" and the hex of sha256(its first user message)[:12], alone,
  on a later turn and with the agent's message after it. A screenshot
  after the agent's message opens a conversation as words do. A
  developer or system message between them doesn't move the id. dsh's
  turn, its runtime context marked for the cache, has the typed
  message's own. A history cut at a tool's result keeps its first
  message's own, and so do these after the agent's message: a tool's
  result, a Chat message without a role, a Responses call, its output
  or reasoning, and a Gemini function's result, in a user content or
  in its own role. A Responses string input is hashed as before.
  TestCacheMarkMovingOnKeepsTheID: the issue's opening on Messages,
  Chat and Responses, the mark on each turn's newest user message,
  turns 1, 2 and 3 with one id, the typed message going on unmarked as
  one part, as a plain string or with a screenshot, and on Chat marked
  on the message itself. TestOpeningHashReadsInPlace: the 1.1 MB body
  above under image_input_test.go's bar of an eighth of the body.
  TestNewConversationsInOneFolderAreRoutedApart: two keys, rotate,
  Stays = session, no session header. On /v1/chat/completions the two
  conversations are each "first", on different keys with different
  convs, and each next turn stays on its key as "session" with its
  conv. On /v1/messages a third conversation, its mark moving on, is
  "first" and turns 2 and 3 stay on its key as "session" with its conv.
- Broken by hand, each red:
  - back to the first user message alone (the old rule):
    TestConversationsOnOneEnvironmentMessageAreApart on all five bodies
    ("two conversations opened on one environment message": one id, the
    message's own; and the screenshot case),
    TestCacheMarkMovingOnKeepsTheID (each of its ten first turns the
    environment message's own),
    TestOpeningHashReadsInPlace ("the environment message was hashed
    alone") and TestNewConversationsInOneFolderAreRoutedApart (the
    second conversation on k1 as "session", with the first's conv).
  - every consecutive user message, unread: the five bodies' cases
    with the agent's message after the user's, the screenshot cases,
    dsh's two turns, the cut history, the tool's result after the
    agent's message and Gemini's function result in a user content,
    and TestDshSessionConvsAreTheGatewayIDs and
    TestDshRoutesCarryTheSessionConvs (the turn's conv not among the
    session's).
  - a tool's result taken into the opening, and passed over like a
    developer message: the cut history, the tool's result after the
    agent's message and Gemini's function result, each way.
  - a system or developer message ending the opening: the Chat and
    Responses pairs.
  - an image, a file or a recording not counted as the user's: the
    screenshot case on all five bodies.
  - an item without a role passed over like a developer message: the
    Chat message without a role and the Responses call, output and
    reasoning.
  - Gemini's functionResponse not read as a tool's result: its case.
  - an opening of several hashed as sent:
    TestCacheMarkMovingOnKeepsTheID at turns 2 and 3 in all ten
    spellings, and on /v1/messages turn 2 went to k2 as "first" with a
    new conv, where turn 1 was on k1.
  - cache marks kept: the screenshot spellings and the message marked
    on Chat, at turns 2 and 3 (a one-part content is read as its text
    either way).
  - a content of one text part not read as its text: the three plain
    string spellings at turns 2 and 3.
  - each string copied before it is hashed: TestOpeningHashReadsInPlace,
    2,233,788 bytes an id.
- With their neighbours, -v: TestConversationID, the Dsh tests in
  gateway and sessions, TestContextDshSessionTitles,
  TestImageWalkReadsTextOnlyTurnsInPlace, the orphan tool result tests,
  TestClaudeConversationKeepsItsAccountsCache, and the affinity,
  rotate, strict, sticks, session route, OpenCode, extra body,
  WorkBuddy session and gateway conversation tests: 115 tests in
  gateway, sessions, gui and provider pass (154 with subtests).
- -race -count=5: TestConversationsOnOneEnvironmentMessageAreApart,
  TestCacheMarkMovingOnKeepsTheID,
  TestNewConversationsInOneFolderAreRoutedApart, TestAffinity,
  TestRotateSpreadsSessions, TestRotateSpreadsABurstOfNewConversations,
  TestGeminiFallbackSessionAffinity, TestSticksWrittenBehind, the three
  TestStrictAffinity tests, the two dsh conv tests and
  TestClaudeConversationKeepsItsAccountsCache: 14 tests, 5 of 5 each.
  -race -count=3: TestOpeningHashReadsInPlace and
  TestImageWalkReadsTextOnlyTurnsInPlace, 3 of 3 each (the id under
  -race: 17 to 32 KB).
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  build -tags nogui for linux and darwin, and go vet and go build for
  windows without the tag: exit 0 each. go vet and go build without
  the tag on linux: exit 1 (this box has no GTK or WebKitGTK dev
  packages).
- go test -tags nogui -count=1 -timeout 45m ./... (tools/suite.sh, Bun
  1.4.2, log kept; 8m23s, load 21 at its start): 71 packages ok, 5
  red, none in what this changes: agent TestInstalledVersion,
  TestCursorFolderFromTheEditorIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath (#3141), TestCodexDriftReached (#3398) and the two
  Reasonix tests (#3641); edit TestWriteAtomicReadOnlyHardLink and
  testenv TestProgram (umask 077, #3640); gateway
  TestPluginToldWhereTheAgentWorks (#3675), the package ran to its
  end, so the new tests passed in it too; gui
  TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie
  (#3649).

Not tried: keeyangyy's own client, or any real agent end to end.

Batch run, at tree 104d75f0a (the twelve coffemon ports together, on
origin/main 7d022bdb6), mote, macOS, go1.26.8:
- go test -tags nogui -count=1 -timeout 45m on the packages the batch
  changes (agent, autostart, daemon, gateway, library, proc, provider,
  sessions, testenv, tui, gui): ok each.
- GUI, node --test with Playwright 1.62.0, Chromium and WebKit:
  library-*.test.cjs and i18n-keys.test.cjs, 1044 of 1044 pass.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... and go build ./...: ok at cdd7c8e46, the same
  batch on origin/main 00098f12b one rebase before.
- The whole go test ./... at cdd7c8e46: 86 packages ok, one red,
  internal/cli TestEveryRouteHasACommandOrIsNamed (GET
  /api/context/reply has no command), red on main too (#5026).
- Linux (wsl-run, Ubuntu 24.04, at 339055896, the batch on f4c664a09):
  proc, autostart, testenv, tui ok; agent: only TestGrokInstalled red
  (#3548); #4033's proc.Look reds (Zed, Copilot, Qoder, Cursor, Omp)
  pass.
- Windows (win-run, Windows 11, at 339055896): proc, autostart, testenv,
  tui ok; library and agent red in the same tests as on origin/main
  f4c664a09 (#4115, #1827, #4786; #5068, #5069, #5070 filed now).
- Rebased onto origin/main fb1f4856a (three commits, no file in
  common with the batch) and run again at the pushed tree: gofmt -l
  nothing, go build ./... and go vet ./... ok; go test -tags nogui
  sessions, agent, autostart, tui, proc, testenv ok; i18n-keys and
  library-* 1044 of 1044 pass.
- Not run before the push: the whole GUI suite (a run at cdd7c8e46 was
  cut off at 1170 of ~1174 tests when mote rebooted; it runs again after
  the tag and any red is filed).
2026-11-03 20:38:11 +08:00
yetone fb1f4856a8 sessions: a fork's own calls are counted; only its copies are the parent's (ZCode, Codex)
Sky (skyhuang1994) on Discord, on their real ZCode database after
v0.1.2847 (1d0fc2bb0): September's message table holds 57,787 rows,
13.552B tokens; 5,204 rows (1.537B) carry a forkOrigin and are copies,
and ZCode's cloud usage says 12.057B. The new version took 5.094B out,
3.6B of it real. The biggest was the "msc" session: forked at the end of
August, then 11,409 calls of its own in September (3.489B), none with a
forkOrigin, a custom-UUID provider. The Usage page had 0 of them.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Not tried:
- a real ZCode database or side chat. There is none on this machine.
  The copy shape was read from ZCode 3.17.2's zcode.cjs (gce).
- a real forked Codex rollout or one from 2026-03. ~/.codex/sessions here
  spans 2026-07 to 11 and has no forks. The fixtures follow codex-rs
  0.117's writer. Whether Sky's 5.1B week is all fork copies is not
  known; a cumulative count read as per-turn in an older format was not
  found in that source.
- newer rollouts' token_usage_record copies in a fork, and a parent in
  another Codex home (WSL, CODEX_HOME).
- the whole gui and gateway suites. Another session's suite was running
  on mote; gui and cli ran only the tests above.
2026-11-03 19:13:00 +08:00
yetone 78cd4e6dd4 sessions: a call through magpie in Cindy is counted once, as the gateway's (jealousy03888)
jealousy03888 on Discord: "cindy里用Zcode订阅 同一个请求两个记录是特性吗".
Their Routing list had one ZCode GLM-5.3 request twice: the gateway's row
(ZCode · api.z.ai, 135/37/84,736 tokens, ~$0.026) and five seconds later
a "local session" row on the provider "magpie-beedee1a" with the same
tokens and cost, so Usage and the Requests totals counted it twice too.

Cause: Cindy's import parser gives a custom provider the link's id plus
eight hex digits of a new UUID (`${id.slice(0,24)}-${randomUUID()
.slice(0,8)}`, read in Cindy 0.1.94's app.asar), so magpie's link (id
"magpie") becomes "magpie-<8 hex>", and Cindy's Pi writes that id on
every reply. The Pi reader left out only "magpie"/"dial", so Cindy's
calls through magpie were read as Cindy's own beside the gateway's.

Now piGateway(agent, provider) also takes "magpie-" + eight lowercase
hex digits as magpie's entry, in Cindy's files only (Pi's own and omp's
providers are named by the user; magpie writes "magpie" there). A
provider the user adds by hand in Cindy under the name Magpie gets the
slug "magpie" or "magpie-2", never this shape. callParseVersions raises
cindy to 1, so Cindy's call shards written before are read again once
on update and the duplicates already shown go away (usage's request and
heat caches key on CallCacheVersion, so they are rebuilt too); no other
agent's shards are re-read.

Every other agent's reader was checked for the same gap (an id the app
chooses rather than magpie): OpenCode and ZCode ("magpie", written by
magpie), dsh (magpie's three route names), MiniMax Code
(custom_provider:magpie), Kimi ("magpie/" model prefix), WorkBuddy and
CodeBuddy (models.json vendor magpie), Grok Build (its config.toml
tables), Pi, omp and Raft (models.json "magpie"), Claude Code, Codex
and Antigravity (paired with the gateway's rows by session, response id
or tokens and time). Cindy is the only one whose provider id is made by
the app; Lody and AionUi also import a link but their sessions aren't
read.

TestCindyGatewayCallsCountedOnce puts a Cindy Pi session shaped like
the report (provider magpie-beedee1a, zcode/GLM-5.3, 135/37/84,736,
durationMs 5292) and a reply on a user's own "magpie-relay" into
Cindy's session folder; the first must not be a call, the second must
be one. TestCallParseVersionRaiseReadsThatAgentAlone now restores the
real versions after it.

Run (on mote): gofmt -l internal/sessions (nothing); go vet;
GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; go build
./... all ok. go test -tags nogui -timeout 45m ./... at 40a287b21+this:
86 packages ok, internal/cli red on two filed reds outside this change:
TestEveryRouteHasACommandOrIsNamed (GET /api/context/reply, #5026,
red alone too) and TestLibraryMCPHub (#4140, passes alone). Rebased on
c3593dc49 (no sessions or usage change between) and run again at the
pushed head: internal/sessions ok, internal/usage ok.

Broken by hand: piGateway's Cindy branch replaced by `return false`:
TestCindyGatewayCallsCountedOnce FAIL ("a call through magpie's link in
Cindy counted as Cindy's own: ... Upstream:magpie-beedee1a ...").

Not tried: a real Cindy session through magpie (none on this machine;
the shape is from Cindy's source and the reporter's screenshot); the
Sessions overview's session count for Cindy, which counts sessions,
not calls, and was not changed.
2026-11-03 18:15:07 +08:00
yetone c28220a5e7 sessions: a Codex thread saved on another provider resumes from Sessions
mrten_95615 on Discord: opening a Codex session from Sessions ran
`codex resume <id>` and Codex 0.166 stopped at "This chat uses custom,
but your current provider is magpie. Switch to custom to continue."
(modelProviderMismatch). Codex 0.166's app-server resumes a thread only
on the provider it was saved with (its state-database row, else its
session_meta), checked against the one config.toml (with -c) selects
(codex-rs app-server config_manager.rs load_for_resume); no flag lets a
resume go on another provider, and a provider config.toml no longer has
fails as modelProviderNotConfigured. Codex 0.165 resumed it on its own
provider without asking.

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

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

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

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

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

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

Not tried:
- The reporter's screenshots, which we couldn't download, so their list
  may be another one.
- A real WorkBuddy AI install.
- The Agents page's detection of a newer, renamed WorkBuddy AI bundle
  (5.9.3).
- Windows.
- WORKBUDDY_CONFIG_DIR set: both apps then use that folder, and its
  sessions are listed as WorkBuddy's.
- No GUI JS changed (the page reads the agents from the API), so no
  Playwright files were run.
2026-11-03 08:54:40 +08:00