2ff85f8a2bc33f87aa1fdfefce580433afff76e3
217
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
84a6a2c420 |
sessions: a range's session list is made to its size (#2278)
statsRead grew out.Sessions by append, so 34k sessions' list (Summary
is ~480 bytes) held up to a quarter more than its rows, 19.4 MB in the
heap after a cold start at #2278's scale, and copied itself through
every size on the way. Each range statsFor keeps holds its list. It is
now made with room for the range's sessions (shares holds only those
with a day in range), and Keys with room for the list.
TestStatsHoursAndSessions checks the list and keys hold their rows and
no more. Broken by hand (the make removed) it failed with "3 sessions
held in 4".
Run at this change (mote): go vet -tags nogui of internal/usage and
internal/sessions for linux, windows and darwin ok; go test -tags nogui
./internal/usage ./internal/sessions ok.
Rebased onto
|
||
|
|
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
|
||
|
|
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 |
||
|
|
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:
|
||
|
|
4c1fb7758b |
sessions: copies an older magpie left are swept when a live store is read in place (#1988)
|
||
|
|
1dc20e73fc |
sessions: a live Cursor's state.vscdb is read in place, not copied (#1988)
Beside a running Cursor, every listing, count, transcript and search read the editor's state.vscdb from a copy in the temp folder, made again each time Cursor had written since the last. The store is often several GB, and on Windows, where no clone makes a copy free, Echo-Huang0010 measured ~10.6 GB written every few minutes. While the store has a non-empty -wal and a -shm beside it, Cursor's own processes share it as readers through the -shm, and magpie now opens it the same way, mode=ro with a 3s busy timeout: no copy. Nothing magpie shows comes from the store's file times (each chat carries lastUpdatedAt), so a reader's mark in -shm changes nothing it lists. With no -shm beside a live -wal, or if that open fails, it falls back to the copy as before. CLI chat stores keep the copy path. OpenUntouched's open is factored out as openSQLite. Thanks to Echo-Huang0010 for the report and the measurements; their patch capped the copy at 64 MiB, which would leave a larger history unread, so this takes the in-place read instead. The Cursor tests set TMPDIR only, which Windows' os.TempDir doesn't read (TMP, TEMP), so TestCursorLeftCopiesSwept's folder landed in the real temp folder and the next test counted it. cursorTempDir sets all three. Run at this head: - mote: go test -count=3 -run Cursor ./internal/sessions ok; go test -timeout 45m ./internal/sessions ./internal/agent ok; go vet ./internal/sessions for darwin, linux, windows ok; gofmt clean. - xiaomi-gpu (win-run): go test -count=3 -run Cursor ./internal/sessions ok (red before cursorTempDir, from the stray folder). - Broken by hand: in-place reads off, TestCursorEditorReadInPlaceWhileLive fails "a live state.vscdb was copied 3 times, want 0". - Windows, two processes: a writer holding a WAL store (~40 MB) with busy_timeout(0) wrote 200 times while a magpie process listed 40 times and read transcripts. 0 failed writes, every list saw the latest title (40 of 40), 0 copies in the temp folder. Not tried: a real Cursor install. Neither test machine has one, so the writer was a stand-in process, not Cursor itself. |
||
|
|
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 |
||
|
|
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
|
||
|
|
67b12956ac |
sessions: a Codex rollout magpie rewrites keeps every line where it was
xybio (Discord #feedback): the Codex app often wouldn't reopen recent threads: "invalid paginated history lineage for <id>: cutoff byte offset is past the source rollout". Codex 0.162 keeps a fork's place in its parent by byte (session_meta.history_base.end_byte_offset, checked by rollout_lineage.rs validate_cutoff_bounds), and its state database keeps turns and how far it has read by byte too. PortCodexRollouts (since |
||
|
|
11dcc743f4 |
sessions: a listed file is 96 bytes, what only some agents' files have kept behind one pointer
A Sessions poll copies every agent's list of ~20k files several times (listedRollouts, heldFiles' clone, callFilesWith, allFiles, byKey, statsRead). Each file was 232 bytes, most of it fields only OpenCode, ZCode, Hermes, Alma, agy, Cursor's editor or WSL files fill. Those move into fileMore behind file.more (nil when a file has none); reads go through m(), writes through w(), which copies first, so copies of a file never see each other's writes, as before. A/B with the real ~/.codex and ~/.claude data (ab5.sh, 8 polls 15s apart, alloc_space between heap-0 and heap-1), base |
||
|
|
50606d8c0b |
sessions: a live file's calls read back from its shard are read on from, not copied
Requests evicts a file's expanded calls after each read, so every change
of a live session loads its calls from the disk shard (loadKept) and
then prepareCalls cloned them whole to read on from. The loaded copy
has no other reader, so the clone was a second full copy of the
session's calls on every poll, held at once with the first while the
chunk was built. readCalls and callsAlong now say when the calls came
from disk, and prepareCalls then copies only the reading state
(cloneState: the Claude window, Codex's maps, which can be a kept
continuation's) and keeps the calls, Msgs and Began. Calls from the
cache are still copied.
Measured on real history (rss-home, owner's ~/.claude and ~/.codex,
read-only), ab5.sh, 90s warm-up then 8 GUI polls 15s apart, alloc
between the heaps:
before (v0.1.1673 head): callFile.clone 160 MB, prepareCalls 201 MB;
footprint 264-412 MB, Requests 287-722 ms
after: clone gone from the profile; footprint 201-367 MB, Requests
144-472 ms
The history is live, so loadCalls itself varied run to run (741 MB vs
172 MB); the clone's share is the part this change removes.
Run at this head (
|
||
|
|
79c8667c92 |
gateway: Codex gives Claude its signed thinking back through encrypted_content
Codex calling a Claude model through magpie (mysterious_dove_96933 on
Discord): a reply's reasoning items carried only the summary, so Claude's
thinking signature and a redacted_thinking block's data were gone. On
the next request of a tool loop magpie sent Anthropic the turn as
[tool_use] alone, with thinking on, which Anthropic documents as a 400
("final assistant message must start with a thinking block"), and the
model lost its reasoning across calls either way.
Now the Anthropic decoders name a signature as Claude's (KSig with
sealAnthropic, Part.SignedBy). The Responses encoder and renderResponses
give each thinking block a reasoning item whose encrypted_content is
"magpie-claude1:" and the block's JSON in base64 (internal/claudeseal):
its summary beside it, an empty summary for a block signed with no
text, and redacted_thinking as an item of its own. parseResponses reads
it back into the block as Claude wrote it, in order, so anthropicBody
sends it as before for an Anthropic client. A Gemini thought's
signature isn't named and isn't sealed.
The envelope never reaches a Responses API: withoutClaudeSeals in
passthrough and forwardOnce (the item keeps its summary, one with none
goes), codexInputAs leaves such an item out for Codex's own models, and
codexUpstreamOn takes it out before the ChatGPT backend. OpenAI's own
encrypted_content is untouched. sessions.PortCodexRollouts writes such
an item as its summary, so a thread resumed against OpenAI itself isn't
refused. redact.MaskJSON already keeps a reasoning item's seal whole
(no change); TestMaskJSONKeepsClaudeBlocks holds that.
Run, at
|
||
|
|
a87f051974 |
sessions: the index is written at most once a minute, not after every poll
A Sessions or Usage page polls every 15s, and a live session changes its
file between any two polls, so each poll's refresh saved the whole index
again: tens of MB of JSON for a long history, and encodeCache allocated
~20-30 MB a write (170 MB over 8 polls). The index only spares the next
start a read, and a parse a save hasn't written yet is read again then,
so a save now waits saveGap (1 minute) after the last one written; saves
in a row are still folded into the latest. Saved (a CLI or the app
ending) sets hurry, so every save queued is written at once without the
gap, and an unused wake-up is drained when the saves end so it cuts no
later gap short. The package's tests write saves as they come
(saveGap = 0 in TestMain).
Run:
- TestSaveWaitsOutTheGap (new): a second and third save right after the
first are not written while the gap stands, and Saved writes them, as
one, at once. Red with the wait removed ("2 writes with saveGap not
yet past") and red with Saved not hurrying ("Saved waited out the
gap", 10s).
- go test -timeout 45m ./internal/sessions ./internal/gui ./internal/usage
./internal/usageapi ./internal/cli ./internal/tui: ok at this change on
|
||
|
|
205e3b8ae7 |
sessions: a poll groups its files by session in one copy, not an append at a time
listSessions, statsRead (twice), nativeIDs, the Codex provider's list
and the two manage paths each grouped the files by key with
groups[f.key] = append(groups[f.key], f): every group grown by
doubling, copying a few-hundred-byte file struct each time, over ~16k
files. byKey counts the kept files per key, makes one slice for all of
them and cuts each group from it with its capacity capped, so a later
append to one group can't write into the next. Each group keeps the
files' order, as before.
Run:
- TestByKeyGroupsAsAppending (new): byKey equals the append loop with
and without a keep, and is unchanged after every group is appended to.
Red with the cap removed (kept[at:at]): a group's first file became
the previous group's appended one.
- go test -timeout 45m ./internal/sessions ./internal/gui
./internal/usageapi: ok (15.1s, 118.9s, 3.4s) at this change on
|
||
|
|
d5f86d9919 |
sessions: a Sessions poll's three reads share one listing of the files
The Sessions tab asks /api/sessions, /api/sessions/stats and /api/sessions/overview at once, and statsFor refreshes its memo in a goroutine beside them. Each listed every session file again. The stats and overview routes and the refresh now take sessions.ShareListing: a hold that, unlike OneListing, doesn't start a new "since" when one is already held, so a listing a read in flight is making is waited for and shared (heldFiles keeps a ready channel per listing) instead of made again. The refresh is also counted as a page read (readingPage), so its memory goes back once it rests. Run at this head: go test ./internal/sessions ./internal/gui ok, TestShareListing -race -count=5 ok. TestShareListing was red with the wait taken out of heldFiles by hand (the second read listed again). A/B on real session files, 8 polls of the parallel trio then /api/state, v0.1.1661 vs this: total allocated 1.96 -> 1.82 GB, trio mean 572 -> 438 ms, first trio 2071 -> 1456 ms, allFiles 353 -> 322 MB. Footprint between polls stayed ~160 MB; statsRead (~520 MB) and listSessions (~345 MB) are the rest and are not changed here. Rebased on |
||
|
|
d4c6230964 |
sessions: a folder's listing is a sorted slice, and one Codex folder isn't copied
dirent.Stats returned a map per folder. Eight Sessions-page polls on the
owner's real ~/.codex and ~/.claude (copied into a sandbox HOME) spent
~90 MB of their 2.3 GB on those maps alone. It now returns a Listing
sorted by name, found with a binary search (Listing.Get), and
listedRollouts walks it in order instead of sorting the map's keys.
listCodexFiles took the one folder most users have into a fresh slice;
that copy was ~65 MB of the same polls, and the folder's own slice is
now kept.
Run at this head: go test ./internal/dirent ./internal/sessions
./internal/usage ./internal/usageapi ./internal/gui ok; gofmt clean;
GOOS=linux and GOOS=windows go vet -tags nogui on dirent, sessions,
usage and gui clean. stats_test checks the listing is in name order.
A/B on real session files (8 polls of the Sessions trio, 15 s apart,
v0.1.1661 vs this with the next commit): listCodexFiles 129 -> 89 MB,
listedRollouts 87 -> 76 MB, dirent.stats 44 -> 36 MB.
Not tried: the Linux and Windows readdir paths beyond go vet; they
build the same Listing through stats_other.go.
Rebased on
|
||
|
|
2929135abc |
sessions: Codex's rollout listing is sized as its last one was
listedRollouts appended each of ~20k rollouts to a slice grown from nothing, on every Sessions, stats, requests-page and effort read; past 256 entries a slice grows by a quarter, so the growth allocated about five times the list. It now starts at the size the root's last listing had (plus a sixteenth), and codexFilesIn takes the first folder's list as its own instead of copying it. Measured on a copy of the owner's real history (real ~/.claude/projects and ~/.codex sessions), warm start, 12 GUI-like poll cycles 15 s apart, v0.1.1655's tree against this one: listedRollouts' allocation over the polls 762 MB -> 343 MB, its append growth (538 MB flat) gone. The run's total isn't comparable: the live Codex history changed between the runs and the requests page read the changed rollouts again. Run at this tree: go test ./internal/sessions/ ./internal/usage/ ./internal/gui/ ok; gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/sessions/ ok. |
||
|
|
0e7d2391ce |
sessions: the list of call files is sized once, not grown a file at a time
callFilesWith appended each of ~20k session files (a ~200-byte struct)
to a slice grown from nothing, on every Sessions and stats read: every
15 s poll of the window. It now gathers each source's list first and
makes the slice and the seen map at their total.
Measured on a copy of the owner's real history (rss-home: real
~/.claude/projects and ~/.codex sessions), warm start, then 12 GUI-like
poll cycles 15 s apart (api/state, api/sessions, stats?days=30,
api/usage, requests today, quotas, providers), origin/main
|
||
|
|
51a2068b52 |
sessions: a Sessions poll lists the session folders once, not twice
Each /api/sessions read listed every Claude Code and Codex session file for its list (allFiles), then again for the Codex threads' effort (usage.CodexModelEffort -> readRequestState -> CallSourcesAndCodexIdentities): ~21k files on this machine, twice every 15 s poll. sessions.OneListing holds the folders' listings (ccFiles per folder, codexFiles) while a request is answered; GET /api/sessions and /api/sessions/manage take one. A listing is shared only if it was taken after the latest hold began, so no request reads files from before it came, and the listings go when no hold is left. Folders are listed outside the lock. The warm-up's own memo (warmListing) is unchanged. Measured on the real history (rss-home, symlinked ~/.claude/projects; prof.sh, 20 s CPU profile, /api/sessions back to back), against fe903798f: - poll 170 ms -> 118 ms - readRequestState 3.89 s -> 1.58 s of samples; listedRollouts 4.95 s -> 3.50 s, now only under List TestOneListing: one listing under a hold; a hold begun after a listing lists again; every read lists once no hold is left. Red with the "taken since the latest hold" check removed by hand. Run at df1ba9586 (on fe903798f): - gofmt clean; GOOS=linux and GOOS=windows go vet -tags nogui ok for sessions and gui - go test -tags nogui -count=1 -timeout 45m: sessions 12.6s, usage 15.0s, gui 52.3s, dirent 4.7s, all ok - not run here: the GUI suite (no page script changed) and the importer packages (run at fe903798f, all ok) |
||
|
|
7b2a330a56 |
sessions: each session folder is read in one listing on macOS, not a stat() a file
Every 15 s Sessions poll (and every Requests page) lists every agent's session files and stat()s each one: on a real history of ~21.7k files in 462 folders that was ~21.7k lstat()/stat() calls, ~10 µs each on APFS, and the largest part of the poll's CPU. Codex's day folders were also read twice, once by WalkDir and once more for the stat()s. dirent.Stats reads a folder's names, kinds, sizes and modification times with getattrlistbulk, a few calls for the whole folder. statFiles looks each file up in its folder's listing and stat()s alone only a link it follows (ccFiles) or a folder that couldn't be listed so. Codex's rollouts are walked with the listings themselves (listedRollouts), in WalkDir's order, falling back to walkLinked and statFiles when a folder can't be read so. Other systems keep the stat()s as they were. Measured on the real history (~/.claude/projects and ~/.codex sessions, read only): - Stats against os.ReadDir + os.Lstat over all 21,672 entries in 462 folders: 0 mismatched kinds, sizes or times; 43 ms against 257 ms. - `magpie serve` on the real history (sandbox HOME, its projects a link to the real ones), /api/sessions asked back to back with X-Magpie-Had for a 20 s CPU profile: before, 177 ms a poll, process CPU 48.5 s for the run, 17.5 s of samples in statFiles; after, 157 ms, 34.3 s, and no per-file stat() in the profile beyond links. Tests: - TestStatsAsLstat: a file's size and time to the ns, a folder, links to a file, a folder and nothing, a unicode name, and 3000 long names (more than one call's 64 KB answer), each as os.Lstat says. - TestStatFilesAsStat: follow and not, the same files kept with the same sizes and times as os.Stat/os.Lstat; on macOS only the two links are stat()ed alone. Red (7 alone, want 0) with Stats turned off by hand. - TestListedRolloutsAsWalked: nested days, a folder and a link named as rollouts, a .zst, a non-rollout, and a sessions folder that is a link (#2233): the same rollouts, order, sizes and times as walkLinked plus statFiles. Red with the listing's sort taken out by hand. - TestCodexFilesStatInOrder (existing) passes on the new path. Run at this head: - gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui on internal/sessions and internal/dirent ok. - go test -tags nogui -count=1 -timeout 45m ./internal/dirent/ ./internal/sessions/ ./internal/usage/ ./internal/gui/: ok (2.4 s, 13.9 s, 15.9 s, 51.1 s). - go test -tags nogui -count=1 -timeout 45m at fe903798f, the packages that import sessions: agent 293s, cli 57s, davsync 73s, gateway 493s, library 192s, otlp 19s, tui 31s, tune 7s, all ok Not tried: Windows and Linux run the stat()s as before, so no change there; an SMB or other network volume on macOS, where getattrlistbulk fails and the per-file path is taken. |
||
|
|
eee5719991 |
sessions: a session's cost is summed in its models' order, so it reads the same each time
assembleListed summed a session's cost over a map of its models, and statsRead summed a summary's the same way, so the float came out a last digit apart from read to read (15225.3933882, then 15225.393388199998, on a real Claude Code session with nothing new written). Each read of the Sessions list then had a changed row, and the stats a changed summary, though nothing had changed. Both sum in name order now. Run at this head (macOS, go1.27): - TestSessionCostSummedInOneOrder (assembleListed, 7 models, 200 reads) and TestSummaryCostSummedInOneOrder (statsRead, 6 models priced, 50 reads): red on the old code (2 different numbers each), green after, -count=3. - go test -tags nogui -timeout 45m ./internal/gui/ ./internal/sessions/ ./internal/usage/ (provider's #3632 skip): ok. - gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gui/ ./internal/sessions/: ok. - Real history (~15.9k sessions, a live session being written): six /api/sessions reads 15 s apart, each the same as a whole read taken just after it; before, the 506 KB row of one session flipped its cost between reads. Not tried: Windows and Linux runs of the package tests. |
||
|
|
bbb4fd478a |
sessions: a parse's models, days and tools are sorted slices, not maps
A kept parse holds a model or two, a day or two and a few tools, and Go's map of one entry is a whole group of eight: ~500 bytes for one model's Tokens, where a sorted slice entry is 56. Over a long history (15.9k kept parses) state.Models, Days, day.Models, Tools and Skills held 18.4MB as maps and 4.2MB as named[V], a slice kept in name order. It is written as the same JSON object a map writes, byte for byte, so the parse cache saved before reads unchanged; names are interned with unique.Make, and plain integers in ints and Tokens are read without reflection. Measured with the real ~/.codex and ~/.claude histories (sandbox HOME, warm cache, 40s after start), base |
||
|
|
3393e61d00 |
sessions: a summary's tools, skills and days are sorted slices, not maps
Each range statsFor keeps (all days, and 30, warmed at start) holds a Summary for every session, and each had four maps (tools, skills, skillLast, perDay) plus a tools map in every day. Most hold one or two names, and a Go map of one is a few hundred bytes. They are now counts (name, calls, a skill's last date) in the names' order, and perDay a slice of days in order; the build still sums into maps and hands those over once. Run at this head ( |
||
|
|
8ab4fd6120 |
sessions: the overview keeps each session's own title, not a copy cut to 160
title() keeps 160 characters and an ellipsis, 161 in all, and the
overview cut every such title again to 160. So each range statsFor
keeps (all days, and 30) held a new copy of nearly every title, and
clip made a []rune of each title to count it. On a 15,921-file
history, 12,220 of the 12,289 titles are 161 long.
The overview now clips at titleKept (161), and clip counts runes
without converting, returning s itself when it fits.
Run at this head (
|
||
|
|
de54b4ff99 |
codex: threads started on OpenAI are listed while magpie is Codex's provider
notnico64 on Discord (Linux, magpie desktop): with Codex connected to
magpie, `codex resume` said "No sessions yet". Codex's resume picker
(tui/src/resume_picker.rs picker_provider_filter) lists only threads
whose model_provider is the one Codex is on now, with no opt-out, and
the filesystem scan checks each rollout's session_meta, not just the
state DB row. With no ChatGPT sign-in (also an API key, magpie API, an
account out of allowance, another machine/WSL) magpie writes
model_provider = "magpie", so every thread started on "openai" vanished
from the list. Nothing in it is Linux-only; macOS does the same.
Now, when magpie becomes Codex's provider and Codex was on OpenAI
before (not on a provider of the user's), the threads on "openai" move
to "magpie": the state DB row and the rollout's session_meta, rewritten
in place (both ids are 6 bytes), the file's mtime kept so the picker's
order holds, with no trash copy. At the Disconnect bringBack relabels
them back the same way before its usual mover. Threads Codex has
already packed (.zst, a week after the last turn) are left alone:
rewriting gigabytes of history at a switch isn't worth it (the owner's
~/.codex/sessions is 51GB, 11,591 of 12,255 rollouts packed). Files
written within ActiveWindow, outside this Codex home, or without their
id in the name are skipped too.
Run:
- Real Codex 0.162.1 in a sandbox HOME/CODEX_HOME (never ~/.codex):
without model_provider the picker listed only the openai thread;
with model_provider = "magpie" only the magpie one (the report).
After RelabelCodexThreads(home, "openai", "magpie") the same picker
listed both threads.
- TestCodexThreadsFollowMagpieIn (new) is red on the old code:
"connected: thread ...c1 on "openai", want "magpie"".
- go test -tags nogui -timeout 45m ./internal/agent ./internal/sessions
at this head: ok agent 480s, ok sessions 41s (rebased on
|
||
|
|
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. |
||
|
|
120264a49f |
sessions: a Codex line's marks are read in one pass, not one bytes.Contains each (#3493)
callHead and codexCallLine asked of every rollout line, with a
bytes.Contains each, whether it held "type":"user_message",
"role":"user", "type":"function_call_output" and nine more: up to twelve
passes over the line in each, a line of megabytes of tool output
included. A CPU profile of a cold usage read on Windows (20,807 Codex
rollouts, 44GB, magpie web in a sandbox home on the Windows box) put 37%
of its 270s of samples in that bytes.Contains (indexbody).
cxMarksOf reads them all in one pass: it walks each `":"` that ends a key
(in a JSON string the quotes are escaped, so never one inside a string),
and records the "type" values and the user's role it finds. It finds
what each value's own pass found: the same line, anywhere in it.
Run:
- TestCxMarksAsContains: twelve lines (long escaped strings holding the
values, a nested value past a long string, "subtype"/"xtype" keys,
"role":"users", empty and cut lines) give the same marks as a
bytes.Contains of each. Red when the role is not recorded (3 lines).
- Every line of the owner's real ~/.codex/sessions, read only: 619
files, 20,059 lines, 4.3GB, 0 lines whose marks differ.
- BenchmarkCxMarks, a 1MB exec_command_end line: 0.36ms a line, from
11.2ms.
- Windows box, cold (.cache\magpie removed), magpie web, 3 rounds each,
alternating, origin/main
|
||
|
|
c26a418d23 |
agent: an import app's status magpie can't read is unknown, not "not added"
Agent.Added now returns (added, known). Cindy's reader turned any
failure (a locked, corrupt or unreadable cindy-local-v1.db) into "Not
added", which told a user who had added magpie that they hadn't. Now
an unreadable database is unknown: /api/agents leaves `added` out and
the row shows the "confirm it there" hint, as it does for Lody. A
stopped WSL distro's app is unknown too, not "not added".
Cindy's database is also read without writing beside it. A mode=ro
open of a WAL database while Cindy was closed made cindy-local-v1.db-wal
and -shm in Cindy's own folder. It now goes through
sessions.OpenUntouched, which is what the Cursor reader already did
(immutable with no log, from a copy with one), moved out of
openCursorStore so both share it.
The CLI's list still offers `magpie cindy add` when the status is
unknown; it never said magpie was missing.
Run: go test ./internal/agent ./internal/sessions ./internal/cli ok;
go test ./internal/gui -run 'Import|Lody|Cindy|Agents' ok.
Broken by hand: Cindy's reader put back on the mode=ro open made
TestCindyHasClosedWALAndUnreadable red ("Cindy's folder changed:
cindy-local-v1.db -> cindy-local-v1.db,cindy-local-v1.db-shm,
cindy-local-v1.db-wal"); api.go ignoring `known` made
TestImportStatusUnreadableIsUnknown red. Both restored, both green.
Not tried: a real Cindy install; the read is tested on fixture
databases only.
|
||
|
|
67a137744f |
sessions: a call shard is written in frames of 2048 calls (#3493)
writeCalls wrote a shard's whole state as one frame, whatever its
size. The largest Codex session on the test copy (52,500 calls) was one
8MB gob frame, and decoding it allocated ~100MB and held ~70MB at once,
which is most of the gap between a cold warm-up's memory peak and a
warm one's.
A write now splits its patches into frames of framePatches (2048).
Every frame but the last has More set, and each carries Calls, the
file's call count after the write, so loadCalls sizes its slice once.
A file whose last frame has More was cut off mid-write and reads as
nil, the same as a bad CRC. A shard read from a frame over
framePatches (the old format) is written again in frames once, at its
first load (loadKept), so existing caches shrink their peak too.
Run at this tree (
|
||
|
|
04439c8592 |
sessions: the warm-up lists the Codex rollouts once for all its reads (#3493)
The warm-up at start ran three reads within about two seconds: the stats of every day, the stats of 30 days and the Requests page. Each listed every Codex rollout again through codexFiles, about 12k lstat()s and ~47 MB allocated a time. codexFiles now keeps its listing while only the warm-up reads (quiet: inside Warm, no page asking) and for 10s at most, the age statsFor's memo already answers with. Each caller gets its own copy. A page asking meanwhile, and every read outside the warm-up, lists fresh, and Warm drops the kept listing when it ends. Measured on the owner's real sessions (sbpairs: Claude Code and Codex history, warm index), the gui warm-up harness inside sessions.Warm, run alternately with the parent |
||
|
|
b686a8dfec |
sessions: a call shard's frames are read into a buffer kept between shards (#3493)
A cold Requests build (the first start after an update that changed the usage package's source, so the request chunks are made again) reads every call shard, ~15.7k on the real data copy. Each frame was read into a new byte slice and decoded into a new callFrame, so gob made a new Patches and Strings slice for every one. loadCalls now takes a frameBuffer from a pool. gob decodes a slice that has room in place, and leaves a field of the zero value as the field was, so each patch and string of the last frame is cleared before the next is decoded in. Nothing read out points into the buffer: gob copies strings and byte slices, and a patch's call is copied into the file's calls. Measured on the real data copy (sbpairs), warm-up harness TestZZWarm, requests-v1.bin removed before each run so every run is a cold build, three runs each: allocated through step 3 2139/2214/2182 MB -> 2001/2041/2044 MB loadCalls (cum, step 2) 781 MB -> 583 MB peak footprint 374-441 MB -> 371-419 MB, within noise Warm starts unchanged (step 2 ~690 MB either way). Run at this head: go test ./internal/sessions ./internal/usage ok; -race -count=2 of the LoadedCalls, CallCache, Shard and Frame tests ok; GOOS=linux and windows go vet -tags nogui ./internal/sessions ok; gofmt clean. TestLoadedCallsKeepNothingOfTheLastShard reads a shard with tokens, a session and a compaction, then one with none, three times; broken by hand (the patches not cleared) it fails. Not tried: Linux and Windows real-data runs. |
||
|
|
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
|
||
|
|
b027ca264d |
sessions: a pass over every session looks at Codex's title index once (#3493)
assemble and assembleListed asked CodexTitles for each Codex session, and each ask took the index's lock and stat'ed session_index.jsonl. A start's stats step assembles every session, so on the owner's data (sbpairs copy: ~10G Claude, ~50G Codex rollouts) CodexTitles was 60ms of step 0's 860ms CPU profile. codexTitleOf gives a pass one function that looks at the index on its first ask and again only when another reader loaded a different index in between; every caller of assemble and assembleListed makes one per pass, beside its pricer(). Run at this head (rebased on origin/main below): - zzwarm step 0 CPU profile on the sbpairs real data: CodexTitles, codexTitlesAt and loadCodexTitles 60ms -> absent; statsRead 340ms -> 270ms cum. Wall times at load 40-76 were within noise both ways. - TestCodexTitleOfLooksOnce: no index, an index made mid-pass not seen in that pass, seen in the next, a rename mid-pass keeps the first name. Broken by hand (re-ask on every call): red at "an index made after the first ask". - go test ./internal/sessions ./internal/usage ./internal/gui ok; -race ./internal/sessions ok; GOOS=linux/windows go vet -tags nogui ./internal/sessions ok; gofmt clean. Not changed: gui's own CodexTitles callers (trace.go, context.go) ask for a few ids at a time already. Not tried: a Linux or Windows real-data run. |
||
|
|
73d17f90ce |
codex: every CODEX_HOME folder's sessions count, its account renewed there
phantom3792 on X: with several ChatGPT accounts kept the way Codex supports, magpie counted only the default profile's usage, and the accounts added from the other profiles read no quota. Codex's mechanism, from openai/codex at 970111f6cb62: - One sign-in per folder. In codex-rs/login/src/auth/storage.rs the sign-in is $CODEX_HOME/auth.json, or the keychain item that compute_store_key(codex_home) names. - Sessions live in the same folder. rollout/src/lib.rs writes sessions/ and archived_sessions/ under codex_home. - `--profile <name>` only lays $CODEX_HOME/<name>.config.toml over config.toml (config/src/loader/mod.rs), and the sign-in stays shared. So a second account is Codex run with CODEX_HOME=~/.codex-work, and magpie read only the folder it runs with. There were two causes: - Sessions: codexFiles() walked CodexDir() alone. The sessions list, traces and the usage ledger (sessions.Calls) never saw other folders' rollouts. - Quota: an account added by importing another folder's auth.json is refreshed from magpie's copy. The import rotates the refresh token, which leaves two holders of one token, and whichever refreshes first signs the other out. The saved account goes "sign-in has expired" and its quota read fails. The fix: - appdir.CodexHomes finds the folders: CodexHome first, then folders named codex* or .codex* in the home folder or beside CodexHome, or one level down in one (~/.codex-profiles/work), that hold auth.json or sessions/. - sessions: codexFiles and Dirs read every folder. - provider: rememberLogins saves each folder's account with Home set to it (codexHomeLogins). The one ~/.codex is signed in to stays that folder's. - renewSaved renews such an account where that folder's Codex keeps it (codexHeldIn, as heldByCodex does for ~/.codex). This one funnel covers quota, gateway, warm-up, keep-alive and revoked sign-ins. codexLoginAuth reads its expiry from the same place. - switchSavedLogin, NextLogin's spares and forgetLogin leave such an account alone. Their errors name the folder and the CODEX_HOME=... codex command. - docs/subsystems/providers-accounts.md gains a row. Run (worktree at |
||
|
|
13f9070135 |
sessions: a kept file of one day holds that day's models once (#3493)
A long history's kept parses held 28MB live after a start's decode of
sessions.json (15,624 files). 15,345 of them have exactly one day, and
that day's model map is the file's own, so every such file held two
equal maps of ~700B each. decodeCache's share now points the day at the
file's map when they are equal.
A kept state is never written: use, unuse and dropUse are the only
writers of Models, and every parser (sessions.go, calls.go, calls_dsh,
dsh, droid, grok, kimi, cline) writes a clone, which copies the two
maps apart.
Run, at this head on
|
||
|
|
42ab935516 |
usage: requests-v1.bin is of the code that makes rows, not of the binary
The file of the session files' chunks was named by the binary's own
stat key, so every upgrade, and magpie ships several a day, read every
session file again on its first Requests page: on a 15.6k-shard history
warm-up step 2 went from ~0.8-0.9s (read from the file) to 1.6-1.9s and
~1.3GB more allocation. It is named now by the call shards' version
(sessions.CallCacheVersion, which already decides whether a shard of the
calls is read) and a SHA-256 of this package's non-test source, which
the binary carries (go:embed *.go, ~750KB with the tests, which the name
leaves out). Of the last 99 releases, 17 changed that source; the other
82 keep the file. Prices, names and settings are in the file's meta as
before. When the embedded source can't be read the name is the binary's,
as it was.
Measured (real history, sbpairs): one test binary wrote the file, a
second binary at another path (the old key differs) read it: step 2
0.79s and 1001MB alloc, against 1.63s and 2285MB cold.
Run at this tree (
|
||
|
|
89dc164765 |
sessions: sessions.json is written a file's parse at a time
A save marshalled the whole index into one buffer: 22.8MB for a long
history (15,624 files), grown by doubling to ~85MB of allocation a save,
and a save follows every refresh that read a changed session file, so a
start while agents run, and a Sessions or Usage poll after any call. It
is written through a json.Encoder into a 256KB buffer handed to a 1MB
bufio.Writer on the temp file, keys in json.Marshal's order and escaped
as it escapes them, so the file is the same bytes.
Measured on the real sessions.json (sbpairs, 22,836,803 bytes):
json.Marshal 54-73ms and 85MB alloc; encodeCache 51ms and 14MB alloc;
the output equal byte for byte.
Run at this tree (
|
||
|
|
ce60cb9908 |
sessions: TestDecodeFrameKeepsDefinitions is skipped under -race
The test counts what a kept gob Decoder saves, and under -race sync.Pool
lets a quarter of what is put in it go, so the kept Decoder is often a new
one: 158 allocations a frame against 478, over the 1/4 bar. It skips on
raceOn as the package's other pool tests do (TestScanFramesReadsALongFrameOnce).
Run: go test -race -count=1 ./internal/sessions: was red on this test at
|
||
|
|
432393217a |
sessions: a shard's gob definitions are compiled once, not once a shard (#3493)
Every call shard's frame is its own gob stream: callFrame's type definitions, then the frame. loadCalls made a gob.Decoder for each, so each of a start's ~15.6k shards compiled the same definitions again. A cold Requests build (every upgrade, since requests-v1.bin is keyed on the binary) spent ~400 MB of its allocation and most of its GC there. decodeFrame keeps one Decoder in a pool along with the definition bytes it has read, and hands it only the value message when a frame's definitions are byte for byte those. A frame of other definitions gets a new Decoder; a Decoder that failed is dropped; bytes left over after the frame are an error, as before. Measured on a copy of real data (15,656 shards, 117 MB), cold step 2 of the GUI warm-up (QueryPage(All)): allocation 2190 -> 1968 MB, CPU 5.51 -> 3.92 s, maxrss 448 -> ~410 MB. Wall stays ~2.2-2.6 s: the serial row building on the consumer goroutine is the limit, next. Run at this head ( |
||
|
|
94503901c0 |
sessions: a string many kept files repeat is held once
decodeCache's Unmarshal made a string for every file's title, cwd and model names, however many files gave the same one. On the real history copy (sbpairs, 27,699 kept files) 23,689 sessions a script ran carry one ~420-byte prompt as their title. The kept parses held 54 MB after a collection, 11 MB of it such copies. Each decode worker now takes those fields (title, cwd, first, named, model, provider, msg_model, msg_day, codex_nickname, and the Codex identity's role and parents) through unique.Make, so the parses hold 44 MB. The decode took 104-114 ms, as it did (121 ms when measured for |
||
|
|
e2dbb03405 |
sessions: the kept parses are decoded on a few goroutines at start
One json.Unmarshal of sessions.json (40MB, 27,679 files on a long
history) took 310 to 440ms of every start before the first page (#3493).
decodeCache checks the file is valid JSON (gjson), reads its version and
zone, splits the files without copying them, and decodes each file's
parse with json.Unmarshal on up to 8 goroutines. The result is what one
Unmarshal gave: a key given twice is its last, and the file is refused
where it was refused (bad JSON, another version or zone, no files, a
parse that doesn't decode). Only the keys are copied out of the read.
Real data (sandbox copy of the live sessions.json, load ~60): Unmarshal
311ms, decodeCache 121ms, reflect.DeepEqual the same 27,679 parses.
Run at
|
||
|
|
500aa70965 |
sessions: listing the session files stats them on a few goroutines and sweeps the shard folder once a minute
Every Requests page lists every session file again
(CallSourcesAndCodexIdentities), and on a busy machine that listing was
most of a warm page after the pairing memo (#3493): ~130ms for 15.6k
Codex rollouts and the Claude Code transcripts, of which the lstat of
each rollout was half, stat()ing each Claude file a sixth, and
pruneCalls a sixth: it read the ~16k-shard cache folder and sha256'd
every path on each call.
- statFiles stats the files a walk found on up to 8 goroutines (from 512
files), keeping the walk's order and leaving out what is gone or no
regular file, as before. Codex's still take their info from the walk's
entry (free on Windows), Claude Code's from os.Stat.
- pruneCalls still drops the in-memory entries of gone files each call,
but looks over the shard folder (and hashes the paths for it) at most
once a minute, and at once when the cache folder moved. Temps already
waited an hour; an orphan shard waits up to a minute more.
Run at
|
||
|
|
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). |
||
|
|
0e643b14e4 |
sessions: a screenshot's line is read thinned, not gathered whole (#3318)
A cold read of the sessions gathered every long line it read whole
(takeLong), to take a timestamp, a folder and a session id off it. In a
10GB Claude projects folder and a 50GB Codex sessions folder the lines
behind that were Claude Code tool results holding a screenshot twice
(message and toolUseResult), Claude Code's api-request-blob lines (up to
15MB) and 154 Codex prompts with screenshots (5 to 15MB a line). Spread
over the read's workers they held 130 to 154MB live at its peak.
scanThin hands such a line on thinned, a chunk at a time, never whole:
- Claude (summary and calls): a user line whose message is a tool result,
or a line of Claude Code's own other than a title or summary (both read
only for keys, timestamp, folder and session id), has every string cut
to 4KB.
- Codex (summary): a line the head lets through has only its data: URLs
cut; a prompt's text is kept whole.
Every byte outside a string is kept, an escape is kept whole or not at
all, and a cut never splits a rune, so the line stays JSON and a search
for a quoted key finds what it found before. Lines over maxLine are still
passed over.
Run:
- TestThinnerKeepsJSON: 200 rounds of random chunk splits (1 to 7 and up
to 9000 bytes) over a line with escapes, \u surrogate pairs and CJK;
red when escapes are ignored.
- TestThinToolResultReadsTheSame: claudeLine (main and not) and
claudeCallLine give the same state thinned as whole over two 3MB tool
results; a thinned read allocates under 3MB (red at 7.9 to 8.4MB with
the thinning off).
- TestThinCodexKeepsPromptText: codexHead+codexBody give the same state
with a 3MB image cut, the 21KB prompt kept whole; red when every
string is cut.
- go test ./internal/sessions ./internal/gui ./internal/usage
-timeout 45m: sessions and usage ok; gui red in
TestRestartHandsTheGatewayOver (12 of 13 requests answered, a reset),
which is #3451; alone -count=3 ok.
- GOOS=linux and windows go vet -tags nogui ./internal/sessions, gofmt.
- Real use: magpie web --gateway under a sandbox HOME whose
.claude/projects and .codex/sessions are the owner's real ones (10GB
and 50GB), caches cold, /api/sessions?limit=50 then the 7 and 30 day
overview (load ~40 on the machine):
before (
|
||
|
|
ccf403bda9 |
sessions: the Sessions list keeps a Claude file's window in sessions.json, read on after a restart (#3493)
The summary's Claude revision window (state.Claude) was json:"-", and a Claude file's parse with no window starts again from byte 0. So after every restart, which is every update, the Sessions list read each grown Claude session from its first line: the live 2 GB session on the owner's machine took seconds of the first list. state.Claude now goes into sessions.json as its bounded window (claudeUsageState MarshalJSON/UnmarshalJSON, the entries in eviction order; window() and claudeWindowOf are shared with the calls .rev sidecar). It is bounded by claudeRevisionEntries and trimSummaryRevisions as in memory. A sessions.json from an older magpie has no "claude" and reads from the start as before; an entry without a contribution is skipped, so a bad window never loses the whole index. #697 kept message maps out of the index because they were unbounded; the window is bounded now, so TestClaudeNativeReplayAcrossReadersAndRestart checks the kept window's weight instead of its absence, and TestQoderUsageAfterWindowLoss's restart case strips "claude" from sessions.json to stand for an older index. Real data (a sandbox HOME with the owner's real ~/.claude and ~/.codex, read only): cold Sessions list after a restart with the live sessions grown, 6.3s with the 2 GB file reparsed -> 0.77-0.96s over three runs, only small subagent files reparsed. sessions.json: 7 windows, ~1 MB of 21.7 MB. Run at this tree: go test -count=1 -timeout 45m ./internal/sessions ./internal/usage ./internal/usageapi ./internal/gui ok (sessions after the two test updates); go test -race ./internal/sessions ok; GOOS=linux and windows go vet -tags nogui ./internal/sessions ok; gofmt clean. TestClaudeSummaryReadOnAfterRestart is red with the tag back at "-" (the summary is read again from its start, its marker lost). |
||
|
|
ff6f3188bd |
sessions: a grown Claude file is read on after a restart, with the window it had (#3493)
A Claude Code session's revision window lived in memory alone, so after
magpie started again (every update), or let a ninth live session's
window go, each Claude file that had grown was read again from its
first line. On the owner's real ~/.claude a live 2 GB session and a
372 MB one were read whole for the first Requests page: 2.4 GB, 7.4s.
The window is bounded (claudeRevisionEntries), so readCalls now keeps
it beside the file's shard (<hash>.rev, temp and rename, ~60 KB), with
the Off and ContentHash of the read that made it. A read whose old
state has no window takes it from there when both match, and reads on.
A file no longer being worked on drops its window as before, and its
.rev with it; pruneCalls takes away a .rev whose shard is gone.
Measured (internal/gui handler, sandbox HOME with the owner's real
~/.codex and ~/.claude, 15,553 sources): the first ledger week after a
restart 7.4s -> 1.7-2.4s across three restarts; 14 .rev files, 8-67 KB.
Run at this tree: go test -count=1 -timeout 45m ./internal/sessions
./internal/usage ./internal/usageapi ok; GOOS=linux and windows go vet
-tags nogui ./internal/sessions ok. TestClaudeFileReadOnAfterRestart is
red with withCallRevisions turned off ("read again from its start"),
and checks the calls read on equal a read from the start, a revised
recent message included.
The Sessions summary's own Claude window, in memory alone the same way,
is kept by the next commit.
|
||
|
|
f8fa8147ba |
sessions: a page-asked first read uses half the cores, not twice them (#3238)
The index's cold scan with a page waiting started min(max(8, 2*NumCPU),
32) readers, as if reading waited on the disk. On an SSD decoding and
parsing is the work: on the Windows box (32 cores) a cold start over
6751 real Codex session files (15156 MB) with /api/sessions waiting
held 2154% CPU, the ~2000% the reporter saw, while other apps ran
beside it. Now max(2, NumCPU/2) readers; the quiet warm-up's NumCPU/4
slots are unchanged.
Run:
- TestAskedIndexReadsWithHalfTheCores: ok; with the old count put back
by hand it fails ("the index read 28 files at once, want 2 to 7").
- go test -count=1 ./internal/sessions/: ok (64s).
- gofmt -l clean; go vet darwin, GOOS=linux and GOOS=windows -tags nogui
clean for internal/sessions.
- On the Windows box (32 cores), a cold read of 14051 session files
(~44 GB) with a page waiting, magpie built from this commit's parent
against this one: peak CPU 1634% -> 1172% (about 900-1100% sustained),
peak working set 1612 MB -> 1108 MB, ~22s -> ~27s to read them all.
|
||
|
|
ea9454d2d8 |
usage: count two ids of one model as one, magpie model alias (SlouchyQuill507 on Discord)
A vendor names one model two ways (deepseek-v4.1-flash and deepseek-flash),
and Usage, Usage > Sessions and `magpie usage` showed two rows. Now:
magpie model alias deepseek-v4.1-flash deepseek-flash
magpie model alias deepseek-v4.1-flash (what it is counted as)
magpie model alias deepseek-v4.1-flash --reset
magpie model aliases
kept as settings.json "usageAliases" {from: to}. Off until one is written.
Ids match as routing groups match them (provider.sameModel: vendor/ prefix,
case, "_", snapshot date), at every provider; a chain is followed to its
end; an alias to itself, a loop, or a flag as an id is refused. A loop
written into the file by hand counts each model under its own id.
Display only: requests, agents' model lists, /v1/models, routing groups,
Same as and prices never read it. Each call is priced by the id it was
made under and only then counted under the alias; the alias's own price
is never put on the other id's calls, and a merged row is priced only
when every id in it is. Applied in usage summarize/direct (Models
groups), the gateway sessions projection (alias read before
gatewayCache's lock; the cache key hashes usageAliases), and
sessions.List/Get/Find/Stats (read before storeMu/mu, merged into new
slices so the memo is untouched; ModelEffort rows merged too). A failed
settings.json read keeps the last aliases read, and SetUsageAlias refuses
to write over an unreadable file (EditUsageAliases under fileMu). The GUI
settings save carries usageAliases. No GUI control.
Not aliased: the Requests ledger's per-request model and its model
filter, which show each call's own id.
Run (worktree at
|
||
|
|
85534cd078 |
codex: threads started on magpie come back to the provider Codex is on
kaizaoji on X (10-22, zwaydot's Codex thread): after using magpie with Codex and then disconnecting or editing the config, projects say their context doesn't exist, and earlier threads can't be read. Cause: Codex lists threads per provider. app-server thread/list filters on the current model_provider when the caller names none (thread_processor.rs), and the TUI resume picker does the same; no setting turns that off. magpie sets model_provider = "magpie" with an API-key sign-in, with no sign-in, with a ChatGPT account out of allowance (codex.out), in the "magpie API" login mode and for a gateway on another machine. Every thread started then is tagged "magpie" in its rollout's session_meta and in state_5.sqlite. After Disconnect (or a hand edit back to openai) Codex lists only "openai" threads, so those threads are gone from resume and from the app. Not done: routing through the built-in openai provider with openai_base_url instead of switching model_provider. The built-in requires OpenAI auth, so with no sign-in the TUI shows its login screen; with an API key Codex skips /models (#322, why |
||
|
|
60fff9a7e5 |
sessions: Droid's sessions can be deleted from the Sessions page (zachzhao1984 on Discord)
zachzhao1984 on Discord: some agents' sessions can't be deleted on the Sessions page. Droid was one of them. What changed (internal/sessions/manage.go): "droid" is Deletable. A Droid session goes to the trash whole: its transcript, its .settings.json beside it, and a subagent's two files. Nothing of another session goes with it, and Restore puts them all back. A session written to just now is left alone (ErrActive), as for every other agent. The package comment now also says why OpenCode, ZCode, Grok Build, Kimi Code and Claude Desktop (Cowork) sessions stay list-only. Guarded by internal/sessions/droid_manage_test.go (TestDroidDeleteRestore). Broken by hand: - "droid" taken out of Deletable: FAIL "droid not deletable". - The .settings.json no longer added to the session's paths: FAIL "a session just written: <nil>". The settings file isn't counted as the session's, so a write to it no longer holds the delete back. Record for this push: 13 commits on origin/main |