e4e9eb0928becfa4e48484dde85ef5032671d582
391
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
e4e9eb0928 |
usage: a ZCode call to a provider added by hand at magpie's address is not a local session's (jiangshangmuyun on X)
The Usage page listed one ZCode call as "new-provider · 本地会话" among the
gateway's own rows for the same Trae CN DeepSeek calls. The reporter has one
ZCode window and routes everything through magpie.
Cause: the user added magpie to ZCode by hand as a provider of their own
("new-provider", base URL magpie's gateway), not through magpie's connect,
which writes the id "magpie". ZCode records that id beside each reply, and
readZCodeCalls left out only "magpie"/"dial" (ocGatewayProvider). Its calls
were read from ZCode's database as well as logged by the gateway, and only
hidden again where pairing by session, tokens and end time matched; a call
whose counts didn't agree was listed twice as a "local session".
Fix: zcodeGateway also takes any provider whose base URL, in ZCode's
config.json or provider_config.json, is this machine (loopback, localhost,
0.0.0.0, one of its own addresses) on the gateway's port (MAGPIE_ADDR or the
saved port). Such calls are left out before pairing, as "magpie" ones are.
zcode's call parse version is 4, so cached shards are read again. Like
workbuddyGateway it reads the configuration as it is now. The label itself
is unchanged: a call that did go straight to a vendor is still a local
session's.
Siblings filed, not changed: OpenCode/MiMo (ocGatewayProvider), Pi
(piGateway) and dsh still match the gateway by provider name only (#7193).
Go run on mote at this change on base
|
||
|
|
3869aee3b0 |
sessions: agy's calls in T3 Code are on Usage → Requests
zzzkl on X: requests from Antigravity in T3 Code weren't on Usage → Requests, while a plain agy's were. T3 Code (pingdotgg/t3code, read at 00c6adbd) runs agy for each Antigravity instance as an ACP server on the instance's own Google sign-in: `agy acp --gemini-dir <profile> --app-data-dir antigravity-acp` (antigravityAuthSupport.ts), the profile being <T3 Code's folder>/userdata/providers/antigravity/<sha256 of the instance id>, the folder $T3CODE_HOME or ~/.t3 (dev for its dev server). Those requests go to Google, never through the gateway, and magpie's agy reader looked only in ~/.gemini/antigravity-cli, so nothing counted them. agy writes the same transcript_full.jsonl there as in its own folder (agy 1.5.10 run that way in a sandbox against a fake Gemini endpoint; the fixture is its bytes). agyCallFiles now reads every T3 Code profile's antigravity-acp too, and Found lists agy for those folders, so the read consent covers them. T3 Code's folder is appdir.T3Code, shared with agent's t3Base. Siblings: `agy acp` from any other ACP client with the defaults writes to antigravity-cli, already read (agy acp --help). T3 Code's magpie instances (Claude, Codex) go through the gateway and are counted there. Run: TestAgyCallsInT3Code (default folder, T3CODE_HOME, ~/ form) red on the old calls_agy.go/access.go with 0 calls, and with Found() = [claude codex] when only access.go is old; green with the change. gofmt -l clean; go vet (darwin, GOOS=linux, GOOS=windows) of appdir, agent and sessions on mote. Full suite (go test -timeout 45m ./..., mica, at |
||
|
|
14b6b95556 |
sessions: a session resumed into copies isn't read whole again after a start (shangyuan0818 on X)
shangyuan0818 on X, on the latest Windows build: after using an agent, Sessions took 18 s to load. They had ~100 Claude Code sessions of 30 to 100 MB and read Claude Code only, and guessed it was dedup, since ccusage is slow on the same files. Cause: older `claude --resume` wrote each resume as a whole copy of the session under a new sessionId. ccFamily judges such a group by every file's message uuids (ccUUIDsOf), and ccRest reads each copy for what its keeper doesn't hold. Both were kept in memory only. cc-rest.json kept the rests, but without the uuids they were read from (ids nil). After a start, the first turn of the session the copies are kept in changed the group's signature and its size, so every file of the chain was read whole twice: gigabytes before Sessions showed. Codex is not read with Claude-only reads (the cold load is the same with its folder empty). Fix: the uuids of each file of a group are kept on disk, one file each in cc-uuids/ (named by a hash of the path), with the size, mtime, the offset read to and a prefixHash of the bytes up to it. A start reads them back and goes on from the offset only while the hash still matches the file's start; otherwise the file is read from its start. The rest ids are kept in cc-rest-ids.bin under the rest's key, so a keeper that only grew leaves its copies unread after a start too. Entries whose session file is gone are pruned once a start. Trash drops an entry. Reset forgets the in-memory uuids, like a real start. Not changed: a first start (no cache) still reads each copy three times (parse, ccUUIDsOf, ccRest), filed as #7143. Windows (xiaomi-gpu, Windows 11, CGO_ENABLED=0 builds, Claude-only reads, sandbox HOME). The fixture is 5 resume chains of 20 files, 30 to 107 MB each, 6.9 GB. Time is for the page's three requests together. origin/main this change cold, no cache 20.2 s 17.6 s warm restart 0.30 s 0.30 s restart after 1 keeper's turn 3.29/3.14 s 0.38/0.25 s 1 keeper's turn while running 1.60 s 0.11 s restart after 5 keepers' turns 7.25 s 0.92 s 5 keepers' turns while running 3.32 s 0.78 s The profile of a restart after a turn on origin/main was ccFamily → ccUUIDsOf (1.23 s) and ccCopyStates → ccRest (1.14 s) in scanThin. The kept uuids take 2.4 MB for the fixture's 100 files. Tests (internal/sessions/cc_copies_test.go): - TestClaudeKeeperTurnAfterAStartReadsNoCopy: a turn, then Reset, reads no file from its start, and the turn is counted. - TestClaudeKeeperTurnTheBranchHeldAfterAStart: a keeper that grows, after a start, with a message the branch held on its own counts it once. - TestClaudeKeptUUIDsOfAFileWrittenOver: an entry whose file was written over doesn't stand. - TestClaudeKeptUUIDsRoundTrip. Run at this tree: - go test ./... -count=1 -timeout 45m on mote: 102 packages ok, 2 red, both filed: internal/cli's TestHealthcheckFindsTheRunningGateway WithoutMagpieAddr, TestUpdateRestartsTheGatewayItFindsWithoutMagpieAddr and TestUpdateFindsAMagpieThatWroteNoRecord (#6471, #6223: they ask whatever serves 127.0.0.1:3425 on mote), and internal/gateway's TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (#7117, red on main). - go test ./internal/sessions -race -count=1 -run TestClaude -timeout 25m on mica: every new test passes; 2 reds, both data races filed and outside this change: TestClaudeCdKeptParseReadAgain (#6213, red the same at |
||
|
|
de58a3879b |
sessions: a cold read packs idle Claude sessions' calls into one file
shangyuan0818 on X: on Windows, Usage -> Sessions took 18 to 25 s with long Claude Code sessions. The cause: a cold read wrote a calls-v15 .gob shard and a .rev for every Claude session, about 21k files for 12k sessions, and Windows Defender scans each file as it is closed. Sessions not changed within the hour are now written into one calls-v15/*.pack per pass (MPCALLS1 magic, the frames, a gob index of path/offset/count, length, CRC32, magic). It is written to a temp file and renamed, and flushed at the end of a pass, at checkpoints, in Saved and every 32 MB. A session's own shard is read before the pack, so a session that grows gets its own shard and its lines are appended there as before. A bad pack means the source is read again. The hourly prune sweeps packs no session points at. Working sessions keep a shard and a .rev as before. Measured on xiaomi-gpu (Windows 11, Defender on), fixture of 12,016 Claude session files, no magpie cache, first /api/sessions reply, the runs alternating old and new: origin/main build: 31.67 s, 25.26 s, 20.74 s this change: 5.92 s, 5.85 s, 5.65 s restart with the pack written: 1.97 s and 2.16 s; then 0.25 to 0.31 s. The cache held 1 .pack and 4 .gob. Tests (call_pack_test.go): TestColdSessionsReadWritesOnePack, TestPackedCallsServeRequests, TestPackedSessionGrows. With the pack branch turned off by hand the first fails (.gob:63 .rev:62) and the second finds 0 packs. Run at 4ace48feb (this change on origin/main |
||
|
|
5cf1d3846a |
sessions: an agent left off in the first "allow selected" is asked about once more, on Sessions and Usage › Requests
baysonfox on X: with magpie installed after Antigravity 2.0, the app's
sessions and calls made without magpie never showed in Usage, while agy
CLI's did. The first consent named the app off beside agy, and a named
agent was never "new" again, so nothing asked about it and nothing on
Usage said why. The reader is fine: the app's calls come from its own
SQLite steps (antigravityRead), read once allowed.
Nothing is turned on by magpie: the gate is the user's privacy choice.
Instead:
- settings.SessionReads gets Kept: agents turned off on their own (a
sessions/reads post without `all`: Keep off, a Settings › Privacy row,
`magpie sessions read off <agent>`). A post setting it on takes it out.
- readsNow's New: off, found here and not Kept (was: never named). So an
agent left off in the first choice's list is asked about once more,
as one found later already was.
- Usage › Requests shows a line above its rows for those agents
(readsLater in the usage plugin): Count {names} / Don't count, the
same {agents} posts as the Sessions page's laterCard. Gone after
either answer; sessions/reads read at most once a minute.
- Old data: an agent turned off in Settings before Kept existed has no
entry and is asked once more, for every user with such an agent.
Tests:
- TestSessionReadsUncheckedAgentAskedAgain (count, keep off): sandbox
HOME with testdata/agy-sessions and the real Antigravity 2.30
conversation (antigravity-2.30-tools); after the first choice the app
is off and New, has no rows in /api/usage/requests; Count brings its
rows in, Keep off keeps none, and neither is asked again. Red on the
old code (New false after the first choice).
- TestSessionReadsTurnedOffNotAskedAgain: off on its own, under all true
and all false, is neither on nor New.
- usage-reads-note.test.cjs: the Requests line in Chromium and WebKit,
en/zh/zh-TW/ja/de at 900/420/390px, both answers, buttons inside the
line, no sideways scroll; red on the old code (no #ledReads).
Run on mica (mote was full: load 40+, another GUI suite on it), rebased
on
|
||
|
|
d2fa7d8d79 |
sessions: an Antigravity app conversation shows what was said, not only its title
@yansheng1003 on X: the Sessions page showed an Antigravity 2.0 conversation's title and preview only. HasTranscript left "antigravity" out, since conversations/<id>.db's step text is encrypted at rest, so the row had no Show conversation and /api/sessions/transcript said "this agent's conversations can't be shown". The app also writes every step in plain text beside the database: brain/<id>/.system_generated/logs/transcript_full.jsonl in the same store, in agy CLI's format (user input, planner responses with their tool_calls, tool results). Antigravity 2.30's language server writes it in the stable store and in Insiders' (both checked: run in a sandbox HOME on Windows against a fake model that called read_file). - transcript.go: antigravity has a transcript; readTranscriptOf reads it through agyTranscript (antigravityTranscriptOf), so the viewer, TranscriptAt, search, the said index and the Markdown export all get it. A conversation with no transcript file is ErrNoTranscript, as before. - antigravity_app.go: antigravityTranscript derives the path from the database's (stable, Insiders, a WSL distro's); its size and time are folded into the session file's with the -wal's, so a step it adds reads the session and the said index again. - search.go: linesFile is false for antigravity, so the encrypted .db is never pre-scanned for the words. - testdata/antigravity-2.30-tools: that real conversation (db with the WAL checkpointed, summary row, brain/ logs). Tests: TestAntigravityAppTranscript (stable, Insiders, WSL: parts, search hit and miss, Markdown), TestAntigravityAppNoTranscript, internal/gui TestSessionAntigravityConversation (/api/sessions marks it, /api/sessions/transcript gives the five parts). Run: on mica (mica-run) at base |
||
|
|
65c9a2e411 |
sessions: the WSL tests wait for the distro's first listing, however busy the machine
TestWSLAgentsGoneListingDrops went red in a run of internal/sessions on mica at load ~48: "answered=true: want 7 sessions, got 0". The first List waits at most wslFirstWait (3s) for the WSL walk, as the Sessions page should, and on a busy machine the walk outlasts it, so the count read nothing yet. Every test built on wslDistro counts that first listing (TestWSLSessionsListed, the Antigravity and Kimi WSL tests), so wslDistro now gives it a minute; TestWSLFirstWaitIsWaitedOnce still sets its own 500ms after. Broken by hand: a 3.5s stall in WSLHomes gave the same red, "got 0", without this change and passed with it (mica-run, -run TestWSLAgentsGoneListingDrops). Alone, unstalled, the test passed 5 of 5 on the old and new code. Run: on mica (mica-run): go test -count=1 -run 'WSL|Antigravity|Agy|Gone' ./internal/sessions ok; gofmt clean. The full internal/sessions run where it went red is in the next commit's record. |
||
|
|
2416beed69 |
sessions: a tab's count is the rows it lists, and a Pi subagent's calls are no row delete can't find (lurx98 on X)
lurx98 on X (tweet 2122972281534402597): on the Sessions page the tabs said Codex 6 and Pi 8. Codex, opened, said 0 and "no sessions yet"; Pi said 6 from any other tab. Deleting a row titled "Task: 只读事实核对…" toasted "no such session". Two causes, both about one count path and the list disagreeing: - Codex: agentCounts counted every rollout, while the list drops a subagent thread whose parent thread is gone (keptSubagents, |
||
|
|
3ec89c5224 |
codex: the takeover's end waits for the chats on magpie the Codex app has open (milianxinqi on X)
milianxinqi on X, the Codex app: "Model provider mismatch. This chat uses
magpie, but your current provider is OpenAI. Switch to magpie to
continue." ("用的好好的,codex 突然就弹这个了"), with nothing disconnected.
Cause. With the ChatGPT account Codex is signed in to held (out of its
allowance and credits), magpie is Codex's provider (the codex.out
takeover, #540) and new chats start on magpie. When the account has room
again (its window's reset, a switch to another account, or the account
the user keeps Codex on,
|
||
|
|
42c43c0020 |
sessions: an agent found after Allow selected is asked about once (Antigravity 2.0)
baysonfox on X: Antigravity 2.0 desktop sessions showed on the Sessions
page only while the app was connected to magpie; agy CLI's always showed.
Cause: not the file reader. Real Antigravity 2.30 (signed out, no model,
sandbox HOME on the Windows box) writes ~/.gemini/antigravity/
conversations/<id>.db, conversation_summaries.db and brain/, and
internal/sessions parses them. The gate is settings.SessionReads:
"Allow selected" (and the Usage readsNote's "Count …") saves all:false,
so an agent installed after that choice is never read and never asked
about again. Gateway-recorded sessions skip the gate, hence "only when
connected".
Fix: /api/sessions/reads marks a found agent `new` when the choice was
made, it isn't read, isn't named in Agents and is on disk (Found(), which
checks every OS's path). The Sessions page shows one quiet card for those
(laterCard): "Show their sessions" names each on, "Keep off" names each
off, so it isn't asked again. No new endpoint; the card posts the
existing sessions/reads.
Tests: TestSessionReadsNewAgent copies the real 2.30 files
(internal/sessions/testdata/antigravity-2.30, sandbox paths only, no
tokens) beside agy-sessions, with agy allowed by name: antigravity is
off and new, nothing listed; after the answer it is not new, settings
keep all:false/agy:true, and its one session is listed only when shown.
TestSessionReadsNewOnlyWhenNamed: not asked, allow all, all with agy off
mark nothing new. sessions-reads.test.cjs: the card, both answers, posts
and no card after reload, Chromium and WebKit, 5 languages, 900/390px.
Run at d7d62d889, on mote, then rebased onto
|
||
|
|
7707ba9adb |
sessions: a compaction that doesn't fit its line goes as text, never as magpie's seal (hey_boyce on X)
hey_boyce on X: Codex, talking to OpenAI itself, got 400
invalid_encrypted_content "The encrypted content for item
cmp_magpie_1794916786407450000 could not be verified".
Cause: PortCodexRollouts writes magpie's compaction item (magpie1:
base64 summary) as Codex's own summary message, keeping each line's
length, since a paginated rollout keeps places by byte. A message
longer than the line (a short summary under Codex's ~400-char prefix)
was left as it was, so the magpie1: seal stayed in the rollout, Codex
replayed it to OpenAI every turn, and the thread was stuck. The
incremental pass never looked at such a rollout again.
Change:
- fitShorter: when the full message doesn't fit, the summary goes
under a short heading, then cut to fit (rune-safe, "…"), then
with no heading. If nothing fits, a standalone item is retired as
{"type":"magpie_compaction"}, which Codex reads as unknown and
never sends.
- In replacement_history an unknown item IS sent (as "other"), and
OpenAI refuses it ("Invalid value: 'other'"; seen with real
codex-cli 0.165.0 and 0.169.1). So a compaction or reasoning item
retired there is left out with its metadata entry, and
magpie_reasoning items main's PortCodexRolloutsLeft already wrote
there are taken out (retiredInList). That was a sibling bug: those
threads failed the same way.
- codex-portable.json gains refit: a state from before makes one
whole pass again, so rollouts already left with the seal are fixed.
- The gateway's last line: a 400 naming an item of magpie's own
compaction asks again with its summary message in its place
(withoutItem), not with the summary dropped.
- codexsummary.Summary decodes the seal; Message uses it.
- docs/subsystems/gateway-routing.md says all of this.
Run (on mica, at this head rebased on
|
||
|
|
8e1534f5f9 |
sessions: read LiveAgent's sessions (#6741)
Usage › Sessions and the Sessions page now list LiveAgent's sessions
with their title, time, model, tokens and cost, and show their
conversation.
- Where: K-brain keeps each session at
<root>/sessions/<project>/<id>/session.jsonl (older ones right under
sessions/). sessions/.runs and sessions/.deleted-history are skipped.
- Root: $LIVEAGENT_HOME, then $K_BRAIN_HOME, then
~/.liveagent/data-dir.json, then ~/.liveagent. The rule now lives in
sessions.LiveAgentDirIn, and agent.liveAgentDir calls it, so it has
one owner.
- Reading: K-brain rewrites the file whole, so it is parsed whole. The
first line is session_meta (id, title, cwd, running totals).
- Tokens:
- Each reply's own usage counts on the day it came back.
- What the totals (model_usage, else usage_in/usage_cached/usage_out)
hold beyond those replies, such as a compaction's call or a rewound
reply, counts on the last message's day, together with sub_usage.
- Cache reads and writes are taken out of prompt_tokens.
- Forks: a fork's copies of its source's messages (seq <= fork_seq) are
the source's, and count in neither the fork's messages nor its totals.
- Subagents: a subagent's own session (task-<parent>-<task>, task_id
set) is filed under its parent with its activity, but no tokens,
because its spend is the parent's sub_usage already.
- Not added:
- a Calls reader: the gateway's own record of LiveAgent's calls
carries no session id, so it would count them twice;
- resume and delete: LiveAgent has no resume command.
- Skills: SkillsManager read (skill://<name>/SKILL.md) and Read of a
skill path are counted.
Run (mote, mote-run, at
|
||
|
|
a75a1fffcb |
provider: agy's Orchestrator (Argon), gemini-pro-orchestrator-g1-pro, is priced as Gemini 4 Argon (mu33410 on X)
mu33410 on X: agy's Orchestrator model showed no cost. |
||
|
|
64ad53f6c7 |
sessions: magpie sessions search and show, for agents (yansheng1003 on X)
yansheng1003 asked for a command or skill an agent can call to search
and read its sessions. magpie had the search on the Sessions page and
in the Magpie Sessions MCP server, but not on the command line.
- `magpie sessions search <words…> [--agent] [--days N|today|all]
[--limit N] [--wait] [--json]`: the Sessions page's search
(sessions.SearchSaid over said-v1.db; SearchSaidSince adds the --days
bound), newest first, each hit named agent:id with title, folder,
time and the words round the match. A one-shot command waits for the
index (SaidReady, 60s by default, a progress line on a TTY only).
- `magpie sessions show <agent:id|id> [--find] [--from N] [--max-chars N]
[--json]`: the viewer's reader (TranscriptOf, TranscriptAt) as text,
from where the words were said; --json is the page's transcript.
- One renderer: the MCP server's search_sessions/read_session text moved
to sessions.SaidText/SessionText (said_text.go), with how to ask for
more given by each caller (TextHow). The MCP server's output is
unchanged (its tests pass as before).
- Consent: neither reads, nor makes the index, until the user has
answered which agents magpie may read; it prints notAskedLine and
exits 1. An agent not allowed is ErrNotRead for --agent and show.
- Flags: an unknown flag or a missing value is refused with the usage,
never taken for words or a session id; `--` ends flags; -h/--help
prints the subcommand's own usage (help_cli.go).
- Parity: /api/sessions/said and /api/sessions/transcript now map to
these commands (settings_parity_test.go).
- Library: magpie-sessions is a featured official skill
(magpie-community/plugins skills/magpie-sessions, pushed as plugins
cf5b0312), listed after magpie-quota.
- Docs: usage.html "Search what was said" in en, zh and ja; llms-full,
search indexes and docs-index.sums regenerated (node docs-index.mjs).
Run at 114eb4592 (rebased on
|
||
|
|
1549ccf743 |
sessions: agy's and Antigravity's own calls carry their first-token time and duration (guyng35955 on X)
Usage → Requests showed agy's own calls with no time to the first
token, no duration and so no speed. Those calls don't go through the
gateway, which is where other calls are timed, and the readers of agy's
and the Antigravity app's conversations never read the step's times.
Each step's metadata row (exa.cortex_pb.CortexStepMetadata) has them:
1 created_at, 6 viewable_at, 7 finished_generating_at. A model step is
created as its request goes out, so 6 less 1 is the time to the first
token and 7 less 1 the call's duration (stepTimesOf). A response that
two steps share is timed from the first step's start to the last's end.
A step with no end, or times out of order, has none (unknown, not 0).
agy and antigravity call-cache versions go to 2 so cached shards are
read again.
Checked with real agy 1.5.9 in a sandbox HOME against a fake Gemini
endpoint that held its first chunk 2.01s and ended at 4.03s: the row
said 2014ms and 4032ms. That row and transcript are the new fixture
(testdata/agy-times).
Run:
- TestAgyCallsCarryTheirTimes, TestAntigravityAppCallTimes,
TestAntigravityAppOneResponseTimedWhole, TestStepTimesUnknown: red
on the old readers (all 0ms), green on these (mote).
- go vet ./internal/sessions ./internal/usage, GOOS=linux and
GOOS=windows go vet ./internal/sessions, gofmt -l: clean (mote).
- go test -count=1 -timeout 45m ./internal/sessions ./internal/usage:
ok (mote, at
|
||
|
|
593517bf00 |
codex: T3 Code's threads on magpie stay on magpie (xxxxpouqqs on X)
xxxxpouqqs on X: "t3code 每次重新会话都出现类似于 The 'codex-2/gpt-6.1-sol'
model is not supported when using Codex with a ChatGPT account".
Cause: T3 Code's magpie · Codex instance runs Codex in ~/.codex on
magpie with `-c model_provider="magpie"` alone, so config.toml names no
magpie. At the next Sync, bringBack took every thread on magpie for a
leftover and moved it to the provider config.toml names (openai), in
state_5.sqlite and in the rollout. Codex resumes a thread on the
provider it was started on, so reopening a T3 thread sent magpie's
model id to ChatGPT. codexRetagOpenThreads (the Codex app's app-server
restart) moved locked or loaded ones the same way.
Fix:
- t3CodexRunsIn(home, dir): T3's magpie-codex instance runs Codex in
this home (no homePath, or one naming it; $T3CODE_HOME honoured; an
unreadable settings file counts as yes).
- bringBack then moves only threads another client started; a thread
whose originator is T3's stays on magpie (sessions.CodexThreadsBy
reads originator and model; a failed read moves nothing).
- codexRetagOpenThreads keeps T3's threads the same way
(RetagLoadedCodexThreadsBut).
Old threads: a T3-started thread an earlier magpie moved to the
current provider with a magpie model id (one with "/") is moved back to
magpie at the next Sync, for every user; a T3 thread started on OpenAI
with OpenAI's own model stays. Nothing to do but update.
Run (worktree at
|
||
|
|
ac4a4cf849 |
sessions: opening Sessions waits on no WSL listing it already has (shangyuan0818 on X)
shangyuan0818 (X, third round, after v0.1.4091 and v0.1.4255): on Windows, Usage -> Sessions opened only after a fixed ~20s when sessions were long. The long sessions were not the cause. Goroutine dumps of the reporter's case on the Windows box showed four waits on WSL on the page's first asks: - agent.Looks -> Clients -> All -> wslDistros: a blocking wslRefresh, `wsl -l -q` (10s timeout) once its list is a minute old, then `wsl -l --running -q` (10s) every time. A WSL that answers slowly but answers is never marked hung, so each open after a minute idle waited for both: about 18s, every time. ClientsIn drops WSL's agents anyway, so Clients now reads only this machine's (local()). - gui agentsHere (the web-mode own-sessions gate) called agent.All the same way. It now calls agent.AllKnown: this machine's agents and WSL's as last listed (wslDistrosWithin(0)), never waiting on wsl.exe. - sessions.wslFilesAs waited wslFirstWait (3s) afresh on each read while the first listing was pending, so list, stats and overview each waited 3s in turn. The 3s is now counted once, from when the first listing started. - provider.copilotCLILogin waited copilotWSLWait (2s) on every re-read of a distro's Copilot sign-in, every copilotWSLAge (20s), though it had an answer. A re-read now answers the last read at once; only the first read waits. Timed on Windows 11 (xiaomi-gpu), sandbox HOME with a 90 MB Claude JSONL and a 32 MB Codex rollout, a fake wsl.exe whose -l -q answers "Ubuntu" after 8s and whose --running hangs; /api/sessions list+stats+overview together, opened 20s after start, then 70s apart: |
||
|
|
90d54a2675 |
usage: Factory Droid's own sessions count under Not through magpie (_meouwu on X)
Droid's sessions were on the Sessions page, but Usage's "Not through
magpie" read no Droid calls, so what Droid spent straight at Factory or
a BYOK provider never added up.
Droid writes no tokens into a transcript: a message line has its time,
the message and a reply's modelId. Read from droid 0.231.0's binary
(its session schema) and the real runs in testdata/droid-skills, what a
session spent is only in <id>.settings.json: tokenUsage, its own running
total (input less the cache, output with thinking, cache read and
written), and lastCallTokenUsage, the latest call alone. So each session
is one call of its total, at its last message (the day Sessions already
counts the same total on), under its settings' model; a subagent's is
under the session that called it, a fork's starts at none.
- sessions: calls_droid.go reads a session with its settings whole
(wholeCallReaders "droid"); droidFiles joins callSources, behind
Reads("droid") and allowed() like the rest. WSL is not read: the
Sessions page doesn't list Droid in a distro either.
- No double count: a session whose settings or any reply names magpie's
own entry (custom:magpie/...) or a custom model whose baseUrl is the
gateway's port on loopback is left out whole; the gateway counted those
calls, and a total can't be split by model. A session is judged when
read, again once it or its settings change.
Tests: TestDroidCalls (the 4 real droid 0.231.0 sessions: tokens, time,
model; custom:mh on localhost:11434 counted, on the gateway's port left
out; Reads off counts none), TestDroidCallsOfSessions (subagent, fork,
no settings, magpie's entry, Factory's own model), and
TestDirectDroidSessionTotals in usage. Both sessions tests are red on
origin/main (0 calls); with the gateway check broken by hand both go red
on the gateway cases.
Run (mote): go test ./internal/sessions
./internal/usage ok; go vet + GOOS=linux/windows go vet of both ok;
gofmt clean; go test ./internal/gui ./internal/agent ok.
Not tried: a real Droid session against Factory's own models (no Factory
account here); no GUI change.
|
||
|
|
91b3af8470 |
usage: Qoder's own calls are under Not through magpie, by the credits they cost (eating_dream on X)
Qoder's and Qoder CN's sessions were on the Sessions page and nowhere in
Usage: callSources never listed their files. They are Claude Code's
lines, and are now read for calls as Claude Code's are (ccCallAgent:
claudeCallLine, the call cache, continuations and revisions).
Qoder writes a reply on its own models ("auto" among them) with every
token count 0 unless QODER_EXPOSE_TOKEN_USAGE is set: the transcript
writer (vUl in qodercli, the same in Qoder.app's worker, qoder-agent-sdk)
zeroes them unless the model is a custom one, from qodercli 1.1.0 on. It
keeps the reply's credits. So such a call carries Credits (new on
sessions.Call, passed to the ledger's Record), counted with no tokens
and no price; "auto" names no model, so nothing is priced for it. A
model of the user's own, whose counts are written, is read and priced
as before. The GUI's direct section already shows credits (ledCredits).
Fixture: testdata/qoder-1.1.89 is lines as qodercli 1.1.89's writer
lays them out (key order, zeroed usage, credits/original_credits/
billable, a reply with no usage), read from its npm bundle; the ids are
made up. The older invented qoder fixtures got message ids of their own
(Calls counts a message id once across agents, and they shared
WorkBuddy's m1/m2).
Run (on mica, at f07e3e067's tree, rebased on
|
||
|
|
64c4261582 |
sessions: search what was said in every agent's sessions, from the page and an MCP server
cryingLiu on X asked to search the chat history of every agent magpie
reads sessions from: prompts and replies, from one place.
What the user gets:
- The Sessions page's search also lists, under the agent's own list,
the other agents' sessions whose conversation says the words, each
with a snippet. A hit opens the conversation in the sheet at the
message that said it (transcript?find=), with "N earlier messages
not shown"; the page itself never scrolls. While the index is still
being built the head says "Indexing sessions…" or "Indexing N of M
sessions…", and the page asks again every 3s until it is done.
- Magpie Sessions, a built-in MCP server in Library → MCP (Discover),
opt in per agent like the other magpie servers. Its tools are
search_sessions(query, agent?, limit) and read_session(id, around?),
both returning text. It runs as `magpie mcp sessions` over stdio and
reaches the gateway's /mcp/magpie/sessions, which serves only local
callers that are not browsers.
How it works:
- internal/sessions/said_index.go keeps said-v1.db beside sessions.json:
a contentless SQLite FTS5 index (detail=none) of the words each
session says. It is built from the sessions list sessions already
caches and refreshed at most every 10s: a new or rewritten file is
read once, a grown Claude Code or Codex file only from where it ended,
and a gone one is forgotten. A query asks the index which sessions
have every word, then reads only those files for the snippet, for at
most 6s. A search waits up to 2s for a refresh. While the first
listing is still running the answer says `listing`, so an empty first
answer is not read as "no session says it".
- Privacy: only agents sessions.Reads allows are indexed or searched;
nothing is read until the user has answered the sessions question,
and in gateway mode no agent's own files are read (the page doesn't
ask). Reset forgets the index.
- /api/sessions/said for the page; the CLI parity list names it.
Run, at this tree (rebased on origin/main
|
||
|
|
ff6f6337f1 |
sessions: the kept parses are written binary, not JSON
The Sessions and Usage index (sessions.json, ~18k files on a long
history) was JSON. Every start decoded all of it through reflection,
and every save, which happens at most once a minute while a session is
live, marshalled it whole again. It is now a compact binary form
(cache_binary.go):
- A magic and a version header.
- Then length-prefixed records, varints for the numbers.
- Interned names, as the JSON path interned them.
- The rare nested parts (Claude Code's window, a Codex identity,
StateMore) as JSON blobs.
Records are decoded in parallel.
A JSON index from an older magpie is still read. loadCache saves it
again at once, so it turns binary on the first start even when no
session changed; before, a save came only after a file changed.
A binary file is refused whole, never half read: when it is cut
anywhere, has a byte added, or is of another zone or version. That
means one full read again, as a refused JSON file meant before.
TestCacheBinaryKnowsEveryField fails when state, day or Tokens gains a
field that the binary form doesn't carry.
On the real acctp history, on mote (18,346 files):
- The file is 14.8 MB, down from 23.3 MB.
- Decoding takes 19 ms, down from 69 ms, and allocates 28 MB, down
from 58 MB.
- Encoding takes 10 ms, down from 98 ms, and allocates 3.1 MB, down
from 32.5 MB.
- The heap kept after decoding is the same: 24 MB.
- /api/sessions from a w94 build on the binary index and from a w92
build (before) on the JSON index answer the same bytes (5000
sessions). Neither rewrote the index.
- The page-open footprint peak was 152 to 214 MB on both builds at
load 60 to 80. It is too noisy to claim a change.
Run:
- mica-run go test -count=1 -timeout 45m ./internal/sessions
./internal/usage ./internal/gui: all ok.
- GOOS=linux and GOOS=windows go vet ./internal/sessions
./internal/usage: ok. go vet ./internal/sessions: ok.
- gofmt -l: clean.
- TestCacheBinaryRefusesBadFiles cuts the file at every length, adds a
byte, changes the zone and the version, and flips every byte; it
checks that a bad file is never accepted and never panics.
Broken by hand:
- The decoder skipped Provider: TestCacheBinaryIsJSON went red.
- loadCache stopped re-saving a JSON index:
TestCacheJSONRewrittenOnStart went red, the file still JSON.
At the pushed head (rebased on
|
||
|
|
9bcdcfb7d1 |
provider: Antigravity's Orchestrator ids are priced as the Gemini model each is
guyng35955 on X: an Antigravity local session's calls under gemini-pro-orchestrator-argon, gemini-pro-orchestrator-carbon and the worker gemini-flash-worker-agy showed tokens and cache but cost "—". They are Orchestrator mode's role ids, which no catalog prices. pricedNamesTo now reads them as the model Antigravity's docs name (https://antigravity.google/docs/models/): Orchestrator (Argon) plans with Gemini 4 Argon, Orchestrator (Carbon) with Gemini 4 Carbon, and Gemini 4 Hydrogen does the implementation, so the worker is priced as gemini-4-hydrogen. gemini-pro-orchestrator (Carbon's id before Argon came, per the Antigravity Context Window Monitor extension 1.17.1's table) is Carbon too. Only these four ids, under a route prefix or an effort suffix; a name only like one stays unpriced. Every cost reads through this one place: the Sessions list and overview (sessions.priceOf -> PricedName), the usage ledger, its totals and per-agent view (Pricer -> ListPrice / MakerPrice). Prices are taken as rows are read, so sessions recorded before the update are priced once it is installed; nothing is re-parsed. Google publishes no rate for the role ids themselves; they are priced at the named model's models.dev list price. Run (mote, at this tree): - the three new tests red on origin/main's models.go (every role id unpriced), green with the fix; red again with argon mapped to carbon by hand - go test -tags nogui ./internal/provider ./internal/sessions ./internal/usage: sessions and usage ok; provider ok but for TestRemoveListedAccountLeavesHiddenNamesake (ZCode account removal, not reached by this change), which passes alone -count=3 with and without this change; filed as #6764 with its output - go vet, GOOS=linux and GOOS=windows go vet of those packages; gofmt -l clean Not tried: the reporter's own Antigravity database, or a real Orchestrator mode account (this Mac has no Antigravity app and the account isn't offered Argon). No GUI change. Reported-by: guyng35955 on X |
||
|
|
4f40a1061e |
sessions: a turn of a long Claude session reads none of its copies again (shangyuan0818 on X)
Usage → Sessions took ~20s on Windows for long Claude Code sessions (tens to ~100 MB each, few rows). A session resumed or forked into new files leaves whole copies of it, listed as one row, and the live one is the file they are kept in. Each turn it gained re-read every copy whole, twice: - ccFamily dropped the uuids read of a group whose verdict it found on disk, so the next change judged the group by reading every file's uuids from the start. It now keeps them while the files start alike, as ccUUIDMemo's comment says, and reads on from where it stopped. - ccRest read each copy whole again whenever the keeper changed. It now keeps the uuids of a copy's own messages, and while the copy didn't change and the keeper only grew and holds none of them, the rest stands. A keeper that took one of them has the rest read again (TestClaudeKeeperTurnTheBranchHeldIsCountedOnce, red with that check turned off: 90 in, want 80). Timings, Windows (xiaomi-gpu), a 100 MB Claude session from a real one with its text scrambled, copied under new ids: - in process, 4 copies, /api/sessions after a turn: 261 ms and 332 ms, now 26 ms and 27 ms; after a start and a turn 523 ms, now 239 ms. - the real dev backend (magpie app, sandbox HOME), 8 copies, the page's three calls after a turn: 607 ms, now 31 ms. Cold start 1.9 s both. These scale with the copies and their size; the reporter's machine is slower than this one. Run: - TestClaudeKeeperTurnReadsNoCopy red on the old code (copies and keeper read whole each turn); red with each half undone alone. - win-run go test ./internal/sessions ./internal/gui: 14 reds, the same 14 on origin/main |
||
|
|
75f872ef19 |
sessions: a page gone from view lets the parsed session files go in 30 s, not 3 minutes
v0.1.4150's away timer let the Sessions stats and the Requests chunks go 30 s after the app's page went from view, but a web page open 70 s and closed still held 92-93 MB 45 and 90 s on. A heap taken 45 s after the close (liveHeap 57 MB, 15 MB at +180 s) showed why: opening the page starts the warm-up (warmStart), which parses every session file, and those parses (decodeCache, the listings, Codex identities: ~40 MB live for the acctp history) go only by the sessions package's own cacheIdle, 3 minutes after their last read. forgetAwayPage now also calls sessions.ForgetParses, which is dropIdleCache without the 3-minute wait (dropCache(0)): it still keeps the parses while a save isn't on disk, the last failed, or a file is being parsed, and the next read has them back from sessions.json with no session file read. It runs only when the stats went too, so a range being read keeps them. Test: TestForgetParsesLetsGoAtOnce (red with ForgetParses waiting cacheIdle, broken by hand). Measured on mote (pageclose2.sh, acctp, page open 70 s and closed, footprint-overlay build like the release): v0.1.4150 (w90): close 122 MB, +45 s 93, +90 s 90, +180 s 55, +600 s 52 this (w92): close 125 MB, +45 s 64, +90 s 61, +180 s 56, +600 s 53 A debug build (w91) logged the away timer firing with no read since, so the 90 MB left was this cache, not a skipped let-go. Run: go test ./internal/sessions ./internal/gui ./internal/usage on mote (ok); GOOS=linux go vet -tags nogui and GOOS=windows go vet of the two packages (ok). |
||
|
|
c41fa8e478 |
sessions: an OpenMausBot conversation can be shown (@qingqingdilaiP on X)
@qingqingdilaiP's OpenMausBot rows in Usage → Sessions ( |
||
|
|
b507b5f692 |
sessions: OpenMausBot's conversations are read (@qingqingdilaiP on X)
@qingqingdilaiP asked for OpenMausBot's sessions in Sessions. OpenMausBot (milind-soni/OpenMausBot, npm 0.1.155) is already an agent in magpie, but its conversations were not read. It keeps its data in $OMB_DATA_DIR, else ~/.openmausbot on every system (server/config.ts): - bots.json: bots[].tasks[], one a conversation (threadId, title, "New thread" until named, and cwd once a turn pins it); - messages.db: SQLite in WAL mode (thread_id, at ms, role user|bot, kind text|activity|..., text, json; an activity's json holds tool.name, a bot text its turnId); - usage/<YYYY-MM>.jsonl: one row a turn (driverKind, model, input with cachedInput and cacheWrite included, output). internal/sessions/openmausbot.go lists each conversation as a read-only session, like Alma's and Hermes's rows: prompts, one reply a turn (a turn says a line before a tool and again after it), tools by name, title from bots.json (else the first prompt), folder from task.cwd, times from messages and usage rows. A conversation holding only a bot's greeting is left out. Its rev joins the thread's count, last time, bytes, usage rows, title and cwd, so a write to it, or a new title, reads it again while the database file looks the same. Tokens count only for API drivers (server/agents-bridge-switch.ts's CHAT_RUNTIME_DRIVERS): a bot on Claude Code, Codex, Pi or another agent CLI runs that CLI, which keeps the turn in its own session, so its tokens are counted there and would be counted twice. Fresh input is input less cache reads and writes. bots.json and the usage files are read again only when their size or time change. Dirs() and Reads/access cover messages.db. Delete refuses it: OpenMausBot keeps the database open. Tests (testdata/openmausbot is OpenMausBot 0.1.155's own data folder, written by the real app in a sandbox on mica with an OpenAI-compatible fake model, database checkpointed): - TestOpenMausBotSessions: titles, tokens, times, greeting-only threads left out, the Sessions page (2 rows, not deletable, 4 and 2 messages), Delete refused, stats (1 prompt, 1 reply, agents_list_bots once), Dirs(), the database's bytes unchanged. - TestOpenMausBotCountsCLITurnsOnce: the sample's rows with one turn on claudeAgent and one with cache read and write, cwd pinned. - TestOpenMausBotReadAgainWhenItChanges: a new title alone, then a new row with the file's time held. - skillsCounted: openmausbot says why its skills are not counted (a bot reads a SKILL.md with its file tools, and the sample has no such turn). Broken by hand, each red: CLI rows counted (claude tokens 1202/42), no turnId dedupe (team 3 messages, 2 replies), no rev check and title ignored (new title not read), cache left in fresh input (1203), greeting threads listed (4 rows). Run: gofmt -l clean. On mote (load ~20 on 18 cores, mica busier with a GUI run): go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go test -count=1 -timeout 45m ./... at 59c5b59ea (this and the yaml.v3 commit on |
||
|
|
50d88f17ce |
sessions: the Claude subscription bridge's own runs are not local sessions
iwinux on X: a Pi request through a group a Claude subscription serves was listed twice in the request log, once as "Pi · Claude Code" and once as "Claude Code · Local session", with the same tokens and cost. Cause: a bridge run is the real Claude Code. It saves its session in the account's projects folder, in the caller's folder's project: the user's own ~/.claude or a saved account's claude-accounts folder, both of which appdir.ClaudeHomes lists. listCCFiles read it as a session of the user's, and the ledger's pairing (request id, then session and tokens) didn't match it with the gateway's record, whose session is the caller's. So every call was counted twice: request log, usage ledger, cost totals, the Sessions page. -p runs and interactive (TUI) runs alike, plus a branch's cut copy and a replayed transcript. Fix: every session a bridge run saves is named by the new internal/bridgesid. New is a version 4 UUID whose last six bytes are a keyed SHA-256 of its first ten, the key a random file of this computer's (<config>/claude-bridge-session-key, made once by temp file + link). To Anthropic, which Claude Code sends the session id to, it is as random as any, so it marks nothing upstream. startRun passes --session-id for a new run (-p and interactive; the TUI helper keeps a --session-id it is given and makes a marked one otherwise), replaySession and cutSessionWhere name their files with it. listCCFiles leaves out a .jsonl, and a session's sub-agent folder, whose id bridgesid.Is knows, for agent "claude" only. That one listing feeds calls, the ledger, the request log, Sessions, traces and WSL distros, so all of them drop the double count. Other bridged runs (warm-up, askClaude, /usage, WSL -p) use --no-session-persistence and write no session. Rows already counted twice: a bridge session already removed (a run's session is removed when it ends) is gone from the ledger already, as it is read from the files there are. One still on disk under an old random id (a live or shelved run resumed under it, or a stopped gateway's leftover in a caller's folder) can't be told from the user's and stays counted until it is removed; old ids carry no mark to fix it on read. Tests: TestNewIsKnown, TestKeyKept, TestKeyMadeOnce (bridgesid); TestBridgeSessionsAreNotLocal (sessions: a marked session in the user's folder, its sub-agent file, and one in a saved account's folder give no calls and no rows; the user's session beside them counts); TestClaudeRunSessionsAreTheBridges (-p and interactive, a new run and a replayed transcript) and TestClaudeCutSessionIsTheBridges (gateway). Broken by hand, on mica: bridged() returning false made TestBridgeSessionsAreNotLocal red (calls req_m1..m4, want req_m1 alone); newUUID back in startRun, replaySession and cutSessionWhere made both gateway tests red (print, interactive and the cut copy). Run on mica at this head (rebased on |
||
|
|
667ac8bd6f |
settings: a look at one setting takes the shared settings, not a copy
settings.Load() copies the whole Settings (clone + deepCopy of every map and slice) for each caller. 133 places read one field of it and threw the rest away: the proxy for every outgoing request (netproxy), the GitHub token, the China mirror switch, a model's output cap, wire or price on a gateway request. With a real account in the tray, Load's clone was 26.6 MB of the 318 MB the process allocated in its first seven minutes, most of it through netproxy.For on each request. Each of them now reads settings.Shared(), the read-only settings every caller is given for the same settings.json. Only reads were changed: a scalar field (string, bool, int, float) or a map field's index read. A caller that keeps a whole map or slice, or calls a method on the settings, still takes Load's copy. |
||
|
|
c51b0ca9fa |
sessions: the Antigravity app connected to WSL has its usage read from the distro (@guyng35955 on X)
@guyng35955 on X: on Windows, with the Antigravity app connected to a
WSL Ubuntu, magpie showed no Antigravity usage.
Why. Antigravity 2.x (dist/wsl.js and languageServer.js in its
app.asar) runs a Linux language server in the distro when it is
connected to WSL ($HOME/.antigravity-server/bin/<version>/
language_server, started through wsl.exe with --app_data_dir
antigravity), so the conversations go to the distro's
~/.gemini/antigravity, not %USERPROFILE%\.gemini\antigravity. magpie
read Antigravity's conversations only from this computer's folder:
- sessions.wslAgents had no antigravity (nor agy, whose
~/.gemini/antigravity-cli in a distro wasn't read either);
- internal/agent kept a distro for the Sessions page only when one of
wslKinds or the Copilot CLI's folder was there, so a distro with only
the app's data never reached sessions.WSLHomes;
- and, found on the Windows box: no SQLite database under
\\wsl.localhost opens in place. Every form (file: URI, plain path,
mode=ro, provider.OpenReadOnly) answers SQLITE_BUSY after its 3s
busy_timeout, since the share doesn't take the locks a WAL database
needs. So listing the files alone would have shown nothing still.
What changed.
- agent: wslKept keeps a distro with ~/.gemini/antigravity(-insiders),
and the probe looks for them (no agent row for them).
- sessions: wslAgents reads the app's conversations (insiders under
their own key) and agy's in a distro; their summary rows name the
distro's folders as Linux does (agyFolder with goos "linux", so
/home/me/site, not a Windows path). The distro's calls count in
Calls (wslFiles("antigravity"), wslCallFiles("agy")). The listing
kept on disk (sessions-wsl.json) carries each file's row, rev and
read-only, so a stopped distro keeps its titles and folders. A
distro's ~/.gemini that is this computer's own (a link) is read once,
as this computer's (sameDir).
- sessions: openAppStore opens agy's and the app's databases read only
in place, or, under \\wsl.localhost or \\wsl$, as OpenUntouched does
(immutable with no -wal, else from a copy of the db and its -wal).
- docs/subsystems/agent-wiring.md says which distros are kept for reads
only.
Not changed: session-read consent ("allow selected" names agents found
on this computer) doesn't look in WSL, as before for every WSL agent.
OpenCode's and ZCode's SQLite readers aren't used for a distro (not in
wslAgents), so they keep provider.OpenReadOnly.
Run (at the tree rebased on dc85a7ca5; then rebased on
|
||
|
|
71a806749d |
sessions: a paginated Codex rollout moves to a longer provider id by its row (@xMopf7RF on X)
@xMopf7RF on X (tweet 2121441393424113800): the Sessions page's Move refused an old Codex session with "rollout-2026-03-09T09-25-….jsonl.zst keeps its history by byte, and "magpie" is longer than the provider it names: Codex couldn't open it moved", and offered nothing else. Since |
||
|
|
ab4b1cf38f |
sessions: a long Codex rollout is read on after a restart, not read again whole
shangyuan0818 on X: on Windows, Usage > Sessions took over ten seconds to open with one very long session (tens to 100 MB), though there were only a few sessions. Cause: a Codex rollout's summary window (state.Codex) and its calls' window (cxRun) lived in memory only. After a restart, or once the window had been dropped, the first line a live rollout gained made parseRead, prepareCalls and readsWhole read the rollout again from its first line: once for the summary and once for the calls. Claude Code sessions were already read on through their kept windows (#3493). Fix: the window of a rollout being written (changed within the hour, the same files memory keeps windows for) is now kept on disk with the parser version, a window version, and the size, offset and content hash of the read that made it. The summary's goes in codex-windows/<hash>.gob next to sessions.json. It is written with sessions.json, and it is removed once the cache drops that window. The calls' window goes in the shard's .rev file next to Claude's. Each is used only when all of those match, so a window from another read, or from an older layout, is never used; the file is read whole instead, as before. Measured (100 MB rollout built from testdata/codex-native-paginated.jsonl, plus a 100 MB Claude Code session, GET /api/sessions in a sandbox HOME): mote (M5), before: after one line appended following a restart, 2.51 s (Codex alone 2.25 s). After: 9.7 ms (Codex alone 6.3 ms). Windows (xiaomi-gpu), before: 2.61 s. After: 22.8 ms. The first read with nothing kept is unchanged: 2.6 s on mote, 2.8 s on Windows. Warm and plain-restart opens were already 10 to 30 ms. stats and overview stayed at a few ms throughout. A real 32 MB rollout: 24 ms after an append, with 2 KB and 4 KB windows. A 100 MB rollout with a unique response id per turn: 11 ms, with 623 KB and 834 KB windows. Tests: TestCodexSessionReadOnAfterRestart reads a rollout, restarts, then appends a replayed token_count and a new turn. It checks that neither reader starts at offset 0, and that calls and the session's tokens, models and cost match a read from scratch. TestCodexWindowLeavesWithItsSession covers writing, reading back, refusing another read's window and removal. TestPlainRolloutReadOnceForSessionsAndCalls (#4369) expected both readers to start from 0 after a restart; it now expects them to read on. Broken by hand, each red: the summary window not read (starts [319830 0]); the calls window not read ([0 319830]); a summary window emptied of what it had seen (it panicked in codexUsageState.count, which is why the version guard was added); a calls window emptied (62 calls vs 61). Run: gofmt -l clean. GOOS=linux and GOOS=windows go vet -tags nogui ./... on mote. Full go test -tags nogui -timeout 45m ./... on Linux (wsl-run, magpie-desktop) at this change on |
||
|
|
f798b4eb7a |
sessions: keeping a file's calls trims the revision windows only when it holds one
keepCalls and keepCallContinuation trimmed every kept window after each keep, under callsMu: a sort of the candidates and a map, twice a file. A request-index build reads ~11.5k session files through four workers, and the files it reads are disk shards that hold no window (weight 0), so each trim changed nothing while the workers queued on callsMu for it. A block and mutex profile of a real-account rebuild showed ~55k contentions on callsMu (about 5 a file), ~3.5 s of lock handoffs and ~4.3 s in pthread_cond_signal. Now keepCalls trims only after keeping a file with a window, and keepCallContinuation only after it adds an entry (its early returns add none). Every window added is still trimmed at once, so the budgets hold as before; a window aging out waits for the next keep that adds one. Run: go test ./internal/sessions ./internal/usage ./internal/gui (ok, on mica), go vet, GOOS=linux and GOOS=windows go vet ./internal/sessions, gofmt -l. Real account on mote (75G sandbox HOME, network blocked): a request-index rebuild forced by a new Anthropic price each run, CPU of the process 30 s after start, alternating: v0.1.4052 21.25 / 17.68 / 15.95 s, this change 14.81 / 14.14 / 13.43 s (mean 18.3 -> 14.1 s). Not tried: a test that counts trims; the change is a cost, and every kept window is still trimmed by the same code. |
||
|
|
f5553d7103 |
sessions: a Pi subagent's calls are its lead session's, on its own model (nzvzbmz78932 on X)
nzvzbmz78932 on X: "在pi子代理中使用了deepseek 但是不显示用量". pi-subagents (npm 0.88.1) runs each subagent as a Pi of its own, its session in <lead file's folder>/<run id>/run-<n>/session.jsonl (async and parallel runs a level deeper), or under extensions/subagent/config.json's defaultSessionDir, its header's parentSession naming the lead's file. magpie read only sessions/*/*.jsonl, so those files were never read. The lead's `subagent` tool result carries the subagents' usage summed, and piParse counted it on the lead's model and provider: a lead on magpie's entry made it the gateway's (piGateway), so DeepSeek's calls were on no page, Usage or Sessions. - piFilesIn reads every session file under a lead's folder as the lead's (non-main, like omp's), and the defaultSessionDir ones through their headers' parentSession, up to 8 levels. - piSubagentsRead: a tool result whose every sessionFile is one of those counts nothing, in piParse and piCall; one naming a file not read still counts as before. - The scout's header id is in Session.Subs (pi is idInFile), so a subagent on magpie's entry is the lead's row to the gateway too. - state.codexPath is parsePath, the file read, for piLeadID: a new field took state past its 416-byte class (TestStateFitsItsSizeClass). - parseVersions and callParseVersions pi/raft/cindy raised. The fixture is a real run: Pi 1.4.0 with pi-subagents 0.88.1 in a sandbox PI_CODING_AGENT_DIR, a lead and one scout on a relay's deepseek/deepseek-flash; system prompts dropped, paths rewritten. Run (mica, at this head): - go test ./internal/sessions: ok (119s) - GOOS=linux and GOOS=windows go vet ./internal/sessions: ok; gofmt clean. - Linux (wsl-run, magpie-desktop): TestPi*, TestOmp*, TestCodex*, TestStateFits*: ok TestPiSubagentCalls: beside the lead and in defaultSessionDir, each with the lead on the relay and on magpie's entry (the reporter's case). Broken by hand: without the walk, 3 of 5 calls and 0 of 2 with the lead on magpie (red); without the tool-result skip, 6 calls, the sum counted again (red); the Subs check was red while it named the run id. Not tried: the reporter's own files; a subagent nesting subagents; a subagent run on magpie's entry against a live gateway. With f0fb22c6b and 5bc816c1a below it, at this head (mica): go test ./internal/sessions ./internal/agent ./internal/claudecode ok, ./internal/gateway -run TestClaude ok, GOOS=linux and windows go vet of the four ok, gofmt clean. |
||
|
|
18b46f5c25 |
sessions: the Kimi desktop app's Work calls reach Usage
CNSA0422 on X: magpie didn't count local usage from the Kimi desktop
app. Its Work agent is Daimon, which runs the Kimi Code runtime it
vendors with its own home under the app's share folder, so its calls
are written as Kimi Code's usage.record lines in a folder magpie never
looked in.
Read from Kimi 3.2.27's own bundle (com.moonshot.kimichat, Daimon
1.0.10, Kimi Code runtime 0.5.1): the app passes KIMI_SHARE_DIR, which
is <userData>/daimon-share or the absolute shareDir in
<userData>/daimon-storage.json; Daimon alone falls back to ~/.kimi.
The sessions are <share>/daimon/runtime/kimi-code/home/sessions/<slug>/
<id>/agents/<agent>/wire.jsonl. userData is kimi-desktop under
~/Library/Application Support, %APPDATA% or ~/.config.
- kimi_work.go finds the shares and adds their wire files to Kimi
Code's ("kimi"), as MiniMax Code Desktop's count as MiniMax Code's.
Found() lists kimi when only Work sessions exist.
- A record's model is Daimon's alias (daimon-kimi-code). It is read
as the alias's model in the runtime's config.toml (k2p6-agent).
- magpie's kimi-desktop plugin points the alias's provider at a bridge
on 127.0.0.1 that forwards to the gateway, which logs those calls.
A call whose alias's base_url is a loopback address is skipped, so
it is not counted twice. config.toml is the current setting only,
so history read for the first time is judged by it.
- docs/subsystems/gateway-sessions.md says so.
Run (mote): go test ./internal/sessions -count=1, ok;
go vet ./internal/sessions for darwin, windows, linux -tags nogui, ok.
Windows (xiaomi-gpu, win-run): go test ./internal/sessions
-run 'KimiWork|Loopback|KimiCode', ok. gofmt clean.
Broken by hand: kimiCallFiles without the Work files made
TestKimiWorkCalls red (no calls), and so did dropping the loopback skip
(the bridged call counted). Restored, green.
Not tried: a real Kimi Work session. This computer has no Kimi desktop
data, so the fixture's records are the Kimi Code format the bundle's
UsageRecord writes and its config.toml is what modelToToml builds. The
Windows installer was not unpacked: the Windows path is Electron's
userData as the bundle's code reads it. k2p6-agent has no price in the
catalog, so these calls show tokens and no cost.
|
||
|
|
11ab58c587 |
sessions: a kept folder listing is one array (#2278)
readDirectory keeps each folder's listing to tell an unchanged folder from a changed one. os.ReadDir's entries are a pointer each to a separate unixDirent plus its name, so a Codex sessions tree of 10k files held 20k small objects for as long as magpie ran. The kept listing is now one []keptEntry (dir, name, type) with pointers into it: one object per entry, and Info() still lstats on demand as os.ReadDir's does. Windows keeps os.ReadDir's entries (their Info is already filled and cheap). Measured on mote, 10k-file folder, HeapAlloc/HeapObjects kept across readDirectory, 3 runs each: before: 1,297,928 B, 19,996 objects (129.8 B/entry) after: 1,042,664 B, 9,994 objects (104.3 B/entry) -20% bytes and half the objects the GC scans each cycle. Run: go test ./internal/sessions on mote (TestKeptListingIsCompact checks entries equal os.ReadDir's in Name/IsDir/Type/Info, are contiguous, and an unchanged folder is not listed again). Not tried: Windows (path unchanged there). |
||
|
|
6bcdc6468d |
sessions: agy's own calls name the model its conversation database names (DvnT662 on X)
Usage → Requests showed every call read from a local agy-cli session with no model (v0.1.3996). The calls reader read only agy's transcript, brain/<id>/.system_generated/logs/transcript_full.jsonl, which carries tokens but no model. agy keeps the model in conversations/<id>.db, the Antigravity app's layout: gen_metadata field 1.19 is the served model, and a step's metadata field 20.3 names its generator (0 when left out, as antigravityRead reads it). A generator's "last_step_index" n in 1.20 names step n+1 for steps the steps table doesn't hold. - calls_agy.go: agyStepModels reads the db read-only and gives each transcript step its model (through agAppModel, so -n deployment suffixes go as on the app's rows). The call file's stat folds in the db and its -wal, so a model written after the step is read again. - agy.go: the Sessions page counts each step's tokens under that model (still "agy" when the db names none), and its rev folds in the db too. - parseVersions / callParseVersions "agy": 1, so cached parses are redone. Fixture: gen 0 is parkavenue9639's real agy 1.5.6 gen_metadata row from #3147 (matching its transcript step 1, 11519 in / 781 out); steps.tsv is the real steps.metadata agy 1.5.7 wrote on this Mac. Generator 1 is made in the test. Run (mote): go test -count=1 ./internal/sessions ./internal/usage ok; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok; gofmt -l clean. Broken by hand, each red: calls given no model; no last_step_index fallback; Sessions not moving counted tokens to the model; call files ignoring the db's stat; Sessions rev ignoring the db. Not tried: a live successful agy turn (this Mac's only agy account is refused, so its db has no answered step); agy in WSL; conversations with a db and no transcript still count nothing (#5432); tok/s and stripping -trial (#4805). Refs #3147, #4805, #5432 |
||
|
|
e630c003cd |
usage: Devin CLI's own calls are read from its sessions (aohan0905 on X)
Usage counted none of Devin CLI's requests. Devin's CLI (3000.11.234, run for real in a sandbox HOME) keeps its sessions in <data>/devin/cli: sessions.db (SQLite: sessions, and message_nodes with each chat_message), or with DEVIN_SESSION_STORE=files a folder per session (log.jsonl + meta.json), whose first run copies the database's sessions in and leaves the database. Each assistant message names its call: request_id, generation_model (swe-2-high, effort and all), created_at and metrics (input/output/cache read/cache write tokens, ttft_ms, total_time_ms), written as two nodes per reply. - sessions: calls_devin.go lists both stores (a session in both once, from the store written last), reads each session whole, one call per request_id (Msg devin:<id>), with the cwd. Registered in callSources and wholeCallReaders; Found lists "devin" for the consent page. - provider: DevinModelEffort splits a variant id into model and effort (claude-haiku-5-5-low -> claude-haiku-5-5, low), so the catalog prices it. swe-2 has no catalog price and shows as unpriced. - agentenv clears DEVIN_SESSIONS_DIR in test sandboxes. Fixtures are the real runs' files: 3 sessions in sessions.sql (schema verbatim, triggers dropped, assistant and user rows only), one session only in the folder store and one in both, project folder renamed. Run (mica): go test ./internal/sessions ./internal/provider ./internal/agentenv ./internal/usage ./internal/usageapi ./internal/cli ./internal/gui ok; go vet darwin, linux -tags nogui, windows on the touched packages ok; gofmt clean. win-run: the Devin tests ok. A built binary's `magpie usage all` / `--csv all` in a sandbox HOME holding the real Devin data: 5 calls under Devin, the two claude-haiku-5-5 calls priced from the catalog ($0.000277, $0.000986), swe-2 unpriced. Broken by hand: devinCallFiles out of callSources (TestDevinCalls and TestDevinDBReadAgain red, 0 calls); a session in both stores listed twice (TestDevinSessionListedOnce red, 9 calls); the per-request dedupe off (red, a request counted twice); DevinModelEffort returning the id whole (TestDevinCalls and TestDevinModelEffort red). Not tried: Devin's folder on Windows (taken as %APPDATA%\devin\cli, as its credentials.toml; not seen on a real Windows install); a long real session or subagents; DEVIN_SESSIONS_DIR set (read from the CLI's behaviour in the sandbox, not from a GUI-started magpie's environment). |
||
|
|
e979553ba1 |
sessions: a start doesn't read Claude Code forks' uuids again to judge them (#2278)
Each start judged every group of Claude Code files that start alike
(ccFamily), then read what each copy or branch holds that its keeper
doesn't (ccRest). Both read every file's message uuids through
scanThin, and what they found was kept in memory only: ~0.2-0.25 s of
CPU on each start for a real history with forks, and a uuid set held
for each file.
What a group came to depends only on its files, so it is kept in
cc-families.json next to sessions.json, by a hash of each member's key,
path, size, change time, first and last message and start; a group none
of whose files changed is not read. A copy's or branch's rest is kept
in cc-rest.json by both files' path, size and change time, encoded the
way the parses are (encodeCache), so another time zone, cache version
or parser version reads it again. Both are written behind mu through a
temp file renamed over the last, in order; Saved and Reset wait for
them. Groups unused for 30 days are dropped.
Run (mote, at this tree):
- go test ./internal/sessions ./internal/usage ./internal/gui: ok
(128 s, 64 s, 151 s); GOOS=windows and linux go vet
./internal/sessions: ok; gofmt clean.
- New TestClaudeFamilyKeptAcrossStarts: a start after one that judged
the group reads no file's uuids, and a copy that went on with a turn
is judged again (a branch). TestClaudeBranchRestKeptAcrossStarts: two
starts count the same 80 tokens in and read no uuids.
- Broken by hand: ccFamilyKept always nil -> the first test red ("read
the uuids of 3 files"); ccRestLoad never reading -> the second red
("start 0 read the uuids of 1 files"). Dropping size and mod from the
group's hash left the first test green: the changed copy's last
message changes the hash anyway; size and mod are there for a file
rewritten in the middle.
- Real accounts (acctp sandbox, pprof of the first 40 s of a start with
the page open): sessions.Warm 0.78/0.79 s -> 0.52/0.57 s, statsKept
0.39/0.43 -> 0.18/0.21 s, ccFamily/ccUUIDsOf gone from the profile;
pageheap: CPU at mark 2.84 -> 2.65 s, Footprint 132 -> 127 MB,
liveHeap 80.2 -> 78.4 MB. The first start of the new build reads and
writes them once (2.70 s at 40 s, as before).
Not tried: Windows and Linux real starts; the files are plain JSON in
the cache folder.
|
||
|
|
c14fa0ce93 |
Bring back 919780414 and 88d2962e0, which 698ed4adb undid
|
||
|
|
db0c1b039d |
sessions: a ZCode session the CLI database lacks is named from the app's task index (Flandern1211 on X)
Titles named a ZCode session only from files in the CLI database
(~/.zcode/cli/db/db.sqlite). A session the app keeps only in its own
tasks-index.sqlite (a request names it without the sess_ prefix) had no file,
so the Context page showed the id's first eight characters. Titles now asks
the task index for each ZCode key still unnamed, by sess_<bare id>, skipping
default titles.
|
||
|
|
698ed4adb5 |
gateway: a busy port names the program holding it, and Tailscale's serve gets its fix (pluoki on X)
The Gateway page, `magpie serve` and the app log said only "port N is held by another program". pluoki's was `tailscale serve` on the same port number. proc.PortHolder reads the holder (lsof on the Mac, /proc on Linux, Get-NetTCPConnection on Windows). Tailscale's daemon is root's and often unreadable, so `tailscale serve status --json` is the fallback for the port. gateway.NoteHeld / PortHeld.Sentence say who holds it, and for Tailscale give `tailscale serve --https=<other> http://127.0.0.1:<port>`. Shown in the `magpie serve` standby line and bind error, the app log, `gatewayHeld` in /api/state (Gateway page) and Start's "taken" answer, in en, zh, zh-TW, ja, de. A holder that can't be read says nothing; the old wording stands. Nothing is killed or touched. Run: gofmt clean; go vet darwin, linux nogui, windows (mica); go test ./internal/proc ok; targeted holder/gateway tests on macOS (mica), Windows (win-run) and Linux (wsl-run); parser tests with real lsof output; GUI gateway-port-holder, gateway-takeover, gateway-older, gateway-skew, gateway-port, i18n-keys, i18n-en-no-cjk in chromium and webkit. Real run on WSL: a holder named tailscaled on the LAN address with magpie on 0.0.0.0 gives the Tailscale sentence at the bind error; a Python holder on loopback gives "held by python3.12 (pid N)". Broken by hand: each fix reverted in turn, its test went red. gateway-card.test.cjs is red on origin/main too (#6029). internal/gateway, gui and cli package runs were still going at push; the full suite follows the tag. Not tried: a real `tailscale serve` (changes live config), a real Windows holder end to end, the bind-error path on macOS (a wildcard bind coexists with a specific one there). |
||
|
|
88d2962e0c |
sessions: a file's head and prefix hashes are kept as 16 bytes, not hex (#2278)
Each kept file's state held its head hash as 64 hex characters and its
sampled prefix hash as "sample-v1:" and 64 more, two allocations of 64
and 80 bytes beside the state. They are only compared, so they are now
a digest: the first 16 bytes of the same SHA-256, inline in the state's
own 16 bytes where each string header was. The state's size class is
unchanged (416), and the 144 bytes a file are gone.
A cache written before reads as the same files: digest reads the old
hex (with or without "sample-v1:") as its first 32 characters, which
are what headDigest and prefixHash give now, so the first start after
the update reads nothing again. The call shards' gob keeps its string
fields, written and read through the digest, so a shard written before
restores the same too. File names still use hashHead's full hex.
Run, on a sandbox HOME holding the owner's real account history (18,346
session files), the same sessions.json before each run, web mode, at
120 s:
- w14 (main): live heap 88.8 MB, footprint 129 MB, 127 MB after GC,
CPU 2.35 s
- w15 (this): live heap 86.1 MB, footprint 124 MB, 121 MB after GC,
CPU 2.48 s; at 30 s 2.31 s of CPU against 2.15 s, so no file was read
again from the old cache
Broken by hand: digest no longer stripping "sample-v1:" turns
TestDigestReadsTheHashesWrittenBefore and
TestPrefixHashUnchangedAndUnbuffered red.
At the pushed head (rebased on
|
||
|
|
67d2df72d9 |
sessions: a range's stats are aliased once, as made, and kept aliased (#2278)
With any model alias set, every Stats read copied each kept range's
days and every session's summary into a second, aliased Stats, and kept
that copy (aliasedKept) beside the unaliased one. With a long history
(~14k sessions) the copy held ~5 MB of summaries for as long as the
kept ranges lived.
Now statsKept aliases a range's Stats in place right after
statsOfRange made it (aliasOwned: only st's own Days and Sessions
arrays are written; the usage, model and effort slices are replaced,
never written into) and keeps that one. keptStats carries the alias
names it was made under, so a changed alias makes the ranges again,
as a changed price or title already did. aliasedKept, aliasKept and
aliasStats are gone.
Tests: TestSessionsCountAliasedModelsAsOne now checks that the kept
range's summaries are the very ones the read returned. Broken by hand
(a copy of Sessions before keeping): it went red ("an aliased read
keeps a copy of its summaries beside the kept ones"), and so did
alias_kept_test's "range 0 named again with nothing changed".
TestAliasOwnedLeavesSharedSlicesAlone replaces
TestAliasStatsLeavesItsInputAlone.
Run at 846cc2b9b (rebased on
|
||
|
|
040debfb1e |
sessions: the kept parses' file is mapped, not read onto the heap (#2278)
A start read sessions.json whole onto the heap (24.6 MB on a real
history) and decoded it; then each `named` object was copied again by
gjson.ParseBytes before being read. Nothing decoded keeps a byte of
the file: json.Unmarshal, ccStr and unique.Make all copy, and the keys
are cloned.
On unix the file is now mapped read-only and unmapped once decoded (it
is only replaced by a rename, never written in place); elsewhere it is
read as before. `named` parses its bytes in place.
Run:
- go test ./internal/sessions (mica): ok 63s.
- GOOS=darwin/linux/windows go vet ./internal/sessions: ok.
- Broken by hand: read onto the heap again, TestCacheFileReadWithoutACopy
is red ("allocates 688976 bytes; want it mapped"); a key left
pointing into the file (no Clone) faults it with SIGSEGV after the
unmap. The fixture has plain and escaped names, since an escaped one
is unescaped into a copy anyway.
- Every custom UnmarshalJSON in internal/sessions read for bytes it
keeps: none.
- Real account, mote sandbox HOME, start to 50s (pprof alloc_space):
sessions.loadCache 29.5 MB -> 4.4 MB, os.readFileContents 46.7 MB ->
22.0 MB. Footprint peak unchanged (163 to 164 MB); it is set later.
Not tried: a real Linux start; Windows reads the file as before.
|
||
|
|
152734cd12 |
dirent: one probe vouches for every folder a poll watches (#2278)
A Sessions poll watched each Codex day folder and each Claude Code
project folder through dirent.Watch, and every call ran its own sync1
probe (a mkdir, an unlink and a wait for the write to be heard). On a
real history that was ~130ms of 1.47s CPU per 40 polls, and the
syscalls around it more. WatchSince(dir, mark) skips the probe when a
probe begun after mark was heard; sessions takes the mark when a hold
begins, so one poll makes one probe. A folder watched for the first
time still probes, since its watch hears only what comes after.
Run, real account (mote, the owner's Claude Code and Codex history,
40 back-to-back /api/sessions polls, sandbox HOME):
- CPU: w10 1.47s -> w11 0.54s; under sync1: 130ms -> 10ms.
- Allocated: 25.98 MB -> 25.08 MB.
Tests (mica): go test ./internal/dirent ./internal/sessions ok at the
pushed head. TestWatchesFromOneMarkProbeOnce is red with covered
forced false ("round 0: 3 probes from one mark") and green on this.
./internal/gui: TestPanelHiddenByWailsMarksPageOutOfSight fails under
-count=3 on an origin/main copy (
|
||
|
|
390341f9ed |
appdir: the homes look tells folders apart by inode, not EvalSymlinks (#2278)
ClaudeHomesIn and CodexHomesIn run on every Sessions poll, and keyed each folder they found by filepath.EvalSymlinks, which Lstats every part of the name: ~3 MB of garbage per 40 polls on a real home. On unix a folder is now keyed by its device and inode, which a link to it shares; a folder that can't be looked at is keyed by its name, and other systems keep EvalSymlinks. The folder checks use DirStat, moved here from internal/sessions so both share one. Run (mica, at this tree): go vet for darwin and windows of appdir, sessions, provider and gui, for linux of the first three (gui needs cgo there); GOOS=freebsd go build; go test ./internal/appdir ./internal/sessions ./internal/provider ok. TestHomesLookAllocatesLittle: 55 and 68 allocations a look now, 387 and 400 on the old code, which fails it. Real account (mote, 40 polls of /api/sessions): w9 31.28 MB allocated with os.lstatNolog 3 MB; w10 25.98 MB, lstat gone from the top list. CPU over 30s 1.47s, within noise of w8's 1.29s at mote's load. |
||
|
|
f8248ccd70 |
sessions: an unchanged folder's look allocates nothing (#2278)
readDirectory looked at each folder with os.Stat on every Sessions poll
to see whether its cached listing still held. os.Stat builds a FileInfo
and a name each time, ~6 MB per 40 polls on a real history. dirStat reads
the same mod time, size and kind with unix.Stat into a stack Stat_t;
other systems keep os.Stat.
Run (mica, at this tree): go vet ./internal/sessions for darwin, linux,
windows; GOOS=freebsd go build ./internal/sessions; go test ./internal/sessions
ok (61.8s). TestDirStatAsOSStat passes; with the old discovery.go it fails
("an unchanged folder's look allocated 2 times").
Real account (mote, 40 polls of /api/sessions): w8 34.16 MB allocated,
os.statNolog 6 MB; w9 31.28 MB, os.statNolog not in the top list.
|
||
|
|
10c3315312 |
sessions: an unchanged listing is the last one, not a new list (#2278)
Every 15 s Sessions poll built every Claude Code file's and Codex
rollout's list again, and merged and filtered them into more new
lists, while nothing on disk had changed. On the owner's real history
that was ~120 MB of garbage per 40 polls in listedRollouts,
claudeFiles, listCCFiles and filesKept.
Each lister now keeps its last list (listsKept). A listing walks the
folders as before and compares each file with the kept list's file at
the same place; while they match nothing is allocated, and the kept
list itself is returned. On the first difference it copies the matched
part and goes on, so a grown, new or gone file is listed as a fresh
listing has it, and the kept list is never written. listCCFiles reuses
its walk's scratch slice per lister. distinctPaths and
distinctCodexFiles return their input when nothing is dropped and never
filter in place; codexFilesIn's twin filter clones before deleting.
rolloutsSeen's day entry is its part of the kept list (clipped), not a
clone. The idle cache drop forgets all of it.
Measured on mote with the owner's real account (75 GB history),
40 /api/sessions polls, `magpie heap` before and after, alloc_space
diff:
before (w6): 155.7 MB; listedRollouts 42.8, claudeFiles 32.2 (71.1
cum), listCCFiles 31.0, filesKept.distinct 18.0
after (w7): 34.8 MB; none of the listers in the top; distinct 4.5,
provider.All 9.7 (next)
CPU over 30 s of polling: 1.79 s -> 1.37 s.
Tests: lists_kept_test.go, red on the old code (an unchanged listing
made a list of its own; distinctPaths wrote its input), green now.
TestClaudeFilesMadeAtTheirSize expects the clipped kept list.
Run on mica at this tree (rebased on
|
||
|
|
facc092d00 |
sessions: a ZCode name poll stamps a copy, not the kept file list
v0.1.3800 (729be88e1) has allFilesForTitles give back the list it keeps
from poll to poll, and other polls read it meanwhile. Titles then
wrote each asked ZCode session's message count and time into that list
in place (zcodeTitleStamps): a data race with any poll reading it, and
the kept list no longer matched the rows, so it was made again on the
next pass. The stamps now go in a copy made at the first one that
changes a file; a poll with nothing to stamp copies nothing.
Audited the other users of allFiles/allFilesForTitles and the
in-place writes in internal/sessions (&files[i], .w(), sort.Slice):
the rest write into lists of their own (byKey copies, traceLineFiles
concatenates, callSources goes through distinctOf).
Run (mica): go test -count=1 -timeout 45m ./internal/sessions/ ok;
go test -race -count=3 -run 'TestZCode|TestFilesKept|Titles' ok; vet
ok; gofmt clean. Broken by hand: stamping in place again makes
TestZCodeTitleStampsLeaveKeptListAlone red ("the kept list was
stamped in place: size 1, mod 1790496500000").
Not run: the full ./... and GUI suites (one package touched).
|
||
|
|
0b4b249e54 |
sessions: an unchanged Sessions poll keeps the last file list
Every 15 s poll made the whole deduped file list again (~1.5 MB on a
real history, distinctOf's 58 MB over 40 polls). allFiles and
allFilesForTitles now compare each pass with the last list, held
weakly so a magpie with the page shut keeps none of it, and give the
same array back while nothing differs. A changed or gone file makes a
new list; the old one is never written into (cap == len). An empty
pass is an empty slice, never nil: refresh reads nil as "not listed"
and kept the parses of deleted files (TestGoneAgentLeavesNoSession
went red on the first try, caught before commit).
Run (mica): go test -count=1 -timeout 45m ./internal/sessions/
./internal/dirent/ ok; go vet of both ok; gofmt clean.
Broken by hand: the nil return makes TestFilesKeptWhileTheSame ("an
empty pass: nil") and TestGoneAgentLeavesNoSession ("5 parses kept")
red; a fresh slice on every pass makes TestFilesKeptWhileTheSame red.
Real account on mote, 40 unchanged /api/sessions polls, alloc_space:
179.5 MB (v0.1.3794 build) -> 147.9 MB; distinctOf gone, the kept
list's own compare 12 MB. /api/sessions body sha identical on both.
Not run: the full ./... suite (mote over its cores; this touches the
sessions package only) and the GUI suite.
|