f2eb56c6bbde1300dddc402861b59cd4e45e0215
243
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
b78b1de003 |
library: magpie-image is behind the MCP hub, saving into the calling agent's project
magpie-image was the one MCP server the hub left out, because it saves what it makes on disk and needs to know whose project that is. The hub now serves its tools like any other server's and tells it where the caller works: 1. the hub answers a tools/call as SSE and asks the agent roots/list on that stream (3s), as Claude Code answers; 2. else Codex's _meta x-codex-turn-metadata.workspaces (git repos only); 3. else the Codex thread's cwd from its session file (sessions.CodexThreadCwd), only with session consent; 4. else none, and the image goes to ~/Pictures/Magpie as before. The hub passes `magpie/roots` and `magpie/client` in the call's _meta; imagemcp saves into the first root and names the agent on its usage row. Its result carries `magpie/model`, which the hub's own usage row takes, so the row says which image model drew it. A WSL agent keeps magpie-image as its own entry (the hub can't reach a path inside the distro). docs/subsystems/mcp-hub.md (mcp-router.md after the next commit), gateway-routing.md and gateway-sessions.md say so. It is rebased on #4382 ( |
||
|
|
1334934881 |
sessions: a listing's gateway titles ask once whether anything was recorded, not once a session (#2278)
Each poll of the Sessions list and of every stats range titled each of ~5000 gateway sessions with GatewayTitle, which made the recordings folder's name and Stat-ed it each time. With nothing recorded, as for most users, that was the whole cost: os.Stat 62 MB and gatewayDir 18 MB of 90 s of polls while an agent worked. GatewayTitler makes the folder's name and asks once, and gives "" with no work when nothing is recorded; gatewayListed takes it. GatewayTitle is GatewayTitler()(agent, id), for one session. Bench (mote, ~/r2278/full, hmw.sh second runs), e14 = |
||
|
|
9e73f69af4 |
providers: rate windows bill a provider's hours at its own rate (#2463)
A provider can have up to 8 rate windows: days, a span that may cross midnight (on this computer's clock), and a rate. Inside a window a call costs the base price times the rate. The base is the user's model price as set, or the list price times PriceRate with the vendor's own peak (DeepSeek, Command Code, OpenCode Go) already in it. The author gave this order as the spec: a 0.8 window on a shared DeepSeek key takes 0.8 off the peak price at peak. The editor's hint says not to set the official peak hours again as a window, in every language. Each call is priced at its own time on the Usage page and its CSV, in the Requests tab's rows, and against a gateway key's cost limit. The Sessions page, group templates and the model list written into an agent's own config use the base price. /v1/models prices at now. Ported from YangHonghang's 2c9d459ff (rate-windows-2463-v2). The Go pricing, its tests and the translations are theirs. Changed here: - No budget raised. Their commit raised appScriptBudget and coreScriptBudget; core_budget_test.go is main's again. The editor's window rows, time menus, validation and hint moved to ratewindows.js, which app.js imports when the field is drawn (as signsheets.js is). The sliding-thumb and modalDepth comments were cut down to make room. The core is 1,535,528 of 1,536,586 and app.js 1,312,242 of 1,315,316. Until the script has loaded, a save leaves rateWindows out, and the server keeps the saved ones. - Their unrelated TestAssetsHaveNoConflictMarkers is dropped (one commit, one goal). - The row badge shows only for a provider with windows. Before, every provider with a price rate alone got a new ×badge. Its title is shorter, and so are its translations. - AgentPricer (agent model files: Pi, omp, OpenCode cost) uses the base price. Nothing rewrites those files when a window opens or closes, so a price taken at Sync stayed on outside the window. - internal/budget gets a TestMain through testenv, so the new test runs in a home of its own. - old-webkit's list of lazily loaded scripts names ratewindows.js. - The draft keeps each window as a shallow copy, and a day chip replaces its days array, so the saved provider is never changed. - The GUI test waits for the lazy script's hint, not a fixed 300ms. It also checks the peak note in each language. Run first on |
||
|
|
bcf0cfa232 |
sessions: usage counts a session Claude Desktop's Code tab ran under Desktop
CyberCaius on Discord: Usage's Claude Code filter listed Claude Desktop's
sessions. Desktop's Code tab runs Claude Code, which keeps the session in
~/.claude/projects like a terminal one; only each line's `entrypoint`
(claude-desktop, claude-desktop-3p) tells them apart. The calls were
counted under Desktop already (desktopEntrypoint), but the session, its
stats rows and its summary were Claude Code's, and the gateway's own
record of the session ("claude-desktop|<id>") wasn't matched with it, so
it could be listed twice.
The parse now keeps the entrypoint (state.Entry, on both the ccWhere fast
path and the full parse; cacheVersion 29) and a Code tab session gets
Session.App "claude-desktop". Its Agent, key claude:<id>, resume and
transcript stay Claude Code's. Stats rows and the summary use the app,
GatewayKeys and MergeExternal know the claude-desktop|<id> pair, the GUI
names it Claude Desktop, and Usage › Sessions filters by app || agent.
Run at the pushed tip (the AnySearch commit after this one, on
|
||
|
|
eadeb89c48 |
sessions, dirent: a poll's listings are kept across collections (#2278)
A full history's page polls listed the same folders every few seconds into a fresh slice, map and set each time: the sync.Pools meant to keep them were emptied by the collector, which runs about twice a second at this size, before the next poll took them. - sessions: listingBufs and pathSets are shelves (shelf.go), which keep up to four across collections. listCCFiles makes its slice with the room of the folder's last listing. - dirent: Stats keeps each folder's last listing (Listing.Done(dir)) and the room of the one before, up to 1<<17 entries in all. A name already in the folder's last listing is taken from it, not copied again. 1<<16 kept too little of ~23k session files and their folders: the first bench of this change (budget 1<<16) took dirent.entry from 67-102 to 80-100 MB a minute, no gain. Bench, mote, the real full history (52G Codex in 12,495 files, 13G Claude Code in 10,186), fullallogh.sh, alloc_space between the 50s and 110s heap profiles, MB per minute, before (v0.1.2132 equivalent) -> after: distinctOf 59 -> 22 listCCFiles 42 -> 17 dirent.entry 67-102 -> 55 dirent.nameOf 24 -> 5 Totals swing 400-1200 MB with mote's load (other sessions), so these are per function. Run at this head (rebased on |
||
|
|
37527c7ad3 |
sessions: omp's subagents and advisor are their session's to the gateway, not counted again (Jumy on Discord)
omp's task subagent (Kid.jsonl) and advisor (__advisor.jsonl) each have a header id of their own, and omp sends that id, not the main session's, in x-session-affinity (seen in a real omp 18.9.1 run through a fake upstream: the main session's requests carried 01a18ae4-555c-…, the subagent's 01a18ae4-5671-…). magpie counts those files in the main session, but the gateway's native keys held only omp|<main id>, so the gateway's records of the subagent's and advisor's calls were added again as sessions of their own: in Usage › Sessions' totals (MergeExternalStats), in the Sessions list (MergeExternal) and in NativeIDs. Session.Subs (subIDs) now holds those ids, and GatewayKeys, MergeExternal and nativeIDsWith take them as the session's own. GatewayKeys takes Claude Code's Copies too, which the GUI list added by hand beside it; the stats' native map already had each copy's own group, so nothing counts differently there. This is at most a second count of the subagent's and advisor's share, not a ~1000x: it may not explain the whole ~900M Jumy saw. Not found in the reader: omp's usage is per call (assistant messages only; toolResult and compaction carry none), re-reads continue from the offset only when the head and sampled prefix hashes match. Tests: TestOmpSubagentsAreTheSessionsToTheGateway (sessions, the existing omp fixture, whose sub headers match omp 18.9.1's) and TestOmpSubagentCountedOnceWithTheGateway (gui, /api/sessions/overview and /api/sessions, from omp 18.9.1's own lines). Broken by hand (subIDs returning nil): both red, the overview showing the Kid id as a second gateway session with 5000 input beside the native one. Run on mote: go test ./internal/sessions -run 'TestOmp|TestRaft', ./internal/gui -run 'TestOmpSubagent|TestTopSessions'; gofmt -l; go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet on the two packages; go build for darwin, linux (nogui), windows. go test -timeout 45m ./internal/sessions ./internal/gui ./internal/usage: sessions and usage ok; gui red only in TestMainWindowCorners/macOS_26_SDK, #3949 (mote's macOS 27, titlebar code this change doesn't reach). The full ./... was not run before the push: mote had other sessions' full suites running at load ~180. Not tried: Jumy's own session files or ledger (not available), so the rest of the 900M is unexplained; Kimi Code's subagents (it sends no session header magpie knows, so its gateway rows aren't sessions); the GUI Playwright suite (no asset changed). |
||
|
|
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).
|
||
|
|
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).
|
||
|
|
7fd65aad56 |
sessions: a Codex listing reuses the last one's names, and dirent its room (#2278)
Each Codex listing (several a minute of the page's polls over a long history) made every rollout's path and key again, grew a new dirent.Listing an entry at a time for every day folder, and gave each rollout name a slice of its own in distinctCodexFiles: ~230 MB of a minute of polls, from 20k unchanged rollouts. - listedRollouts keeps each day folder's rollouts as its last listing found them; a rollout listed before keeps its path and key (made only from its folder and name) and takes its size and time now. A folder is kept again only when a rollout came or went. - dirent.Stats takes its listing from a pool and its callers (listedRollouts, statFiles) give it back with Done once read; Done clears it. getattrlistbulk's 64 KB buffer is pooled too. - distinctCodexFiles keeps a name's first file in a map of ints, and a slice only for names with more files. New tests: TestListedRolloutsKeepTheirNames (a grown, a removed and a new rollout; reused strings) and TestStatsAfterDone. Run on mote. Written on |
||
|
|
7037cd9801 |
sessions: the reads under a hold share one listing, and a pass's path set is reused (#2278)
A minute of the page's polls over a long history (52G Codex, 13G Claude) allocated ~70 MB copying the held Codex listing for every reader, ~35 MB on pruneCalls' and refresh's path maps, and ~40 MB more on distinctOf's set and the Requests/effort listing made for each ask. Allocation is what drives the collector's ~33% of CPU. - heldFiles and the warm-up's listing hand every reader the same slice, clipped so an append is made elsewhere. Every caller only reads it or copies it (distinctOf, appends into their own); the one that sorted it, traceLineFiles, now concatenates into its own slice. - distinctOf, pruneCalls and refresh take their path sets from a pool and clear them after the pass. - CallSourcesAndCodexIdentities builds its listing in a pooled buffer given back once its sources are taken. TestWarmUpListsRolloutsOnce checked that a caller could write over the kept listing; it now checks the listing is shared and clipped. TestHeldListingShared and TestListingPoolsGiveBackEmpty are new. Run on mote at this tree, rebased onto |
||
|
|
7db0810b03 |
sessions: stats asked again unchanged are not encoded again; lists made at their size (#2278)
The Sessions page asks for /api/sessions/stats (7, 30 and every day) and the list every poll. On a full history (52G Codex + 13G Claude) the stats for every day are ~6 MB of JSON, encoded and hashed again on each ask even when the page already had them, because the read behind every 10s replaced the kept stats with an equal copy. - statsKept has a gen, kept when the read behind finds the same stats (sameStats: From, To, Keys, Days, what is sent). The handler keeps the tag last sent per ?days with its gen and agent names, and an ask with that tag is answered X-Magpie-Same without encoding. Only the 32-char tag is kept, no body. - MergeExternalStats grows Sessions once for every external session; a Clip and then an append a session copied the whole list over and over. - listSessions makes its page and its latest map at their size. Run on mote at this head (rebased on |
||
|
|
68b31ce236 |
sessions: a poll's file lists, merges and copy groups are made once (#2278)
Each Sessions or Usage poll listed every agent's files several times and copied the Claude Code and Codex lists twice: callFilesWith made a deduplicated slice and set, then callSourcesWith and allFiles appended to it and deduplicated it again. Now callFileLists hands out the lists, and distinctOf builds one slice and one set at their combined size. More cuts on the same poll path: - allowed (the read-consent gate, |
||
|
|
45fce0495d |
sessions: a poll's session list is sorted and gathered in slices made for it (#2278)
listSessions kept each group's latest time in a map and sorted a key slice that looked it up; the /api/sessions handler grew its native-key map and its output slice by appending. Under 80s of polls while a session was written (ab17, v0.1.1978 with stats kept) those were 72 MB (latest map), 129 MB (listSessions out) and 139 MB (gui out.Sessions) of 5.4 GB allocated. The groups are now one slice of key and latest, sorted once, and every output is made at its size. Run at this head (mote, Go 1.26.8): - GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions/ ./internal/gui/ ./internal/usage/: clean. - go test -timeout 45m ./internal/sessions/ ./internal/gui/: sessions ok; gui red only on TestCoreScriptBudget (#4133, red on main since |
||
|
|
af8f3a9399 |
sessions: a new install reads no agent's session history until the user allows it (RustCats on X)
RustCats on X: a fresh magpie showed every agent's session history on
the Sessions page before anyone agreed to it, and asked for a per-agent
choice instead.
- sessions.Reads(agent) (internal/sessions/access.go) is the one gate,
from settings.SessionReads {Asked, All, Agents}. Every lister asks it,
the aggregators (allFiles, callFilesWith, callSourcesWith,
traceLineFiles, wslFiles, DesktopDataDirs) filter by it again, and
readers of an already-listed session (TranscriptOf, ContentOf,
SearchSession, SubagentTranscript, CarryOver, ReadCallSource) return
ErrNotRead, so a cache from before a switch was turned off goes no
further. The Sessions list, stats, /api/sessions/overview, the call and
trace indexes, Usage's agent-file calls and the Codex/Pi title readers
all pass it.
- SettleReads decides once and saves: an install with sessions.json or
a calls-v* cache read sessions before and keeps all on; a fresh one
reads none, not asked. A saved value is never replaced; save, sync and
restore keep it (KeepOwn); only SetSessionReads writes it. An
unwritable settings.json reads nothing this run.
- GUI: GET/POST /api/sessions/reads. While not asked, the Sessions page
shows a consent card: each agent found (by a stat of its folder only)
with a switch, Allow selected and Allow all. Settings > Privacy >
Agents' session history has "Agents found later" and a row per agent.
Strings in en, zh, zh-TW, ja, de.
- CLI: magpie sessions read [on|off all|<agent>...]; magpie sessions
says on stderr when nothing is allowed yet; the TUI's empty Sessions
page says how.
Read either way, because none of it lists or shows a session: the
gateway's own usage ledger, its projections and the conversations it
recorded (magpie's own records, so usage and cost keep working); the
agents' config and sign-in files; Claude Code's and Codex's
history.jsonl last-used time and a session file's mtime for a quota's
first use; Codex's newest rollout's last line before magpie restarts
Codex (codexTurnOpen).
Tests: TestFreshInstallReadsNoAgentUntilAllowed,
TestSettleReadsKeepsWhatWasThere, TestSessionReadsRoutes,
TestSessionsRead, TestSessionsNotAskedSaysHow, sessions-reads.test.cjs
(26 cases: consent and Settings in 5 languages, Chromium and WebKit,
390 to 900 wide).
Run on mote:
- full Go suite (gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui,
GOOS=windows go vet, go build, go test -timeout 45m ./...) at this
change on
|
||
|
|
168dcf455d |
sessions: a hold counts holds, not times (#4114, #4177)
heldFiles reused a listing taken after the latest hold began, judged by
time.Now(). On Windows two time.Now() a moment apart can be equal, so a
hold begun in the tick a listing was taken in read that older listing
as its own: TestOneListing red. Its t.Fatalf came before done(), so
the package-global hold stayed set and every later test read a stale
listing: TestPurgeOne, TestPurgeAll and TestUnchangedPackedNotReadAgain
red, and TestShareListing / TestReadNotHeldByAnotherRead waited forever
(the 45m package timeout in #4114 and #4177).
- held.gen counts holds begun; a listing carries the gen it was taken
under and is reused only under the same gen. No clock is read.
- holdsEnd(t) ends any hold a test left, so one red names itself and
doesn't take the package down with it.
- TestShareListing, TestReadNotHeldByAnotherRead and
TestReadWaitsForAFirstReadUnderWay select on the other channel too,
so a missed listing fails at once instead of hanging.
Run (Windows: win-run on xiaomi-gpu; macOS: mote-run; Linux: wsl-run):
- Windows, old one_listing.go: TestOneListing red alone. Fixed:
TestOneListing and TestShareListing -count=500 green.
- Windows, fix without holdsEnd: the cascade comes back with each test
red and named, no hang. With it: internal/sessions green but for
TestAgySessions/TestAgyRowOnly (#4115, red at main too).
- macOS and Linux: internal/sessions ok, at the rebased head too.
- GOOS=windows go vet ./..., GOOS=linux go vet -tags nogui ./..., go vet
./... on mote: ok. gofmt -l clean.
Broken by hand: the time comparison put back (red on Windows, above);
holdsEnd removed (cascade, above).
Not tried: the full go test ./... on mote (six other suites were
running there; owner rule: don't wait behind it).
At the rebased head (on origin/main
|
||
|
|
9474eaf9cb |
sessions: Raft's Pi agents' sessions are listed as Raft's, with their prompts, calls and delete
Raft (slock's raft-computer) runs its agents on Pi and keeps each one's Pi SDK session files in that agent's folder: <slock>/agents/<id>/ .pi-sessions/<ts>_<id>.jsonl, or .builtin-sessions/ for its built-in runtime. <slock> is $SLOCK_HOME or ~/.slock (%USERPROFILE%\.slock on Windows, the distro's ~/.slock under WSL). Read from raft-computer 1.0.14's PiDriver (buildPiSessionDir), BuiltInDriver and resolveSlockHome, and a read-only listing of ~/.slock here. runtime-sessions/ holds handoff notes, no sessions, and is not read. - The Sessions page lists them as Raft's (agent "raft", in agent.Clients' others), titled and opened with their prompts as Pi's are. - Their calls count on the Usage page as Raft's; calls through magpie stay the gateway's, as Pi's do. - Raft's Pi uses the user's own ~/.pi/agent, so a request it sends through magpie reaches the gateway as Pi's under the same session id. sessions.GatewayKeys gives a Raft session both "raft|ID" and "pi|ID", so the gateway's copy is not listed twice nor counted twice (Merge, stats, NativeIDs, the GUI's Via). - Delete and restore work as Pi's: the one file goes to the trash, and a folder beside it is left (the agent's workspace is not the session's). A session written in the last minutes is refused as active. - No resume command, no carry and no trace export: Raft starts its own agents, and nothing outside it can resume one. - SLOCK_HOME is passed through agentenv like the other agents' homes. Run (at 958ad9f10 on |
||
|
|
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
|
||
|
|
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 |
||
|
|
a54e336e44 |
sessions: Desktop's Code tab in its 3p mode is Claude Desktop's, not Claude Code's
cybercaius (Discord #help) runs Claude Desktop through magpie's gateway
and saw Desktop's work listed under another agent. Desktop set to a
gateway is in its third-party inference mode, and Desktop 2.7032 then
starts its Code tab's Claude Code with CLAUDE_CODE_ENTRYPOINT
"claude-desktop-3p" (its nK: type "3p" -> "claude-desktop-3p", else
"claude-desktop"; the value is in Claude Code's own entrypoint enum).
The calls reader (calls.go) and the trace reader (traces_claude.go)
only took "claude-desktop", so every call from such a session was
counted as Claude Code's. Both now ask one desktopEntrypoint.
This is what Desktop's transcripts say. The gateway's own attribution
of a live request (agentOf, by key then User-Agent) is not changed:
with Desktop's own key magpie-claude-desktop it already names Desktop,
and the reporter's misattributed title request was not reproduced.
Run on mote: go test ./internal/sessions -run
'TestCallsDesktop3pCodeTab|TestClaudeTraceSubagentsShareSessionWithoutIDCollisions|TestCalls'
ok. Broken by hand: both readers back on == "claude-desktop" ->
TestCallsDesktop3pCodeTab and the trace test's claude-desktop-3p case
fail. Rebased on origin/main
|
||
|
|
bc247a8cc4 |
sessions: the Sessions page answers before a first read of a long history
hey_boyce on X: "会话tab等的时间有点长", the page standing on its skeleton rows on its first open. /api/sessions/manage read every file it had no usable parse of whole before answering: the agent shown, and every agent with a gateway session for its ids (Codex's 52 GB too while Claude Code's page was shown). That is every file after a first start, a cacheVersion bump, or a Claude Code or Codex file whose kept parse can't be read on after a restart. |
||
|
|
536a98316d |
sessions: a poll over unchanged files gets the stats the last one read (#2278)
The Usage page asks for its range every 10 s and the Sessions page for 7, 30 and every day every 15 s. Each read put every session of every range together again, though between two polls the files mostly haven't changed: statsReadAll allocated ~1.1 GB per 80 s of polling, a fifth of all magpie allocated. statsKept keeps each range's Stats (at most 8 ranges) and the native keys, with what they were read from: every listed file's path, key, agent, size, mod time, main/read-only, WSL distro and its parse pointer (a published parse is never written; a changed file gets a new one), today, and the cache generation. It also keeps the answers the read got from the prices, Codex's thread names and Claude Desktop's names, and asks them again before it hands anything out. When any of these differ, everything is read again. The listing and the refresh of changed files still run on every poll. MergeExternalStats wrote into the Stats it was given (a day's usage rows, an append into spare room in Sessions, sorts in place). It now copies whatever it changes, so a kept range is never written. What this doesn't help: while an agent is writing a session, every poll sees a changed file and reads everything again. Reading only the changed sessions is the next change. Run at the pushed head on mote: - GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions/ ./internal/gui/: ok. - go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/ ./internal/usage/: sessions ok, usage ok, gui red only TestMainWindowCorners/macOS_26_SDK (#3949, open, same as main). - New tests: TestStatsKeptBetweenPolls (the same backing array on an unchanged poll; a grown file and a price change are read in), TestStatsKeptNewDay, TestStatsKeptRangesBounded, TestMergeExternalStatsWritesNoInput. TestStatsAllRangesOnePass now forgets the kept ranges before each single read. - Broken by hand, each red: keptFor always missing (TestStatsKeptBetweenPolls, "put together again"); the price check dropped (repriced cost unchanged); MergeExternalStats without its copies (TestMergeExternalStatsWritesNoInput). - Real data (a copy of the owner's history, ~34k sessions), v0.1.1978 against this: /api/sessions/stats?days=0/7/30 and both overviews asked 4 times 12 s apart, each pair byte-identical (1.97 MB for days=0). - A/B, 80 s of GUI polling, v0.1.1978 against this: allocated 5512 to 4480 MB, statsReadAll's share 1108 to 261 MB (the listing); GC 3.90 to 3.42 s, madvise 1.05 to 0.61 s, CPU 28.6 to 25.3%, avg RSS 1061 to 1019 MiB. mote's load was 20-40, so latencies aren't compared. The A/B binary was built before the 8-range bound was added. - Rebased onto |
||
|
|
f193c3865f |
sessions: a stats share keeps its days and models in slices, not maps (#2278)
statsOfRange made each session three maps per range on every poll (its models, the dates it counted and its per-date shares) and a list of the range's files first. A session has few models and few days, so they are small slices now, and the files are filtered as they are read. The output is the same: models are summed in name order and listed by tokens, then name, as before. Measured on mote (Usage stats polled every 5s with gateway feed, heap diff 120s to 200s, A/B against v0.1.1971 |
||
|
|
2f55483718 |
sessions: a stats share makes its tools and skills maps only when a day has some (#2278)
statsOfRange made four maps (tools, skills, skillLast and a day's tools) for every session of every range on each poll, and most sessions' days use no tools or skills. They are made now on the first day that has one. Measured on mote (Usage stats polled every 5s with gateway feed, heap diff 120s to 200s, A/B against |
||
|
|
905166d786 |
sessions: Codex identities are kept while no rollout changes (#2278)
Every Sessions and Requests poll built the Codex thread identities again
over every rollout (CodexIdentities, CallSourcesAndCodexIdentities, List,
Stats, ListAgent, Get), though nothing had changed since the last poll.
codexIdentitySnapshot now keeps the identities it built for the last four
file lists, with what each Codex rollout gave them from: its key, the
cached identity's value and whether it conflicts. A list whose rollouts
give the same is handed the kept map. The maps are now shared, so only
read: CodexIdentities' comment says so, and the old test that deleted from
one is replaced by TestCodexIdentitiesKeptWhileNoRolloutChanges.
Run at this head (
|
||
|
|
fa2dfc1458 |
sessions: the page's 7, 30 and all-time stats are read again in one pass (#2278)
statsFor keeps each ?days range the Usage page asks for and reads it
again behind the page once it is 10s old. Each of the three ranges
(7, 30, 0) was its own combinedSessionStats: a listing of every Claude
Code and Codex file, a refresh, the Codex identities and task titles,
every session assembled for the native keys, and the ccCopies, all
identical whatever the range. With 25k Codex rollouts that was ~4.2s of
CPU a minute on a polled page.
Now a stale range takes every other stale range with it, and
statsReadAll does the shared part once and sums each range from it
(statsOfRange). The sessions assembled for the native keys are reused
for each range's list instead of assembling them again.
Rebased onto b4267de59; the tests and vets below ran again on mote at
the rebased head, same results. The A/B ran before the rebase:
- TestStatsAllRangesOnePass (new): ranges 0, 1, 7, 30 from one pass
are each DeepEqual to statsRead of that range alone, and the files
are listed once.
- GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions
./internal/gui: clean.
- go test ./internal/sessions ./internal/usage: ok. ./internal/gui: ok
but for TestMainWindowCorners/macOS_26_SDK, the macOS 27 red in #3949
(titlebar, untouched here).
- A/B on mote, sandbox HOME with a copy of the real 115MB usage.jsonl
(240k rows) and 25k Codex rollouts, the page's 10 reads every 5s and
4 appends a second, 240s each, v0.1.1959 (
|
||
|
|
3ec9babe7d |
sessions: the overview points to the sessions it sums up, not copies (#2278)
Stats.Overview copied every Summary (~400 bytes) into its working slice, then cloned that slice once per Top ranking. Over 34k sessions the Sessions page's poll allocated ~1.5 GB in two minutes this way while an agent worked (alloc profile of v0.1.1928 on mote: `in = append` 958 MB, slices.Clone 557 MB). It now ranks pointers into st.Sessions and copies only the k sessions each ranking keeps. shapes, toolUse and skillUse take the pointers. TestOverviewCopiesOnlyItsTop: a second Overview over 5000 sessions allocates at most half of their Summaries' size, and its count and rankings are what they were. Red on the old code (14,923,144 bytes over a 1,020,000 bar), green on the new. A/B on mote (34,040 session files, 240k-row usage.jsonl, the feed run of run2278c.sh: 230s, feed from 60s, Usage and Sessions pages polled), v0.1.1928 code vs this change. mote's load was 47 to 66 from other runs throughout, so the numbers are noisy: avg CPU after the feed starts 122.8% -> 69.4% heatmap poll mean 6.97s -> 4.84s all polls mean 3.11s -> 2.16s footprint peak 685.6M -> 626.1M footprint at the end 402.8M -> 337.5M Run on mote, at base |
||
|
|
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 (
|