Commit Graph
34 Commits
Author SHA1 Message Date
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
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
yetoneandSKYhuangjing 2741b749f9 sessions: a codex fork's rollout-<n> turn does not end the copied head (#5090)
ownTurn ended a Codex fork's copied head at the first turn id the parent's
file didn't hold (fb1f4856a). codex-rs names a turn that has no id of its
own "rollout-<n>" (the rollout canonicalizer's implicit turns; the
thread-history builder), and a copied head can carry one the parent's file
lacks. It was taken for the fork's first own turn, so every copied
checkpoint after it was booked as the fork's call: July and August usage
that was the parent's history over again. Reporter: SKYhuangjing, whose
fork branch codex-fork-head-marker (acb034645) this ports.

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

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

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

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

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

Co-authored-by: SKYhuangjing <13705011+SKYhuangjing@users.noreply.github.com>
2026-11-04 09:10:52 +08:00
yetone 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 accb951ab7 sessions: OpenCode 2, Cline and dsh count tool calls and skills; every agent says its skills
MaxMooreMy on X also asked whether every agent is checked ("感觉很多遗漏
的"). Going through Found()'s agents, three with sessions counted no tool
calls or skills at all:

- OpenCode 2 (v2 session_message): an assistant's content[] tool parts
  ({type:"tool", name, state.input}; the skill tool's input is {id}), a
  user row's skills[] (picked with @ in the TUI) and a 'skill' row
  (activated through the API).
- Cline: Anthropic tool_use blocks; the "skills" tool's input.skill.
- dsh: tool/call events (arguments a JSON string; the skill tool's
  {"name"}), and a /skill typed by the user (a user/message whose
  source is {kind:"skill-invocation", name}).

cacheVersion 28 reparses old sessions.

skills_every_agent_test.go: TestEveryAgentSaysItsSkills reads Found()'s
agents from access.go and fails when one has no entry. Each entry names
the test that proves its skills count (which must exist), the agent
whose parser it shares (compared by pointer), or why it has none:
zcode (OpenCode 1 tables, tool parts not read), kimi, workbuddy,
codebuddy, hermes, cursor, agy, minimax-code and gemini.

Fixtures are real captures in a sandbox HOME through magpie's gateway:
opencode 2.0.25 (a sqlite .dump of session_v2 and session_message),
cline 3.0.70 and dsh 0.2.1-rc.2 (zstd session.v4.jsonl), byte for byte.

Run on mote (mote-run): go test ./internal/sessions/ ok (76.9s), go vet
for darwin, linux and windows ok, ./internal/tui/... ok, ./internal/gui/
red only in TestMainWindowCorners/macOS_26_SDK, the same at base
(#3949). The sessions-overview GUI files passed in chromium and webkit.
Broken by hand: on the old parsers the three agent tests fail ("tools 0
[]"); the guard fails with an entry removed, a wrong parser, or a named
test missing.

Not tried: OpenCode's TUI typed by hand (prompts sent through its API,
as the TUI does), OpenCode 1's tables, Kimi Code (only the retired
Python kimi-cli was captured), hermes, cursor, agy, workbuddy; Windows
and Linux runs; a full ./... suite (mote busy with two other sessions'
suites). During the Cline capture, Cline's own auto-updater removed the
global /opt/homebrew/lib/node_modules/cline; cline@3.0.70 was installed
again (cline --version 3.0.70).
2026-10-30 11:28:49 +08:00
yetone 23e63f1a36 sessions: Factory Droid's skill calls count in the overview
MaxMooreMy on X ("droid 也能帮忙修复下吗") showed the Sessions overview's
Skills card empty for Droid. Droid's parser counted no tools by skill:
it never read the Skill tool's input.skill, and a typed /<name> prompt,
which droid sends with a <system-notification> holding
<skill filePath=…><name>X</name>, counted nothing.

Now the Skill tool counts its input.skill, and each <name> in a
skill-selection notification of a user message counts once (HTML
entities unescaped, a name cut short counted as nothing). cacheVersion
27 reparses old sessions.

Fixtures are four real droid 0.231.0 sessions (droid exec through
magpie's gateway, sandbox HOME), byte for byte: a Skill tool call,
/greet-user, /greet-user /wave-hand, and /nonexistentzz (no skill).

Run on mote (mote-run): go test ./internal/sessions/ ok (76.9s, with
the next commit), go vet for darwin, linux and windows ok,
./internal/tui/... ok, ./internal/gui/ red only in
TestMainWindowCorners/macOS_26_SDK, the same at base (#3949). Broken
by hand: the old droid.go fails TestDroidToolsAndSkills.

Not tried: Droid's TUI, a subagent's skills, Windows and Linux runs,
a full ./... suite (mote busy with two other sessions' suites).
2026-10-30 11:28:49 +08:00
yetone f594b452e3 sessions: a Claude fork after a compaction is a branch under its session, read from the start
neo_o11 (Discord, after v0.1.1809): one conversation still showed as ~9
rows with the same title, and opening one showed "Session start" and a
single turn.

Cause, reproduced with real Claude Code 2.1.312 in a sandbox
CLAUDE_CONFIG_DIR: the reporter's session was compacted, then forked
several times (headless --fork-session per task, or /branch). Each fork
starts at the compact boundary and summary, and copies the session's
last reply under the same uuid. So every fork holds the original's
Leaf, and ccCopies hid the original as a fork's copy, though it alone
holds the conversation before the compaction. Each fork had a Leaf of
its own and stayed a row, with the copied title. Opening a fork read
its own file: the summary and one turn.

Fix:
- cc_copies.go: ccFamily returns copies and branches. A file is a
  copy of another only when that one holds its Leaf and its Root too,
  so a file with what came before the other's start is never hidden.
  The members of a family left visible pick a head (holds the other's
  Root, then named in the other's forkedFrom, then the earlier start,
  then the lower key); the rest are branches of it.
- sessions.go, manage.go: a branch has role "branch" and
  parent_session = its head, in List, Find/get and ListAgent.
- transcript.go: a branch's transcript is its head up to the fork
  point (the last line of the head holding one of the branch's
  uuids), then the branch's own lines. Search still reads its file.
- stats.go: a branch counts only its own lines, so tokens are not
  counted twice.
- GUI sessions plugin: the fold under a session names branches apart
  ("2 branches · 1 subagent"), in en/zh/zh-TW/ja/de.
- Fixtures in testdata/claude-forks/tasks*.jsonl are trimmed from real
  2.1.312 output: a session compacted once, two --fork-session task
  forks and a /branch copy with forkedFrom.
- docs/subsystems/gateway-sessions.md: copies and branches.

Run:
- go test ./internal/sessions -run 'TestClaude|TestQoder|TestMergeExternal'
  on mote, at e15b2277c before the rebase: ok. Red on the old code (cc_copies/sessions/transcript/stats
  restored from HEAD~): 5 tests failed (the original hidden, only forks
  as rows; a branch's prompts starting at the summary).
- Broken by hand, each red: dropping the Root rule (3 compacted-fork
  tests), ignoring forkedFrom (TestClaudeBranchNamesItsSession),
  turning branchTranscript off (3 tests), counting a branch whole in
  stats (90 tokens, not 80).
- GOOS=linux (-tags nogui), windows and darwin go vet, at e15b2277c: ok.
- Full go test ./... -timeout 45m at this head (71124a2d7 on c1660481c),
  on the Linux box (mote was at load 300 with six suites): every
  package ok, sessions 144s, gateway 987s, except: ., internal/cli and
  internal/gui didn't build (no gtk4 there), ok again with -tags nogui;
  internal/agent's TestInstalledVersion, TestGrokInstalled,
  TestOmpDetectedWithPiDir and TestCursorFolderFromTheEditorIsNotTheCLI,
  the first three red the same at origin/main c1660481c there, all four
  in #4033 (#3548, #3141). Nothing here touches internal/agent.
- GUI on the Windows box, both engines, every language:
  sessions-subagents + i18n-keys 40/44, the 4 reds 5s nav-click and
  goto timeouts in WebKit; WebKit alone again 20/20. Every
  session*.test.cjs file (32): 381/399. Its six red files run again at
  origin/main c1660481c and here, one at a time: calendar-fill zh red
  on both (#1314), sessions-today WebKit zh red here only, the
  reads.n race of #1315; the rest green on both.

Not tried: get()'s path for a session beyond the listing's 200 has no
test of its own; the TUI and CLI lists show a branch as a row of its
own, not nested; an uncompacted fork that went on has no real
forkedFrom fixture (TestClaudeBranchNamesItsSession injects one).
2026-10-29 15:03:18 +08:00
yetone d5eac64f23 sessions: a deleted Codex session leaves the Codex app's list too
zhuddan (Discord, Codex app 26.1023): a Codex conversation deleted in
magpie went on showing in the Codex app. The app lists threads from its
own catalog, <CODEX_HOME>/sqlite/codex.db (codex-dev.db for a non-prod
build), table local_thread_catalog, and drops a row only on the
app-server's thread/deleted or thread/archived. After its first full
sweep it takes in only threads newer than its watermark, so a row of a
thread whose rollout magpie moved to its trash stayed.

Delete now does what the app does on thread/deleted: the local host's
rows of threads whose rollout is gone from that Codex folder's sessions
and archived_sessions (as Codex's state database names them; neither
the file nor its packed twin there, and a file that can't be looked at
counts as there) are deleted and catalog_revision raised, in one
BEGIN IMMEDIATE transaction that waits for the app's own. The rows go
into the trash note (codex_catalog) and Restore puts them back, since
the app wouldn't take in a thread that old by itself.
/api/sessions/manage does the same once a run (TidyCodexCatalog) for
threads deleted before this release.

Run (Windows, win-run, go1.26.8):
- go test -count=1 -v -timeout 25m ./internal/sessions/: 339 PASS,
  including TestDeleteForgetsCodexAppCatalog,
  TestTidyCodexCatalogForgetsEarlierDeletes and
  TestTidyCodexCatalogKeepsWhatItCantJudge. Red: TestAgySessions,
  TestAgyRowOnly (#4115), TestOneListing and TestShareListing hanging
  the package (#4114). The same four are red at origin/main bc247a8cc
  on the same box, run alone. A second run also had TestPurgeOne,
  TestPurgeAll, TestUnchangedPackedNotReadAgain red and
  TestReadNotHeldByAnotherRead hanging, and internal/gui
  TestGatewaySessionHistoryAndCalendar red; all the same at
  bc247a8cc (#4177).
After the rebase onto origin/main (mote, go test -count=1 ./internal/sessions/ ./internal/gui/): sessions ok; gui red only in ten AppKit window tests killed at 30s (TestPanelCloseHidesIt, TestMainWindowCorners and others), mote's pboard being down (#4125).
Broken by hand: forgetCodexCatalog returning nothing turns
TestDeleteForgetsCodexAppCatalog and
TestTidyCodexCatalogForgetsEarlierDeletes red.
Not tried: the real Codex app (its catalog is in the owner's live
~/.codex, which sessions never touch); the schemas in testdata are
Codex 26.1023's.
2026-10-29 13:17:17 +08:00
yetone 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 b3edcabf29 sessions: a Claude copy's subagents and what only it holds count in the usage stats
beautiful2674 (Discord): after updating from a 0.1.17xx to a 0.1.18xx,
Usage's total over All was ~200M tokens lower, with the same filters.

Since f4762e921 (v0.1.1803) a Claude Code file whose last message
another file holds is a copy, and statsRead left every file of the copy's
key out. Claude Code 2.1.312's `--resume --fork-session` (and /branch)
copies only the conversation along its last message, so that dropped
spent tokens no other file holds:
- the subagents the first session ran: their files stay in the first
  session's subagents folder only (a sandbox run of 2.1.312 against a
  fake API: the fork's folder has none);
- what came before a compaction, when the branch was made after /compact
  (it starts from the summary) and went on while the session didn't:
  the session is then the copy, and its whole pre-compaction history was
  dropped;
- messages /rewind left on another branch, and sidechain messages an
  older Claude Code wrote into the session's file.
Part of the drop is right: before 1803 the copied messages were counted
in both files.

A copy now adds to the session it is kept in: its subagents' files whole,
and its own file read for the user and assistant messages the keeper's
file doesn't hold (ccRest, kept while neither file changes). A copy that
is a copy through and through adds nothing, as before.

Fixtures: testdata/claude-forks/subagent*.jsonl are Claude Code 2.1.312's
own files from a sandbox HOME with a fake API (a session whose first
prompt ran a subagent, and a --fork-session of it with a prompt of its
own), cut to user and assistant lines, paths rewritten to /w/proj. The
compaction case cuts compacted.jsonl before "rw prompt eight", as it was
when compacted-branch-on.jsonl's branch was made.

Run (mote) at this tree on efb55b5c9; rebased on 96d4715c6 (routing groups in
gateway, provider, cli and the GUI between; nothing in internal/sessions
or its callers' stats paths), internal/sessions ran again there: ok.
gofmt -l clean; GOOS=darwin, linux and windows go vet -tags nogui
./internal/sessions ./internal/gui ./internal/cli ./internal/tui ok;
go test -tags nogui -count=1 -timeout 45m ./internal/sessions
./internal/gui ./internal/cli ./internal/tui ./internal/usage all ok.
Broken by hand, each red: stats.go as on origin/main (4000 in, want
5000; 20 in, want 80); the copy's subagent files and its rest left out
(the same two).

Not changed: the Sessions row of the session a copy is kept in still
leaves out the copy's subagents and its pre-compaction messages (#4054).
Not tried: the reporter's own files; how much of their 200M was double
counting before 1803 and how much this gives back is not known.
2026-10-28 19:01:27 +08:00
yetone 502674abb7 sessions: a Claude copy made after /compact is one row with its session
Neo (Discord #feedback, on v0.1.1803, used /compact and /rewind): one
conversation was still listed as many rows of the same title.

Claude Code 2.1.312's /branch (and --resume --fork-session) after a
compaction copies only the compaction's summary and what follows it,
under the same uuids. 1803 grouped copies by the file's first message,
so such a copy (its first message the summary) never met the session it
was copied from and was a row of its own; opened, it read from the
summary on. Each Claude file now also records its compact summaries'
uuids (state Compacts, cacheVersion 24, so every file is read again),
and files are judged together when one starts with a message the other
starts with or holds as a summary. Of two files that hold each other's
last message, the one that also holds the other's first message is kept
(a post-compact copy written last no longer stands in for the whole
conversation), then the newer, as before.

/rewind writes in place: "Restore conversation" and "Summarize from
here" both append to the same file (a new branch under an earlier
parent, a new compact summary), no new file. Its summary is recorded
with /compact's, so a /branch made after it folds too.

Fixtures (testdata/claude-forks/compacted*.jsonl): Claude Code
2.1.312's own files from a sandbox HOME with a fake API: a session of
/compact, a /rewind restore, a /rewind summarize, a /branch after them,
that branch gone on with a turn of its own, and a /branch made after
the session's last turn; trimmed of request records, cost lines and
attachment text, paths rewritten to /w.

Run (mote) at this tree, 8eaf10cac on 4655e1659: go test -tags nogui
-timeout 45m ./... 75 packages ok, internal/gateway red on
TestPluginStreamsPastTheBudgetWait only (connection reset, vendor saw
182 of 192), which is #3946: alone it is red 2 of 3 here and 1 of 3 on
origin/main 4655e1659, which this change doesn't touch. gofmt -l clean;
go build ./... ok; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/sessions ok.
Broken by hand, each red: grouping by the first message only (the
copies' rows came back: [11111111… 7b1e0c2a…]); keeping the newer of two
files that hold each other without the first-message rule (the branch
made last was the row, edc82b93…).
GUI: no file reaches it; the sessions page's JSON is unchanged
(Compacts is in the cache only, Copies is json:"-"), not run.
Not tried: Neo's own files; the ten copies of one moment he saw 16h
before are taken to be /branch or fork copies made after a compaction,
which he confirmed he used (/compact, /rewind). Copies made by a
compaction that ran in each copy on its own would each start with a
summary of their own and still be rows. The calls ledger (FindCall)
still holds a copy's calls.
2026-10-28 11:53:24 +08:00
yetone f4762e9217 sessions: a Claude conversation Claude Code copied into another file is one row
Neo (Discord #feedback): one Claude conversation was listed as ~11 rows
with the same title, message count and size, each under its own id.

Claude Code 2.1.312 copies a conversation into a new <id>.jsonl when it
forks one (--resume --fork-session, /branch) or moves it to a background
session: every message again, under the same uuids, with the new
sessionId. magpie keyed each file as a session, so each copy was a row,
and the copies' tokens were counted again in usage.

Each main Claude-format file (Claude Code, Qoder, Qoder CN) now records
the uuids of its first and last message (state Root/Leaf, cacheVersion
23, so every file is read once more and old copies fold in too). Of the
files of one agent that start with the same message, one whose last
message another holds is a copy (cc_copies.go). Only a random (v4) uuid counts, as Claude Code
writes them: files whose writer reuses ids like "u" stay apart. A copy
is not listed
(List, ListAgent, Agents), not counted in stats, and Delete trashes it
with the session that holds it (Restore brings it back). A fork that
went on with a turn of its own has a last message no other file holds
and stays its own row, as Claude Code's /resume shows it. The gateway's
session rows and the GUI's native keys know the copies' ids, so a
gateway-only row doesn't stand in for one.

Fixtures: testdata/claude-forks is Claude Code 2.1.312's own files from
a sandbox HOME with a fake API (a session, a --fork-session of it with a
third prompt, another fork with a different one), trimmed of request
records and attachment text. Pure copies are that session with its
sessionId rewritten, as /branch leaves one.

Run (mote) at 2b7ce2967 on d8c70504d: go test -tags nogui -timeout 45m
./... all 76 packages ok; gofmt -l
clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/sessions
./internal/gui ok; go build ./... ok.
Broken by hand, each red: ccCopies returning nil (all four row tests),
stats counting copies (110 in / 55 out, want 30 / 15), Delete not taking
copies (a copy came back as the row), MergeExternal ignoring Copies (a
gateway row came back). Without the v4 check, five tests whose
fixtures share "uuid":"u" went red (cli, gui x2, sessions, tui).
GUI: no file reaches it; the GUI tests fake the API and the JSON a page
gets is unchanged (Copies is json:"-").
Not tried: Neo's own files, and the opened view showing only "session
start" and one line in the second screenshot; that was not reproduced.
The calls ledger (FindCall) still holds a copy's calls.
2026-10-28 10:40:28 +08:00
yetone b30734f964 sessions: Antigravity CLI (agy) conversations are listed, with title, folder, tokens and resume (RickyWei, #1718)
agy's conversations were on no Sessions page: internal/sessions had no
lister for them, only the calls reader of #2097. Now each
~/.gemini/antigravity-cli/brain/<id>/.system_generated/logs/transcript_full.jsonl
is a session (agy.go). Its steps give the start and last times, the first
prompt (taken out of agy's <USER_REQUEST> wrapper), prompts, replies, tool
calls, and tokens under the model "agy", since no step names one. A step
written again replaces its tokens, read on or read whole. The title and
folder come from the conversation's conversation_summaries.db row:
title, and workspace_uris through agyFolder, which turns file:///C:/... and
file:///c%3A/... into C:\... and a host into \\host\share on Windows. agy
writes the title after the transcript, so the row is the file's rev. The
database is read again only when it or its -wal changed, and a failed read
keeps the rows read before. A row with conversations/<id>.db and no
transcript (#1718's case) is listed from the row alone, with no tokens and
no conversation to open. Resume is "agy --conversation <id>". When agy is
set to use magpie, it is the agent's launch command (gateway variables and
--model, the PowerShell form on Windows) with --conversation after it,
through sessions.AgyStart, which package agent sets. The transcript (user
text, thinking, text, tool calls, tool results) can be opened and searched.

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

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

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

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

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

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

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

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

Not tried: Windows and WSL with real binaries (WSL sessions get no
offer), images through the real binaries (round trip in tests only),
Open in session terminal on a real Terminal (the POST is tested, the
terminal path is the existing openTerminal), a Codex session compacted
by OpenAI (encrypted, not carried), and the full ./... suite.
2026-10-25 12:25:06 +08:00
yetone 9572a35761 usage: dsh sessions in Context go by their titles (Kumo31 on Discord)
Usage -> Context listed DeepSeek Harness sessions as "magpie-a",
"magpie-f" and so on, while Usage -> Sessions showed their titles. Real
dsh 0.2.0-rc.2 sends no session header on its chat-completions and
messages routes. The gateway therefore keys each request by
conversationID, a hash of the first user message. contextOf joined
titles on agent + session id, and a hash never matches a dsh session
id. The responses route sends session_id and was already joined.

- The dsh reader (sessions) records the ids the gateway gives a
  session's requests: the first typed user/message and the
  session/title-llm-request message. Each is hashed in the forms dsh
  sends it: a string, and a text part with or without a cache mark.
  The text goes through a JSON.stringify-compatible encoder (jsString),
  because encoding/json escapes <, > and &. These ids are
  Session.Convs; cacheVersion goes to 22.
- contextOf (joinConvs) puts a route that names no session under the
  session its conv id came from. An id two sessions share is left as
  it is. The title call merges in and is skipped as a tool-less side
  call. The existing title join then finds the session.

Fixture: internal/sessions/testdata/dsh-gateway holds two real dsh
session files and the four requests that dsh sent for them to a fake
upstream: a turn and a title call on each of the completions and
messages routes, headers and body as captured. Only the cwd is
rewritten to /work/proj.

Siblings: other agents that send no session header have the same gap,
but none was run to see what it sends. Filed as #3263.

Run at bc11b8a5f (on origin/main ccbc72781):
- gofmt -l: clean.
- go vet: darwin, GOOS=linux -tags nogui and GOOS=windows ./...: clean.
- set -o pipefail; go test -timeout 45m ./... | tee: exit 0, every
  package ok.
- No GUI or page files changed, so the GUI suite was not run.

Broken by hand:
- joinConvs commented out: TestContextDshSessionTitles red, the
  sessions keyed magpie-950998..., magpie-3dc586... and so on, with no
  titles.
- json.Marshal in place of jsString: TestDshSessionConvsAreTheGatewayIDs
  red on all four requests.
- title-llm-request not collected: that test red on both title calls.

New tests:
- TestDshRoutesCarryTheSessionConvs sends the captured requests
  through the gateway's handler and finds each route's Conv among its
  session's Convs.
- On the old code the tests don't build, because Convs doesn't exist.

Not tried:
- a masked first prompt (the hash is taken after masking, so the
  session stays untitled);
- a first prompt with an image or several parts;
- dsh's subagent files and forks (seeded sessions);
- a conv after compaction;
- the DSH desktop app;
- Kumo31's own history. Old routes keep their Conv, so they should
  join on the next read, but that was not seen.
2026-10-22 19:03:32 +08:00
yetoneandJuckZ c8ed37e126 sessions: each Codex response exported to Langfuse carries only its own reply and tool calls, with the turn's prompt, and a finished turn exports once (#2284, JuckZ)
JuckZ's Codex Desktop trace in Langfuse showed one reply repeated on every
later response of its turn, no prompt or tool linkage, and a completed turn
exported a second time as failed.

- token_usage_record copied t.output (the turn's last AgentMessage, a role-less
  text array) into every later response, including tool-call-only ones. Each
  generation now takes its bodies from the rollout's response_items: input is
  the base instructions (session_meta) as a system message, the turn's
  developer/user messages, and the tool results fed back since the previous
  response; output is only that response's assistant text and tool calls, in
  OpenAI chat shape with call IDs. Turn IDs fall back to the desktop's
  internal_chat_message_metadata_passthrough.turn_id, then the current turn
  (the CLI records none).
- task_complete/turn_aborted deleted the turn but left it current, so the
  following thread_settings_applied recreated it and the next task_started
  exported it again as an inferred, failed root under the same ID.
- Extension items (web search, image generation) get a span named by kind with
  query/action/prompt in and results/saved_path/failure out; FileChange gets
  its diff, ImageView its path. Never the image generation's base64 result.

Not copied from the reference: it rebuilt the whole turn history for every
response. That is quadratic, and the user's real rollouts carry 2-3MB
screenshots in tool outputs and 100-400KB data-URL images in prompts, which
it would repeat on each response. Here inline images in a prompt or fed-back
result are named ("[image image/png, N bytes not exported]"); the tool's own
span keeps the output as recorded. Siblings: Claude, Pi/omp, Gemini and
OpenCode already give each response its own message's content; the reused
output and the recreated root were Codex-only.

Fixture: internal/sessions/testdata/traces/codex-desktop-sanitized.jsonl is
JuckZ's file byte for byte (cmp against d96139c2), described in the README.

Run (worktree on origin/main 95e7c6bcc, sandbox HOME):
- go test ./internal/sessions -run 'Codex|Trace'; -race -count=20 -run Codex
- end to end through sessions.TraceReader.Poll + otlp.sessionRecord on the
  fixture: 2 roots, 28 generations, system+developer+user in, own reply out
- gofmt -l; go vet ./... (darwin), GOOS=windows, GOOS=linux -tags nogui
- go test -count=1 ./internal/sessions ./internal/otlp: ok
Full suite: SUITE_LINE

Broken by hand, each red: the original traces.go (all three new tests);
output from t.output; out not reset between responses (repeated tool call
id, 8 of 5 responses with text); data URL kept; Extension unhandled (0 of 4
web ops); current not cleared on completion (3 roots over 2 IDs); base
instructions dropped; native bodies dropped.

Not tried: a real Langfuse server, a live Codex Desktop or Windows run,
context compaction (the transcript is not reset on it), earlier turns'
context in a response's input, local_shell_call/web_search_call response
items. Masking of tool arguments and MCP result order from the reference
are left out of this commit.

Co-authored-by: JuckZ <35656100+JuckZ@users.noreply.github.com>
2026-10-15 23:08:00 +08:00
yetone c7830731ca sessions: a session nothing was said in, which the Sessions page lists, opens and exports instead of "no such session" (#2273)
ListAgent lists a session assemble calls empty (no title, nothing
counted), so it can be cleared away, but Find searched only List(0) and
Get, and both drop it. The row's conversation, Markdown and Terminal
routes all go through Find, so they answered "no such session" for a row
the page itself shows. A real case is Codex's Image Session Helper: a
rollout with session_meta, settings, task_started and turn_aborted only.

Find now falls back to get(), which reports a session's files were found
even when assemble calls it empty, and fills it in the way ListAgent does
(listed(): Resume, Carry, Transcript), so Find finds every session
ListAgent lists. Get and List are unchanged: an empty session still
isn't in the main list and Get still says ok=false for it.

Run:
- TestFindEmptySession (internal/sessions) and TestEmptySessionOpens
  (internal/gui), on a fixture made from the real aborted helper rollout
  (paths and ids redacted). Both fail with Find's fallback broken by
  hand (only taking ok sessions), and pass with it.
- gofmt -l clean; go vet for darwin, linux (nogui) and windows.
- go test -p 4 -timeout 40m ./... with pipefail, sandbox HOME, at
  2b0037f41 plus this change, with four other full suites running on the
  machine: every package green but internal/gateway, whose
  TestOTelFastRequestTranscriptDiscovery/true failed ("request must still
  have a cached discovery miss"). That is #1811, its 2s discovery cache
  window under load; this change doesn't reach that path (TraceSessionIndex
  reads headers itself, never Find or ListAgent). Run alone with -count=10
  with its sibling it passes 10/10. Noted on #1811.
- Real use: a dev-tagged build in a sandbox HOME holding a copy of the
  real empty rollout, sessions feature on. /api/sessions/manage lists it,
  /api/sessions/transcript returns 200 {"parts":[]}, /api/sessions/markdown
  returns 200 with the .md attachment.

Not run: real use on Windows or Linux; the GUI suite (no GUI asset
changes). Whether an aborted helper rollout should count as something
said, and so show in the main list, is left as it was.
2026-10-15 09:40:51 +08:00
yetone ec15f87393 sessions: a Codex Desktop fork's replayed parent checkpoints book no usage, so a thread_spawn session isn't counted ~1000x (#2234, zlxdengtianhei)
A token_count event that can't be paired with a response record fell
back to the cumulative total's delta whenever a previous total existed,
even when the event's own last_token_usage was there. A Codex Desktop
subagent fork (thread_spawn) writes two cumulative counters into one
rollout: its parent's, replayed with last=0, and its own. Each switch
from the fork's lower counter back up to the parent's booked the gap,
tens of millions of tokens, as one call. The reporter's day read 187.4B
tokens where ~10.3B was real.

last_token_usage is the request's own usage, exact even when zero, so it
is used whenever it is valid; only a missing or invalid last falls back
to the delta, and with no previous total to the total itself, as before.

Run:
- TestCodexUsageForkReplayCountsOnlyLast (new), on the reporter's own five
  lines (testdata/codex-fork-replay-checkpoints.jsonl, numbers untouched),
  checking both Calls and the session summary. Old code: FAIL "calls
  booked {Input:832145 Output:281374 CacheRead:82834688 ...}, want
  {Input:3273 Output:1201 CacheRead:72448 ...}". New: PASS, on macOS and
  on the Windows box with every TestCodex* test.
- TestCodexUsageUnpairedCountKeepsLegacyDelta and the other Codex usage
  tests still pass; go test -tags nogui ./... on macOS with this series:
  every package ok.
- gofmt -l, go vet ./... on darwin, linux (nogui) and windows: clean.

Not run: a reindex of the reporter's full dataset; the numbers above are
from their excerpt.
2026-10-15 03:34:58 +08:00
yetone c8c3ce9a9a usage, sessions: Antigravity CLI's (agy's) own calls are counted, read from its transcripts, and a step it sent through magpie once (#2097, parkavenue9639)
agy wrote its calls nowhere magpie read. Each conversation's
brain/<id>/.system_generated/logs/transcript_full.jsonl has a line per step,
and a model step carries its own input_tokens, cache_read_tokens and
output_tokens. readAgyCalls reads those as agent agy, provider unknown
(session-unknown) and no model: the step names none, and settings.json's is
only the one picked now. A transcript an older agy wrote has the lines with
no token fields; they are left out, not counted as zero.

agy sends the gateway no session header, so its gateway records name no
session and the matcher, which pairs by session, would have counted a step
sent through magpie twice. matchedBlocks now pairs an agy step with a
session-less agy gateway record by tokens alone, and lets the record end up
to 30 minutes after the step's created_at, which is when the step began (to
the second), not when its call ended.

Tried for real: agy 1.2.16 under a sandbox HOME, with GEMINI_API_KEY and
GOOGLE_GEMINI_BASE_URL on a fake Gemini endpoint, three turns of one
conversation. It sent User-Agent google-genai-sdk/1.72.0, X-Goog-Api-Key and
no session header; its transcript's input_tokens is the prompt less the
cached tokens and output_tokens includes thoughtsTokenCount (8 + 40 = 48),
as the gateway counts a Gemini reply. A turn that failed to connect wrote
ERROR_MESSAGE steps with no tokens. That transcript is the fixture beside
the issue's quoted lines and an old one without tokens; the built binary's
`magpie usage --csv all` in that HOME lists the three steps as agy, log.

Run: TestAgyCalls and TestAgyStepThroughMagpieCountedOnce fail without the
change (0 agy calls; "the step the gateway logged is counted again"); gofmt
-l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on sessions and
usage; go build darwin, linux nogui, windows; go test -tags nogui of
internal/sessions, internal/usage, internal/usageapi, internal/cli in a
sandbox HOME, all ok.

Not tried: a step through a real magpie gateway and a real Google account
(the matcher's pairing is covered by the unit test with the gateway's
numbers from the fake run); agy on Windows or Linux; the full go test ./...
2026-10-14 14:35:23 +08:00
yetone 110b204313 sessions: Pi's and omp's own calls reach Usage, here and in WSL (#1951, Elenoxe)
Pi in WSL on a provider of its own never reached the Usage page: the
call ledger had no reader for Pi's or omp's session files, so only what
went through magpie's gateway was counted, and Sessions showed tokens
that Usage didn't.

calls_pi.go reads them whole, as call_cache's wholeCallReaders does for
Kimi, from piFiles, ompFiles and wslFiles("pi","omp"):
- each assistant message is a call on its own provider and model, with
  Pi's durationMs or omp's duration/ttft;
- "usage" / "model_usage" entries on the provider they name, and a
  compaction's, branch summary's or tool result's usage on the model in
  use, as Sessions counts them;
- a call through magpie's own entry (provider "magpie", "dial" before
  the rename) is left to the gateway, which logged it already;
- a failed call (no usage) is none;
- a fork's copies of its parent's entries (written before its header's
  time) are the parent's, and a call is keyed by entry id + time.

The fixtures are Pi 1.1.0's and omp 18.9.1's own files, written in a
sandbox HOME against a fake OpenAI-compatible relay (a run, a pi --fork
of it, a session whose calls failed before it went on through magpie);
the magpie lines are the owner's own Pi's, the reply text left out.

Run: go test -tags nogui -count=1 -timeout 45m ./internal/sessions
./internal/usage ./internal/cli ./internal/gui (green); gofmt -l; go vet
-tags nogui on darwin, GOOS=linux and GOOS=windows for internal/sessions.

Broken by hand: with the reader unregistered TestPiCalls finds 0 pi
calls and TestWSLSessionsListed says the distro's pi calls aren't
counted; without the magpie skip TestPiCalls/BesideReplies count the
gateway's calls; without the fork rule reading the fork's file alone
gives its parent's calls too.

Not tried: a real WSL distro (wslFiles is covered by the existing fake
distro), Windows paths at runtime, real "usage"/"model_usage"/
branch_summary entries beyond the fixtures. Grouping the Sessions
agent strip by WSL distro stays open in #1951.
2026-10-13 16:08:07 +08:00
yetoneandggbdpq 4921e5e2a6 sessions: Kimi Code's sessions are listed on the Sessions page and the Usage page's Sessions tab (#1913, infinitr0us)
Kimi Code's calls reached the usage ledger in #1607, but no session reader
was ever written for it: allFiles had no Kimi entry, so its sessions were
missing from Sessions and from Usage > Sessions (both read sessions.List).

kimi.go reads a session folder, sessions/<workdir slug>/<id>/, as Kimi Code
itself does (packages/agent-core-v2, checked at MoonshotAI/kimi-code afd95f6):
- state.json: the title, custom or Kimi's own (isCustomTitle, titleKind,
  an old customTitle, as normalizeSessionTitle decides), cwd or 1.4's
  workDir, createdAt as epoch ms or an RFC 3339 string. Its size and mtime
  join the main file's, so a rename reads the session again.
- each agent's wire.jsonl: usage.record tokens (a magpie/ model counted
  under its own name: here it is the session's spend), turn.prompt typed by
  the user (a subagent's system_trigger and a skill_activation aren't),
  step.end end_turn as replies, tool.call names.
- a fork counts only what follows its last {"type":"forked"} marker
  (copyAgentWire + appendForkedMarker); one without a marker is cut at its
  createdAt.
- resume: kimi --session <id>.
The same files feed the calls reader (kimiCallFiles now shares
kimiFilesIn). Siblings: Kimi's ~/.kimi-code in a WSL distro is listed
(wslAgents) and its calls are counted (callSources); the Usage page's
Sessions tab reads the same List.

ggbdpq described a reader on the issue; the patch they mentioned didn't
come through as an attachment, so this is written from their notes and
Kimi's source. Co-authored for the design.

Tests (testdata/kimi-code-sessions: the #1607 reporter's whole real files,
6 sessions, totals equal to their README's): TestKimiCodeSessions,
TestKimiCodeSessionCounts, TestKimiCodeSessionFork, TestWSLKimiCode. Broken
by hand, each goes red: no kimiFiles in allFiles, no marker cut (the
clock-set-back fork), no createdAt cut, no WSL entry, any origin as a
prompt, no workDir, no resume case.

Run: go test -tags nogui ./internal/sessions/ ./internal/gui/ in a sandbox
HOME, gofmt -l, GOOS=linux and windows go vet. Not tried with a live Kimi
Code install (the fixtures are real files from one).

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-13 15:46:21 +08:00
yetone d3d1605c2c sessions: Kimi Code's own calls reach Usage, read from its wire files (#1607, infinitr0us)
Usage counts the gateway's calls and the calls the agents' own session
files record (sessions.Calls). Kimi Code had no reader, so its calls
straight to api.kimi.com on Kimi's own sign-in never showed (the
reporter's 47 k3 calls of one session on 2026-10-11).

The reader (calls_kimi.go) is built from the redacted real wire files
infinitr0us shared from two machines (protocols 1.0, 1.4, 1.5; text
replaced, every id, model and number kept) and their notes from Kimi
Code's source. It reads every agents/*/wire.jsonl under
$KIMI_CODE_HOME/sessions, else ~/.kimi-code/sessions (as agent.KimiDir
finds the new Kimi Code), main and subagents, ses_* folders included.
One call per usage.record: inputOther, inputCacheRead and
inputCacheCreation go to Input, CacheRead and CacheWrite, output as is,
the record's own model and time. Nothing is paired with step.end, since
1.4 and 1.5 write them in opposite orders and the June 1.4 build has no
messageId or llm.request. A model beginning "magpie/" (magpie's own
entry in Kimi's config) is skipped: the gateway counted it. kimi fork
copies the parent's records unchanged, so a call is keyed by agent
(agentId, else its agents/<id> folder), time, model and usage, and Calls
counts a key once. It is a whole-file call source (callSources,
wholeCallReaders) and the folder is watched (Dirs). The subsystem page
gets the list of call readers.

Fixtures (testdata/kimi-code) are the reporter's files cut to the lines
a call is read from, each line verbatim (50 KB; one of the July
session's eight agents kept).

Run: the reader over the reporter's whole, untrimmed files gives exactly
their README's totals (32/2,841,972/12,283; 151/7,025,587/122,782;
6/147,822/2,009; 10/338,328/2,176; 0 for the four others).
TestKimiCodeCalls (both homes), TestKimiCodeSkipsCallsThroughMagpie,
TestKimiCodeForkCountsOnce, TestKimiCodeBrokenFiles (cut mid-record,
empty, junk, null/negative/timeless usage) pass. Broken by hand, each
goes red: no magpie skip, no key, key without agent, no negative or
time guard, main only, KIMI_CODE_HOME ignored, cache read dropped.
go test -tags nogui ./internal/sessions ./internal/usage ./internal/cli
./internal/gui under a sandbox HOME, gofmt -l, go vet (darwin),
GOOS=linux go vet -tags nogui, GOOS=windows go vet.

Not tried: a live Kimi Code run (fixtures are the reporter's real
files, not a sandbox capture), a successful call through magpie (the
magpie-routed record in the test is the reporter's quoted 1.5 line with
a magpie/ model), a compaction record (usageScope "session", none in
the files), Kimi Code in WSL (not read), Windows paths at runtime. A
subagent's calls carry the session but no Subagent field.

Thanks to infinitr0us for the write-up from Kimi's source and the
redacted wire files.

Reported-by: infinitr0us
2026-10-13 06:59:17 +08:00
yetone a3f2097ede sessions: CodeBuddy Code's own calls reach Usage, read from its session files as WorkBuddy's are, and its calls through magpie's gateway are left to the gateway (#1779)
CodeBuddy Code was wired on the Agents page, but nothing read its session
files, so a call it made straight to its vendor never reached the usage
ledger. Only the calls it made through magpie's gateway showed, logged by
the gateway.

CodeBuddy Code writes its sessions the way WorkBuddy does:
projects/<cwd>/<id>.jsonl under $CODEBUDDY_CONFIG_DIR, else ~/.codebuddy.
A reply's usage sits in providerData.usage on its function_call or
assistant message line, keyed by providerData.messageId, and models.json
has the same format. So WorkBuddy's reader is now parameterized by agent:
- buddyFiles(agent, dir) lists the files.
- buddyGateway(dir, id) reads that agent's own models.json. Its stamp
  cache is kept per path.
- readWorkBuddyCalls takes the agent from the file.
"codebuddy" is registered in callSources and wholeCallReaders. A model
CodeBuddy asks for as custom-local:<id>, where models.json names <id> with
vendor "magpie", went to the gateway, and is skipped as WorkBuddy's are.

The fixtures in testdata/codebuddy are CodeBuddy Code 2.164.0's own files
(npm @tencent-ai/codebuddy-code), with only the cwd path shortened. They
come from two `codebuddy -p` runs in a sandbox HOME against a local OpenAI
fake: one on a model the user added for another vendor (counted: two
replies, 521 in + 26496 cache read, 115 out), and one on a vendor "magpie"
entry (skipped).

Run:
- TestCodeBuddyCalls goes red (0 calls) with codebuddyCallFiles taken out
  of callSources, and green with it in.
- TestCodeBuddyGatewayIsItsOwn checks that each agent's models.json is its
  own.
- go test ./internal/sessions passes.
- gofmt, go vet, Linux nogui vet and Windows vet are clean.
- Sandboxed go test ./... at the rebased head.

Not done:
- The Sessions page still doesn't list CodeBuddy Code's sessions. This
  commit is the Usage side only.
- Reasoning tokens (outputTokensDetails) aren't recorded, as for WorkBuddy.
- Not run against the reporter's China-edition session (47 calls). The
  line shapes match those in the issue.
2026-10-12 22:55:23 +08:00
yetone 5c9221899f sessions, agent: MiniMax Code's own calls reach Usage's split by agent, and its 0.6.8 User-Agent names it (#1605, LukeZ1988)
Usage's split by agent counts the gateway's calls and the calls the
agents' session files record (sessions.Calls). MiniMax Code had no
session reader at all, so a MiniMax Code on its own MiniMax sign-in or a
relay of the user's never showed in it.

What @minimax-ai/code 0.6.8 really writes, run in a sandbox HOME and
MINIMAX_DATA_DIR against a fake Anthropic upstream: each session is a
folder under <data dir>/v2/sessions/<yyyy>/<mm>/<dd>/, named
<time>-session_<base64 of its mvs_ id>, its messages in messages.jsonl.
An assistant line names the provider and model that answered, its usage
(input without the cache, output, cacheRead, cacheWrite, as pi's ai
package counts them) and the time in ms. The new reader
(calls_minimax.go) is a whole-file call source (callSources,
wholeCallReaders), and the folder is watched (Dirs). A call through
magpie's own entry (custom_provider:magpie) is skipped; the gateway
already counted it, with the account that answered. A reply is keyed by
its message_id, so one copied into another generation of the history
counts once.

Gateway side: magpie's entry sets User-Agent minimax-code, and the sandbox
run showed it reaching the upstream on /v1/messages and count_tokens.
0.6.8 without that header (a provider pointed at magpie by hand) sends
"MiniMaxCode", which now names minimax-code too. The class check:
StepCode, jcode, Prime Agent, Snow and every other built-in agent are
named by their own gateway key (TokenFor); TestEveryAgentNamedByItsKey
guards that for all of Clients(). Their direct, non-gateway calls are
not read yet, and neither are those of pi, Cline, Qoder, Grok, Droid,
omp, Cursor, Hermes and Alma, which the Sessions page reads (filed
as #1607).

Run: TestMiniMaxCodeCalls (the two real messages.jsonl files, verbatim:
three calls through magpie's entry and one on a relay; under ~/.minimax
and under MINIMAX_DATA_DIR) passes; dropping the gateway skip by hand
turns it red (4 calls). TestAgentOf (MiniMaxCode, minimax-code),
TestEveryAgentNamedByItsKey. go test ./internal/sessions
./internal/usage, the agent tests named above, gofmt -l, GOOS=linux and
GOOS=windows go vet. Not tried: MiniMax Code on Windows or in WSL (WSL
distros' MiniMax sessions are not read), a call on the MiniMax sign-in
itself (provider name taken from the file whatever it is), or a session
after compaction.
2026-10-11 20:09:15 +08:00
wizzy-yangandwizzy-yang e95852e301 usage, gui: 用量页补上各 agent 会话文件里的用量,请求页按「经过 / 不经过 magpie」拆开 (#948)
* sessions: dsh、ZCode、WorkBuddy 的会话文件里有各自花掉的 token,用量台账从来不读

Sessions 页面一直都在读这些 agent 自己的会话文件,用量台账没有:用量页只显示网关本
身应答过的调用——也就是装上 magpie 之前的什么都没有,而一个直接指向厂商的 dsh 更
是什么都没有。本机上装 magpie 之前就已经在用这些 agent(用它们自带的模型),那段
用量一直对不上账。

  * 新增三类"整文件读取"的调用来源,走 wholeCallReaders(它们的调用不是一行一条,
    或者文件不能从中间接着读):dsh 的会话是 zstd 分帧追加的;ZCode 用的是 OpenCode
    那几张表;WorkBuddy 的同一句回复会在多行里重复同一个 messageId。三者的 token
    语义各自换算成 Call 的 Input/Output/CacheRead/CacheWrite,调用缓存跟着记一份(v9)。
  * 每个来源都跳过经由 magpie 网关发出的调用:网关自己记过那一本账,还带着真正应答
    的供应商和账号;dsh 发往网关的请求不带会话头,两边事后对不上(token 数每次不同、
    又没有可配对的 id),硬读就是同一通调用记两次。dsh 认它被配置去的那个 provider
    (dshGatewayProvider:magpie / dial),ZCode 和 OpenCode 认路由里写的 provider
    (ocGatewayProvider)。WorkBuddy 那部分见下一个提交。
  * WorkBuddy 的调用里,同一句回复的多行只记最后一次(它带这个回复的总量);而它从
    旧历史搬过来的回复一条 messageId 都没有,每一条都是独立的一通调用——会话汇总的
    读法(workbuddyLine)就是这么数的,这里照它来,否则台账会比 Sessions 页面少算,
    正是本次要消灭的那类"两页对不上",只是方向相反。
  * dsh 的一通调用保留它文件里记的两样东西:被配置去的供应商(Upstream,作为历史,
    从来不当成路由的证据),以及厂商真正应答的模型——回复的 replayState 里那个和
    请求模型不一致时,Model 记应答的、Requested 记被请求的,和 Claude Code 的文件
    一样的读法,好让请求表的若干列有东西可填。
  * 会话的 fork:dsh 的会话从另一个会话续起来时会带上对方已写入的事件(isSeeded /
    seedLength,session/end-seed 标记之后的不算),parser 跳过的这里同样跳过,否则
    同一通调用会在每个 fork 上再花一次。
  * WorkBuddy 的 subagents/ 子目录是父会话自己的调用来源(它带自己的消息 id,会话
    归到父会话名下);调用这条路不读 file.main,那个标记是 Sessions 页面给"会话自己的
    文件、不是子代理的"用的。

夹具:dsh 的三个会话(普通、带供应商与应答模型、以及一通经网关的),ZCode 的两条
(其中 ses_zcA 那条的 providerID 是 magpie,应被跳过),WorkBuddy 的既有会话(m1 的
usage 同时落在 assistant message 和它最后一个 function_call 上,只能记一次;旧历史
三条无 messageId 的回复各记一次)和一通经网关、一通走用户自建端点的会话。
调用缓存升到 v9:v8 里既没有 dsh 的供应商和应答模型,也没有"跳过网关调用"这件事,
旧缓存会继续把旧账 Serve 出来。

TestDshCalls、TestZCodeCalls、TestWorkBuddyCalls 是新的;把跳过网关调用那几行、以及
WorkBuddy 旧历史那条判据去掉,它们必挂、加上必过(都实际跑过反向验证)。

验证:go vet;go test ./internal/sessions(只余 TestCursor,Windows 路径前缀问题,
改动前同样失败);go build(windows)。

* usage: 请求页把"magpie 转的"和"它只读到的"分成两个数,GUI 跟着拆成两栏

用量页一直只显示网关自己应答过的调用,而现在它还要读 agent 自己会话文件里的调用:
两本账混在一行里,读者分不清哪一段是 magpie 转的、哪一段只是它从文件里读到的,
而总数事实上几乎全部来自后者(本机 30 天 847M token 里,网关只转了 2.4%)。Summary
里的两个来源卡片也加不出这个数来:它们只算 input 和 output,上面的 KPI 把缓存的
token 也算在内,于是"全部请求"读作 13.6M,而"Tokens"是 847M。

  * usage.RequestPage 和 usage.Filter 各多一样东西:前者在 Sum 之外带上 Through 和
    Direct(网关应答的,和从会话文件读到的),后者多一个 Through 维度。两种建页路径
    (流式的 queryPage 和治疗桌用的 pageFromLedger)都做同一个拆分,两边一致——
    TestCompactPageMatchesLedger 现在也覆盖两个来源筛选。
  * 每一行本来就是按 Source 区分这两类的("log" 是会话文件里的调用,其余走的网关),
    拆分就落在它上面;网关自己拒掉的调用两边都不算(页面在总数下面也这么说),所以
    SourceOf 对它返回 "",点哪一栏都同样把它排除,两栏自己的计数本来也不含它。
  * 两栏自己的数字是在"来源"这个挑选被清空的情况下数的,和各维度分组一样:三栏是读者
    来回切换的地方,各自得一直报着自己的数,否则点了其中一栏另一栏读作 0,且没有回
    到全部的路。
  * /api/usage/requests 支持 via=through|direct;GUI 那一侧的三个格子、计数单位、
    方块样式在下一个提交里。
  * Filter.Via 这个名字和 Record.Via(转发调用的那台电脑,#542)重了,改叫 Filter.Through。

Sessions 页列表长度那件事(sessionListLimit)拆到单独的 PR 里,不在这里。

验证:go vet;go test ./internal/usage(只余 TestOTelRetryAfterBound,计时的 ±30ms,
origin/main 同样失败);go build(windows)。

* gui: 请求页把来源拆成三栏,汇总那一排也改成方块

用途页的请求栏一直只有一本账(Sum),而现在它既显示网关应答的调用,也显示从各 agent
自己会话文件里读到的调用。三个格子画在上方汇总那一排方块里,样式一致:三张各自带
边框、彼此留缝的卡片,窄屏(≤620px)下竖排。

  * 每栏是一个 button:点一下就只列这一来源的请求,再点一下、或点"全部请求"回到
    全部;被选中的那一栏底下有一道本主题色的线。aria-pressed 标出当前选中的是哪一栏。
  * 计数后面跟单位("147 请求"),免得一个光秃秃的数字被读成下面的 token;token 是
    四项合计,和上面 KPI 的算法一致。
  * 三个格子在重绘之间是同一批元素、原地改(class / aria / 文本 / onclick),不是每次
    replaceChildren 重建——同一份 app.js 里 5810 行的规定就是这么写的("The switch is
    the same element across redraws, changed in place, so one being pressed or focused is
    never swapped out"),正在点的那个不该被换掉。
  * 汇总那一排本身(五张 KPI 卡)改成同样的方块:各自一张卡、有缝,边框写成
    var(--line) 而不是 --card-edge(那是面板用的变量,这些卡在独立窗口里也有)。
    ≤860px 两列排布时卡片之间的那几条线照旧:奇数位去掉左边框、第三张起加上边框,
    是 e0eaf5b4 带 #799 的老规则,这里只是跟着搬了位置,没有删。三张来源格是 button,
    不参与这套分隔线。
  * 供应商·账号 一栏:来自会话文件的行显示它文件里记的那个供应商 id(Codex 一向
    如此),有账号时仍是账号优先,什么都没有才说"本地会话"。"本地会话"角标的条件
    跟着放宽到账号或供应商任一存在,提示分两种说法:文件记了供应商的,说明这是它
    被配置去调用的那个记录、不是 magpie 看到的路由(不等于官方供应商);只认得出
    账号的,沿用原来那句"仅当本地元数据能明确识别时显示账号"。
  * 窗口参数支持 via,用后从地址栏清掉,和 tab/provider/agent 等一致。
  * 新增的串子在 en/zh/ja/de 四种语言里都有("{n} tokens" 上游已有,不重复加,
    i18n-keys 绿)。

验证:node --check(app.js、i18n.js);go vet;go build(windows)。
界面效果在本机用改动后的源码构建的二进制上过目:三栏的切换与计数、方块样式、
窄屏竖排、请求表新增的会话文件行(含供应商 id)。
浏览器套件(chromium 与 webkit、en/zh):session-identity、usage-ledger、
ledger-protocol、number-units、usage-ledger-chart、usage-ttft-rounding、
usage-chart-axis、usage-fold、web-page、usage-accounts、i18n-keys 全绿;
ledger-hscroll、usage-speed、click-scroll 全绿;gui-ja、gui-de 各一条失败、
usage-ledger-detail 六条失败,均在本机 origin/main 上同样失败,与本次改动无关。
usage-ledger-chart 新钉了 ≤620px 下 KPI 卡与来源格的分隔线(把 app.css 换回上游版本
它必挂,实测过)。

---------

Co-authored-by: wizzy-yang <wizzy-yang@users.noreply.github.com>
2026-10-07 19:43:01 +08:00
Fanbuz c21cd8c881 sessions: reconcile replayed Claude message usage without persisting message maps (#697)
* fix: 按消息修订校正 Claude 用量并限制缓存状态

* fix: 释放历史 Claude 索引并按字段读取请求标识

* fix: 保留大型 Claude 会话的增量读取窗口

* fix: 修正 Qoder 重计并按解析成本保留会话窗口

* fix: 避免历史会话窗口挤占活跃日志缓存
2026-10-04 10:01:52 +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 d079dc6223 usage: an OpenCode session's row shows the effort and the model it asked for (#680, Sun1090: 数据不完整,推理强度是有的)
OpenCode rows read from its own data (opencode.db or storage/) had 请求模型 and 推理强度 as —. OpenCode keeps both on each reply (packages/schema/src/v1/session.ts, AssistantMessage): variant, the effort picked in its model menu for the prompt (high, max, low, xhigh, none, thinking … as the provider's variants name them; prompt.ts copies lastUser.model.variant onto every reply), and modelID, the model the reply was sent to. OpenCode 2 (session_message) keeps the variant in model.variant (Model.Ref). It records no model the response named, so modelID is what was asked for, as a Codex rollout's model is.

Now a call's Effort is the reply's variant ("default" or none is no effort picked); a compaction in OpenCode 2 takes the effort last replied with, as it takes the model. In the ledger an OpenCode call is told as a Codex one: requested = its model, served left empty rather than claimed. The call cache moves to calls-v5 so calls read before carry the effort.

TestOpenCodeCallsJSON/DB/V2 (fixtures with variant high, default, xhigh and none) and TestOpenCodeSessionCallIsWhatItAskedFor fail on the old code and pass. go vet ./internal/..., builds (nogui, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. Not tried against a real OpenCode database with variants (this machine's OpenCode data predates them).
2026-10-03 23:44:06 +08:00
mofelee 38b4a9d984 feat: export gateway and agent conversation waterfalls to Langfuse (#581) 2026-10-03 01:43:32 +08:00
yetone cd7b7a042f sessions: omp's local sessions are in Usage › Sessions (#303), and the GLM Coding Plans take Codex's Responses as they are (#306) — omp (oh-my-pi) keeps Pi's session jsonl (v3) under ~/.omp/agent/sessions (and profiles' and $XDG_DATA_HOME/omp's) with a title line, title changes, model_usage for calls outside the chat, provider/model changes and subagent/advisor transcripts beside the file; they are read through Pi's parser, subagents counted in their session, a fork's copied entries in the original only, resumed by omp --resume <id>. The zhipu and zai Coding Plan regions get their Responses base (open.bigmodel.cn/api/v1, api.z.ai/api/v1, per their Codex docs), so Codex's requests go there as they are instead of rebuilt for Chat; Chat and Claude Code routes are unchanged. TestOmp, TestDirsMore and TestGLMCodingPlanResponses fail without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass. 2026-09-30 18:07:32 +08:00
yetone e927f027f3 sessions: Grok Build's and WorkBuddy's sessions are counted too (Aimer779: 用量→会话 增加 Grok Build 和 WorkBuddy 的本地会话统计)
Usage → Sessions and the stats now list Grok Build's and WorkBuddy's local sessions next to the other agents'. The GUI and CLI filters already name them from agent.Clients(), so nothing else needed changing.

Grok Build: the reader looks under $GROK_HOME/sessions (else ~/.grok/sessions), at <url-encoded cwd>/<id>/, reading summary.json and updates.jsonl.
- Tokens come from each turn_completed's usage.modelUsage, per model. Input is counted without the cache it read (inputTokens already includes cachedReadTokens), so the cache isn't counted twice.
- A subagent's session (session_kind "subagent…") counts once, inside the session it ran in.
- A fork's copied updates count only in the session they came from. The fork itself counts from its created_at on.
- The title is the first prompt typed, else Grok's generated_title.
- The hooks that fire on start and end don't count as time at work, so a session closed the next day doesn't run overnight.
- It resumes with `cd <cwd> && grok --resume <id>`.

WorkBuddy: the reader looks at $WORKBUDDY_CONFIG_DIR/projects/**/*.jsonl (else ~/.workbuddy).
- Tokens come from providerData.usage and count once per reply (providerData.messageId), however many of its lines carry it. Cached tokens (inputTokensDetails) are taken out of the input.
- The older snake_case input_tokens/output_tokens are read as well, with the cwd from <id>.meta.json for sessions migrated from its old history.
- The title is custom-title, then ai-title, then the first prompt (without WorkBuddy's <system-reminder> and @scene: blocks).
- There is no resume command, since it is a desktop app.

Tested:
- go test -tags nogui ./... passes. New sanitized fixtures cover both readers: a Grok main session with a subagent, a fork and a hooks-only session, plus a WorkBuddy session with repeated usage lines and a migrated one.
- go build -tags nogui passes for darwin, linux and windows (CGO_ENABLED=0).
- A read-only run against real ~/.grok and ~/.workbuddy: 7 Grok sessions (an 8th, hooks only, left out) and 16 WorkBuddy sessions. Token totals match a raw jq tally of the same files: Grok 293910 in / 4396 out / 610560 cache read, WorkBuddy 13548053 / 621856 / 32321668.
2026-09-28 23:25:18 +08:00
yetone 4eba5c37a8 sessions: ZCode, DeepSeek Harness, Cline and Qoder's sessions are listed too (lml: 希望会话里也能看到 ZCode、Qoder CN、Cline、DeepSeek Harness 的) — ZCode's are OpenCode's tables in ~/.zcode/cli/db/db.sqlite, read as OpenCode's database is (opened read-only), its tokens the AI SDK's (input less the cache, output as it is), its model modelId, a title_source of default no title, a prompt typed a real_user's; dsh's are ~/.dsh/sessions ($DSH_HOME), a folder a session, the latest format's session[.vN].jsonl[.zstd] read whole, zstd frames and all, a subagent's (parentSession) in its parent's, a fork's seeded events (seedLength, or up to an inherited session/end-seed) counted where they were first written; Cline's are ~/.cline/data/sessions ($CLINE_SESSION_DATA_DIR, $CLINE_DATA_DIR, $CLINE_DIR), <id>.messages.json with its manifest <id>.json for the cwd, the prompt and the title, a subagent's other messages file beside it, a fork's messages before its forkedAt not counted, cline --id <id> to pick it up; Qoder's and Qoder CN's are Claude Code's lines in ~/.qoder/projects and ~/.qoder-cn/projects ($QODER_CONFIG_DIR, $QODERCN_CONFIG_DIR), qodercli --resume / qoderclicn --resume. Each folder is watched when it's there (Dirs). Tests keep HOME in their sandbox now. Tested with made-up fixtures for each (a ZCode database made in the test, dsh plain and zstd, forks of both formats, a Cline fork and subagent, both Qoder builds), and read-only against copies of this machine's ZCode database and dsh sessions: 2 and 13 sessions, their token totals the same as a separate tally of the raw rows 2026-09-28 22:45:50 +08:00
yetone 44cd8fac4c sessions: OpenCode's and Pi's sessions are listed too (貌似没有opencode和pi的session,能支持一下么) — Usage → Sessions, magpie sessions and the TUI read OpenCode's opencode.db (or $OPENCODE_DB) read-only, or its older storage/ JSON files when there is no database, under $XDG_DATA_HOME/opencode or ~/.local/share/opencode, a subagent's session counted under the one that started it; and Pi's JSONL sessions under $PI_CODING_AGENT_DIR or ~/.pi/agent, plus $PI_CODING_AGENT_SESSION_DIR or settings.json's sessionDir, a forked session not counting again what it copied from its parent. Each gets its title, folder, times, tokens per model with cache reads and writes, cost, and a resume command (opencode --session <id>, pi --session <id>); the folders note names only the agents that are there 2026-09-28 18:45:07 +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