Commit Graph
18 Commits
Author SHA1 Message Date
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 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 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 68b31ce236 sessions: a poll's file lists, merges and copy groups are made once (#2278)
Each Sessions or Usage poll listed every agent's files several times and
copied the Claude Code and Codex lists twice: callFilesWith made a
deduplicated slice and set, then callSourcesWith and allFiles appended to
it and deduplicated it again. Now callFileLists hands out the lists, and
distinctOf builds one slice and one set at their combined size.

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

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

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

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

Run at this head, on mote:
- GOOS=linux, windows and darwin go vet -tags nogui ./internal/sessions/
  ./internal/usage/ ./internal/gui/: ok.
- go test -timeout 45m ./internal/sessions/ ./internal/usage/
  ./internal/gui/: sessions and usage ok. gui red only on
  TestMainWindowCorners/macOS_26_SDK (#3949, open, red on macOS 27); this
  touches no GUI file.
2026-10-30 06:00:55 +08:00
yetone 905166d786 sessions: Codex identities are kept while no rollout changes (#2278)
Every Sessions and Requests poll built the Codex thread identities again
over every rollout (CodexIdentities, CallSourcesAndCodexIdentities, List,
Stats, ListAgent, Get), though nothing had changed since the last poll.
codexIdentitySnapshot now keeps the identities it built for the last four
file lists, with what each Codex rollout gave them from: its key, the
cached identity's value and whether it conflicts. A list whose rollouts
give the same is handed the kept map. The maps are now shared, so only
read: CodexIdentities' comment says so, and the old test that deleted from
one is replaced by TestCodexIdentitiesKeptWhileNoRolloutChanges.

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

Not run: the full suite and the GUI suite (no GUI change).
2026-10-29 07:08:23 +08:00
yetone 7e58591dcf sessions: Grok Build's tool calls and skills are counted (MaxMooreMy on X)
MaxMooreMy on X, after v0.1.1870 counted Codex's skills: "grok build 好像
也不支持。grok build 的工具调用啥的也没采集到". Usage > Sessions showed no
tool use and no skills for Grok Build.

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

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

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

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

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

Not tried: skills from Grok plugins/marketplace (installed-plugins was
empty here, layout unknown), so a /<plugin skill> isn't counted; a /name
skill whose folder was deleted since isn't counted when the file is read
again; the TUI (only headless grok -p sessions were captured); Windows
and Linux runs of the Grok CLI.
2026-10-28 20:28:27 +08:00
yetone 1feee38d17 sessions: Codex's skills are counted, from its reads of their SKILL.md (MaxMooreMy on X)
MaxMooreMy on X: "magpie的skill调用统计是不是坏了。用了一天,一个都没统计到".
The screenshot is Usage → Sessions, Codex (gpt-6-astra), 10 sessions,
Tool use "exec 488": Top skills says no skill was called up.

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

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

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

Not tried: the GUI against a live magpie (the page only shows what
Overview returns; app.js unchanged, so no GUI suite run); a SKILL.md read
through tools the rule doesn't know (a plugin's own read tool) and a
skill whose SKILL.md sits in a nested folder (clawra-selfie/skill/
SKILL.md counts as "skill"); internal/gateway and internal/agent, which
import sessions for other things. Other agents with no skill count
(Droid, Kimi Code, Hermes, Cursor, Antigravity) have no real session
here to build from: #4037.
2026-10-28 17:34:27 +08:00
yetone 22a7f86c9b sessions: the Requests page walks the Codex folders once a rebuild
readRequestState asked CallSources and then CodexIdentities, and each
walked ~/.codex/sessions and archived_sessions, lstat()ing every
rollout. Over the 12,069 rollouts of a real Codex folder that was two
walks of ~75ms on every rebuild, which runs on each 5s refresh while
an agent works. CallSourcesAndCodexIdentities walks once and hands the
list to both; CallSources and CodexIdentities stay as they were for
their other callers.

Run at this head:
- go test -timeout 45m ./internal/sessions ./internal/usage
  ./internal/usageapi: ok. TestCodexIdentityParentChainsAndSummaryCache
  now checks the one-walk pair equals CallSources and CodexIdentities.
- GOOS=linux and GOOS=windows go vet -tags nogui on both packages, gofmt.
- Real data (sandbox HOME over the owner's ~/.codex, 12,069 rollouts,
  ~416k rows): CPU profile of two rebuilds, codexFiles 0.31s before,
  0.12s after. Wall times on a loaded machine were 1.0-2.1s both ways,
  too noisy to compare.

Not tried: Windows or WSL folders (wslFiles is still walked as before).
2026-10-25 04:07:20 +08:00
yetone c381e4cd1e sessions: a read is never held by another read's refresh, only by a change to the files (#2776)
A read of the sessions (List, Stats, Manage, the agents' lists, Codex's
threads) took dbReadMu, a plain mutex, for the whole call, parse
included. The start's warm-up reads every session file with a quarter of
the cores, so the first pages and API calls after a start waited for its
whole read before they could even look at the cache.

- dbReadMu becomes storeMu, an RWMutex: reads take it shared, and only
  the changes to the files (Delete, a Codex provider move, a Claude
  project relocation) take it alone.
- A file another refresh is reading now is in `parsing`, with a channel
  closed when its parse is in the cache. A second read serves the parse
  it already has of such a file, and waits only for one it has never
  read; it never reads the same file twice at once.
- Each parse is published as it finishes, not in checkpoint batches, so
  a waiting reader gets it at once.
- The shared store handles (OpenCode, Hermes, Alma, Cursor) closed at the
  end of every read; with reads overlapping, one could close a handle
  another still used. They now live as long as their last user
  (useDBs). get() and the titles path closed them without the lock at
  all before.

Tests (internal/sessions/refresh_shared_test.go), each broken by hand:
- TestReadNotHeldByAnotherRead: the warm-up's parse of 12 grown files is
  held; List and Manage answer within 10s from the kept parses, each file
  is parsed once in all, and a later List parses none. With storeMu.Lock
  in List: red, "List waited for another read of the same files to end".
- TestReadWaitsForAFirstReadUnderWay: a file never read is waited for,
  not served empty, and read once. Without the waits: red, "List answered
  without the files being read". Without the skip of a file being read:
  panic, close of nil channel.
- TestStoresLiveAsLongAsTheirLastUser: with the release always closing:
  red, "closed while a read still used it".
All three pass with -race.

Measured on a sandbox instance (600k gateway calls, ~4,600 Claude Code
and Codex sessions, 300 grown since the last start; 4 API calls asked
3.5s after the routes, when the warm-up starts), base 1a3b92688 against
this branch, back to back. The machine's load average was 350-480
(nine agents running suites), so these timings are mostly CPU wait and
vary by tens of seconds run to run:

  first answer (stats?days=30)  base 91s / 81s    new 50s / 79s
  manage?agent=claude           base 112s / 95s   new 83s / 96s

The pages no longer queue behind the warm-up's lock, but at this load the
answer is bound by the CPU its own parse gets, so no gain shows above the
noise in the second pair. On an idle machine the held reads are what
#2776 reports; the tests above show they are no longer held.

Run on origin/main 2ceff7370 with all four #2776 commits' changes
(this one and the three beside it), load average 291-568 (nine agents
running suites), macOS:
- go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok,
  among them agent (2310s), gateway (1707s), provider (764s), usage
  (83s). Red:
  - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept,
    TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each
    "TempDir: mkdir ...: no space left on device" (the disk filled
    mid-run). After space was freed, ./internal/sessions alone: ok
    (139s).
  - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
    TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow,
    TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and
    TestMainWindowCorners (86s): the real-window AppKit tests under
    load, already filed as #2645 and #1936. Rerun alone at load ~335:
    all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s).
- gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and
  GOOS=windows all exit 0.
- No internal/gui/assets file changed, so the GUI Playwright suite was
  not run.
- At this commit alone (2ceff7370 + this change): ./internal/sessions
  ok (82s), and its three new tests with -race ok.
2026-10-19 11:32:59 +08:00
yetone a78ac27532 sessions: a Codex subagent in a legacy-history rollout gets its spawn task_name too, and a forked child's copy of its parent's spawns no longer erases its siblings' titles (#1591)
Two gaps in the previous commit's title link:

- Legacy rollouts. Codex's ThreadHistoryMode is Legacy by default. The local
  thread store has only defaulted to Paginated since openai/codex#47900
  (2026-09-24). A legacy rollout doesn't persist item_completed for a started
  SubAgentActivity. It persists an event_msg instead:
  {"type":"sub_agent_activity", "event_id": <call id>, "agent_thread_id",
  "kind":"started", ...}. Its children got no title. That event now links
  the same way, through one helper (codexAgentStarted) shared with the
  item_completed path.
- Forked children. A forked child's rollout repeats its parent's history,
  including the spawns of its siblings. The same call id then linked from
  two files, which counted as a conflict and erased the sibling's title.
  Titles are now keyed by {child, parent}, and only the file of the child's
  own parent_session names it or takes a name away from it.

What was run:
- New tests. On the previous commit each fails with:
  - TestCodexSubagentTaskTitleFromLegacyActivity: `legacy activity title
    for child-started = "", want "Legacy started task"`.
  - TestCodexSubagentTaskTitleComesFromItsOwnParent: `a fork's copy of the
    parent's spawn erased the child's title: ""`.
- Broken by hand: with the parent dropped from the key, the second test
  fails with `a spawn its parent never made named the child: "Only in the
  fork's copy"`.
- go test -tags nogui ./internal/sessions ./internal/usage: ok.
- The event's field names come from Codex's source (protocol
  SubAgentActivityEvent and the rollout persistence policy, openai/codex
  669449b). Not tried: a real legacy-history Codex subagent rollout.
2026-10-15 04:21:31 +08:00
Hogee 3c4b4dc973 sessions, usage: a Codex subagent with no title takes its parent's spawn_agent task_name, its nickname shows apart, and Usage requests say which calls were compactions (#1591, Hogeexxl)
Hogeexxl's change (his fork branch codex/codex-session-details, f7c176c9),
cherry-picked with his authorship:

- A Codex child thread whose title is still empty after the existing
  precedence takes the task_name of the parent's spawn_agent call, linked by
  the call id and the SubAgentActivity "started" item that names the child's
  agent_thread_id. Conflicting links leave the title empty.
- session_meta.agent_nickname is exposed as `nickname` on the list, one,
  manage and overview responses, beside the title, not in place of it.
- GET /api/usage/requests and /v1/magpie/usage/requests carry `compaction`
  (true/false) for Codex calls with native evidence, and leave it out
  otherwise. A gateway row matched by a unique response_id takes the marker
  and keeps its own model, usage, cost and kind.
- Flags bits 1024 (rowCompactionKnown) and 2048 (rowCompaction) are new.
  TestRowFlagsApart covers them, and they don't overlap 1..512. The sessions
  cache goes to version 21 and the calls cache to calls-v15.

Review:
- Rollout format checked against Codex's source (openai/codex 669449b):
  - v2 spawn_agent args carry task_name.
  - A paginated rollout persists item_completed with a SubAgentActivity
    item: kind "started", id = the call id, agent_thread_id.
  - SessionMeta has a top-level agent_nickname, which Codex's own list.rs
    and metadata.rs read too.
  - compaction_response_id lives in token_usage_record.
  Gaps in legacy rollouts and in calls without a response_id are fixed in
  the next two commits.
- Privacy: only a title string the user's own Codex wrote and a boolean
  are added to local API responses. Nothing new goes to a vendor or to
  telemetry. The ingest POST parses fields one by one, so it is unchanged.
- No .github, dependency or network changes.

What was run:
- His tests pass: go test -tags nogui ./internal/sessions ./internal/usage,
  and the two new internal/gui API tests.
- Broken by hand, each caught by his tests:
  - the nickname read removed;
  - the conflict checks removed;
  - mergeCodexCompactions broken;
  - the gateway pair's setCodexCompaction removed;
  - the flag read forced to true.
- Not caught:
  - the parent check on the title link (covered by a test in the next
    commit);
  - `copy.codexCompactions = nil` in cloneCodexChunks removed. That line is
    defensive only: the shared chunks never hold the map.
- The gofmt, vet and full-suite record for the three commits is in the
  last one.
2026-10-15 04:21:31 +08:00
Hogee 644f4316f9 sessions, usage, gui: separate Codex thread relationships and consumption (#1591)
Preserve native Codex thread IDs and explicit parent chains. Associate gateway
calls with their actual thread by unique response ID before legacy matching;
fold identical native history copies and keep ambiguous actors unknown.

Existing Sessions APIs expose optional Codex roles, parent/root relationships
and per-thread model/effort consumption. The overview uses its existing calendar
range. Usage request APIs expose query-time actor classification and reuse
session/subagent/parent_agent for Codex. Other agents, pricing, gateway routing,
UI assets, raw Usage logs and model-only aggregation retain their semantics.

Verified after rebasing onto main 331c27703a,
at commit 50baace0a52953263dddc49f4dc55f97a8457dd1, code tree
78743e334f8c841e2a188aafe26996c016a8fa4b. Only this message is amended afterward.
Go 1.26.8 darwin/arm64; tests used temporary HOME and pinned Go caches.

Passed (each exit 0):
- git diff --name-only origin/main...HEAD -- '*.go' | xargs gofmt -l (no output)
- go vet ./...
- GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go vet -tags nogui ./...
- GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go vet ./...
- go build -o /tmp/magpie-codex-session-identity-p4-darwin
- GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -tags nogui -o /tmp/magpie-codex-session-identity-p4-linux
- GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -o /tmp/magpie-codex-session-identity-p4-windows.exe
- go test -tags nogui ./...
- go test -race -tags nogui ./internal/sessions ./internal/usage ./internal/gui -run '^(TestCodexIdentityParentChainsAndSummaryCache|TestCodexIdentityParentMergeAcrossRolloutFiles|TestCodexCallThreadIDPriorityAndCache|TestCodexCompactionPromotesThreadID|TestCodexSourceNativeVariants|TestCodexIdentityFieldsOmitOtherAgents|TestCodexIdentityInvalidatesOldSummaryCache|TestCodexLedgerResponseIdentityAndOwnConsumption|TestCodexRequestPageFoldsCopiesBeforeResponseMatching|TestCodexExactResponsePairPreemptsLegacyMatchInLedgerAndDirect|TestCodexQueryPageExactResponsePairPreemptsLegacyMatch|TestCodexRejectedGatewayDoesNotPairWithNativeCall|TestCodexKnownSubagentWithUnknownRootKeepsOwnConsumption|TestCodexQueryPageRefreshesIdentityAndSharesJSONFields|TestCodexActorSurvivesPackedRequestChunk|TestPackedRequestPageCallerAndRouteIdentity|TestPackedGatewayRetainsOversizedSnapshot|TestCodexSessionAPIAddsOwnModelEffort)$' -count=1
- git diff --check

Behavior-break proof: removing identity/thread-ID promotion fails native identity,
upgrade/conflict and compaction assertions. Disabling exact-pair preemption loses
a neighboring main call. Removing API enrichment yields missing consumption;
using All for a 7-day overview yields 740/74 instead of 40/4. Restored code passed
its targeted tests and the final checks above.

Native checks had Clang enum/linker deployment-target warnings.
Linux/Windows runtime, real accounts/vendors and manual UI were not exercised.
No frontend suite was run because the change does not touch GUI assets.

Refs #1591 (Codex portion only).

Reviewed and applied by yetone (cherry-picked from Hogeexxl's fork, bf8c8c9e).
The one conflict was call_cache.go's version: main had taken calls-v13 for
compaction times (e1dcd1e1d), so this is calls-v14. Run with the follow-up
commit on top, at tree 122b933ba4c474e443f2b29c6d0a4163ae364f78 on origin/main e5cd125f0 (Go 1.26.8
darwin/arm64, sandbox HOME, private GOCACHE):
- gofmt -l on the changed files: none
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...
- the darwin, linux (nogui) and windows builds
- go test -tags nogui -timeout 40m ./...: all ok
- go test -race -tags nogui -run 'Codex|Packed|QueryPage|RequestPage'
  ./internal/sessions ./internal/usage ./internal/gui: ok
Broken by hand, each red: codexIdentityRow not setting Subagent (8 usage
tests), setting it for a main thread too (2), Session kept raw instead of
the root (7), thread_spawn's parent_thread_id not read (3 sessions tests),
response pairs not reserved before the old matching (6).
Not tried: a real Codex subagent rollout (none on this machine; every
recent rollout is a vscode main thread whose session_id equals its id),
and the GUI by hand. Claude Code's fields are unchanged.
2026-10-14 22:45:40 +08:00
yetone 585f7f7dfa sessions, gui: Codex sessions made with another provider are moved to Codex's own from the Sessions page, and back (#887, cjyrainbow) — Codex's history lists only the sessions of the provider it uses now, so sessions made through CC Switch (model_provider "custom") vanished from it once Codex used magpie, though their files were still there and the Sessions page listed them. The Codex tab now reads each session's provider from its session_meta (cached with the rest) and the one Codex in that session's home uses (config.toml's model_provider, or its profile's; "openai" when none), says how many were made with another and which, and tags each. "Move to <provider>…" opens magpie's own dialog listing them, each ticked; Move rewrites only the model_provider string in each session's files (.jsonl and .jsonl.zst, in its own Codex home, so WSL's too, mtime kept) and in Codex's state_*.sqlite threads row: messages, id, title and archive are left as they are. A copy of the files goes to magpie's trash folder (trash/codex-provider, with a move.json) first, a failed rewrite is put back from it, and a session written to in the last minute is left alone and said so. Undo moves each back to the provider it had, byte for byte. Nothing is moved by itself. POST /api/sessions/codex-provider; en/zh/ja/de. TestMoveCodexProvider (listing, bytes, mtime, the DB row and nothing else, backup, byte-identical undo, an active session, a bad id), TestMoveCodexProviderPacked and TestCodexProviderIn fail without the change, as does sessions-codex-provider.test.cjs (WebKit, en and zh: magpie's dialog, Cancel posts nothing, an unticked one stays, Undo, no click moves the page, no left border, translations); sessions-manage, -toolbar, -purge, -folder-delete, -wsl-delete and click-scroll pass. Not tried against a real CC Switch history. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass. 2026-10-05 17:26:19 +08:00
Fanbuz 67004a7e8f sessions: count Codex RECORD and compaction usage without a history parent (#695)
* fix: 按本地事件配对统计 Codex 响应与压缩用量

* fix: 限制用量索引内存并精简磁盘缓存

* fix: 淘汰解析索引后仍释放请求行缓存
2026-10-04 07:57:49 +08:00
yetone f1ca6139b5 usage: a Codex call through the gateway that wrote to its upstream's cache is no longer listed a second time as a local session call (laowangba233 on #589: 用量中的统计是不是重复了 … 为啥会一个是提供商的一个是本地会话的) — the Usage page drops a Codex rollout's call when it matches a gateway record by session, end time within 2s and equal tokens. Codex reads input_tokens_details.cache_write_tokens from a Responses reply and keeps it as cache_write_input_tokens; the gateway's rUsage read only cached_tokens, so for a call whose upstream told a write the record had CacheWrite 0 and the rollout didn't, the tokens never matched, and the call stayed listed under Local session beside its provider's row. Calls without a write matched, so only some calls were counted twice (Maru Code 92 calls plus 22 "本地会话" in the report). Also, sessions' spent took only the cache read out of Codex's input_tokens, which holds the write too, so such a call's write was counted twice in its own input. Now: the gateway reads cache_write_tokens (input = input_tokens - cached - written) and tells it to Codex when it translates a reply; spent takes the write out of the input as well; and the matcher compares a call's input plus cache writes, its output and its cache reads, so a record and a rollout that split the write differently — an older Codex without the field, or records already in usage.jsonl from before this change — still match, and the duplicates already on a user's page go too. The session caches' versions go up (sessions.json 11, calls-v4) so kept parses are read again, and older calls-v* folders are removed. Under a provider filter the provider ranking still lists the other providers, as it is a picker; the duplicates were what made it read as double counting. TestCodexCacheWriteMatchesGatewayCall (a Codex rollout and gateway records for two calls, one with a 9000-token cache write; with the rollout naming the write and the record not, both naming it, and an older Codex without it: two rows, no Local session row, the provider ranking maru-code alone, unfiltered and filtered to the provider, by QueryPage and LedgerOf; fails without the change with a third row from the log), TestCodexCacheWriteNotInInput and TestResponsesUsageCacheWrite (parse and round trip through what Codex is told) are new and fail without the change; TestCallsCodex's call with a write now expects input 200 (2500 - 2000 read - 300 written). go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./internal/... under a temp HOME pass (TestFXInState's known TempDir-cleanup flake aside, which passes alone). 2026-10-03 00:47:33 +08:00
yetone 41841997d6 sessions: a fast index with an animated first run, searchable model and folder pickers, and the overview's session shape, tool use, top skills and heatmap by messages or output tokens (v: 感觉我们的Session可观测性页面也要做的这么的丰富、优雅、简洁…; 顶多第一次打开顶多需要个1分钟,然后之后都是靠索引能够极快的打开; 一定一定要特别炫酷的一个动画; Image #6/#7/#8)
The index: session files are read in parallel and each line told from its first bytes (a Claude line's type, message head and usage; a Codex line's type and payload), so tool results, attachments and compactions are never decoded; a cold index of this machine's sessions takes about 32 s, then the page opens from ~/.cache/magpie/sessions.json (version 4, which re-indexes once) and only changed files are read again. The page keeps showing the last answer while a fresh one is computed, and GET /api/sessions/progress says how far a first run is, which the page shows in an animated hero instead of a spinner (reduced motion respected).

All models and All folders are searchable combo boxes that draw only the rows in sight, so 13k folders open at once.

Each day now counts the prompts typed, replies, tool calls by name and skills called (a subagent's calls and tokens count, its messages don't). The overview adds:
- Session shape (会话形态): sessions by messages (1–5 … 121+), minutes at work, or autonomy (tool calls a prompt, <1 … 21+), toggled and remembered;
- Tool use (Tool 使用): calls and sessions, the top tools with their kind's dot, calls, sessions and share, the kinds (Bash, Edit, Read, Write, Grep, Glob, Task, MCP tools, other) as a stacked bar and by week;
- Top skills (常用 Skills): each skill's calls, sessions, last use, agents' share and projects;
- the activity heatmap by Output tokens (输出 Token) and Messages (消息) beside Tokens, Sessions, Cost and Active.
No border stripes; a toggle leaves the page where it was.

Tested with TestStatsToolsAndSkills (Claude reply blocks laid out both ways, a Skill call, an MCP tool, /clear, an interrupt, a subagent; a Codex rollout's function and custom tool calls) and the stats tests, and internal/gui/tests/sessions-overview.test.cjs in Chromium and WebKit, en and zh: the new metrics and their tips, the shape's buckets and toggles (the page not moved), the tools' rows, kinds and weeks, the skills' lines, nothing overflowing at 1100 and 560 px. go vet, go build -tags nogui (and GOOS=linux, GOOS=windows), go test -tags nogui ./... and the GUI suite pass (panel-fold flaked once in the parallel run, passes alone).
2026-09-29 23:17:43 +08:00
yetone e3984b2442 sessions: history by day — the Sessions view gets a range (today, 7, 30, 90 days or all), model and folder pickers, tiles for the range's cost, tokens, cache read and active time, and a daily bar chart of tokens or cost (weekly past 92 days). Each session file's cached reading now keeps its usage per local date and model, a message counted on the day of its timestamp, so a session that runs past midnight splits across both days and a file read on from where it stopped adds only what's new; Claude Code's repeated usage for one message moves with it to its last block's day. Totals come from every session file in the range, not the latest 200 the list shows: GET /api/sessions/stats?days=N returns each day's rows by agent, folder and model with their cost, so the view filters without asking again, and files last written before the range aren't read at all. Active time is the sum of gaps under five minutes between one line and the next in a session's main file (subagents run alongside it, so theirs aren't added), credited to the later line's day. The cache is version 2 and records the time zone, a change of which reads the files again; the list no longer drops the cached readings of files it doesn't show, only of files that are gone, and changed files are parsed in parallel. On 4000 synthetic files (880MB, 180 days) a cold read takes 0.74s, a warm one 22ms, a reload from the 4.7MB cache 49ms 2026-09-28 13:05:56 +08:00
yetone 78fe45dbc3 usage: Sessions — Claude Code's and Codex's own session files read into a list beside the overview: each session's folder, first prompt, models, tokens and estimated cost at list price, filtered by agent and searched; Resume copies the cd and claude --resume / codex resume that picks it up, and the Mac app can open it in Terminal. Only the latest 200 are read, cached by size and time, nothing written to the agents' folders 2026-09-27 17:47:14 +08:00