ac4af582301a4e8a29245dbba767eba31334ddf9
42
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
8d80f6bc0a |
sessions: the kept stats and listing hold an untitled id once, not a map entry
keptStats and keptList noted every answer Codex's titles gave in a map[id]string, to ask each again before the kept ranges are given out. Nearly every id has no title, and the map held 3.12MB on an 18k-file history. titleAnswers keeps the named ones in a map and the untitled ids in a slice, sorted, without repeats or slack once settled; still() asks each again as before. Both caches use it. Run (mote, real-account copy, idle 180s, network blocked): - statsKept.keptTitle.func4 3.12MB -> under the profile's cut; total inuse 107.40MB -> 104.23MB. - TestStatsKeptBetweenPolls now also names a Codex thread after the ranges were kept and checks the title reaches them. TestTitleAnswersSettled checks repeats and slack go. - Broken by hand (still() skipping untitled ids, settle not compacting): TestListKeptBetweenPolls, TestStatsKeptBetweenPolls and TestTitleAnswersSettled red; green on this code. - go test ./internal/sessions/ ok; go vet darwin, linux, windows ok; gofmt clean. Not tried: the full suite (only internal/sessions reads these caches). |
||
|
|
cd0ba05c21 |
sessions: each day's usage and active rows are made to size
statsOfRange grew every day's Usage and Active rows by append, and the
overview keeps three ranges (7, 30, every day), each holding the slack
of every doubling. The rows are now counted per date first and made at
their length.
Run (mote, real-account copy, idle 180s, network blocked):
- statsOfRange's own inuse 9.90MB -> 8.37MB (-1.54MB in the diff
against the v0.1.3411 build's profile).
- TestStatsDayRowsHoldNoSlack: green; red on the old code by hand
("usage 5 of 8, active 5 of 8").
- go test ./internal/sessions/ ok; go vet darwin, linux, windows ok;
gofmt clean.
Not tried: the full suite (one package changed, nothing outside it reads
the rows' capacity).
|
||
|
|
36ddd57619 |
sessions: the overview's active hours keep only the hours with time
Each range statsFor keeps holds an Active for every day, agent and folder, and each had a 24-int64 Hours (192 bytes), mostly zeros: 4.5 MB of statsOfRange's 13.5 MB in the idle heap on the owner's real cache (18,331 files). Active.Hours is now the same sparse hours a day keeps (hour<<58|seconds), and the act sums in statsOfRange use it too. Its JSON is the 24 numbers of seconds it was, which the Usage page's heatmap reads (a.hours.forEach). Run on mote at this head: - go test ./internal/sessions: ok - GOOS=darwin/linux/windows go vet ./internal/sessions: ok; gofmt clean - TestStatsHoursAndSessions now reads the hours through JSON, as the page does. Broken by hand (ms not turned into seconds): red, "the 20th by hour: [... 180000]". - Real-account copy (~/r2278/acct), idle heap at 180s: inuse 110.65 MB (v0.1.3402's tree) -> 100.21 MB at this head (sampled; 4.5 MB of it was the hours' own lists). |
||
|
|
f8186c6915 |
sessions: a day keeps only the hours it has time in
A day's hours were a [24]int64 (192 bytes) whether or not it had any. The owner's real cache has 18,331 files and 19,191 days; 13,406 days had hours, but only 19,107 hours across them had any time, so ~2.6 MB of zeros sat in the idle heap for good. hours is now a sorted []uint64 of hour<<58|ms, one entry per hour with time. Its JSON is still the 24-number array, so sessions.json reads and writes as before; an all-zero array read back keeps one zero entry so the day still counts as having hours. Run on mote at this head: - go test ./internal/sessions: ok - GOOS=darwin/linux/windows go vet ./internal/sessions: ok - gofmt -l: clean - Broken by hand: without hours.MarshalJSON, TestHoursKeepTheCacheShape is red (the packed entries went out as raw numbers). - Real-account copy (~/r2278/acct): idle heap at 180s, t1 (v0.1.3398's tree) vs this: inuse 112.94 MB -> 110.65 MB (-2.3 MB; the 2.6 MB estimate less sampling noise). |
||
|
|
5ebceee2da |
usage: the tool legend keeps each spelling's own kind (#2969)
Follow-up to ggbdpq's b2a8b74c7 (the tool list grouped case-blind).
That change put every spelling's calls in the legend under the kind of
the spelling seen first, so where two spellings have different kinds
("task" is Other, "Task" is Task) the Categories legend changed with
the order sessions were read in, and no longer matched the weeks
(pd.tools), which count each spelling under its own kind. The legend
now counts each call under ToolCategory of the name it was called by,
as before b2a8b74c7; only the Top rows merge. The tie-break comment
said "the shorter name", where the code takes the first in byte order.
TestToolUseMergesSpellings gains "the legend keeps each spelling's own
kind" ("task" 3 then "Task" 5: legend Task 5, Other 3). Broken by hand:
with b2a8b74c7's stats.go it is red ("categories [{Name:Other Calls:8
Sessions:2}]"), green with this.
Run at the pushed head on mote: go test ./... -timeout 45m on mote with this branch on
|
||
|
|
1c76095e97 |
usage: the tool list groups tools case-insensitively, as its summary does (#2969)
What changed
- toolUse now folds a tool's spellings into one row of the sessions'
"Tool use" detail list: its calls and sessions are summed under one
case-insensitive name, the row is shown by the summary's own spelling
when the tool is its kind save for the case ("bash" as "Bash"), and by
its most called spelling otherwise. A session that called both ways
counts once.
- The summary's per-kind list ("Bash 2.2K") already merged the spellings,
via ToolCategory; the detail list keyed its rows by the raw name, so
the same tool read as two.
Why (issue #2969)
The card's left list split `bash` (1.4K calls, 20 sessions) from `Bash`
(779, 2), `read` (192, 15) from `Read` (123, 1) and `write` (64, 13) from
`Write` (56, 1), while the right legend showed one Bash 2.2K, Read 315,
Write 120 - the sums of each pair. Same card, two answers. The detail
rows now answer with the summary.
Run
- go test ./internal/sessions/ -run TestToolUseMergesSpellings: fails on
the old code (the split above), passes on the new; a session that
called `read` and `Read` counts once, and tools that only share a kind
(two mcp__ tools) stay apart.
- go test ./internal/sessions/: ok.
- gofmt -l on the touched files: clean; go vet ./internal/sessions/: clean;
go build ./...: ok.
Landed (yetone), at the pushed head on mote: go test ./... -timeout 45m on mote with this branch on
|
||
|
|
e55bab72df |
sessions: the gateway's sessions are merged beside the native ones, not into a copy of them (#2278)
MergeExternalStats grew a copy of every native Summary to append the gateway-only sessions, and cloned them all again, with their days, when the gateway's history began before the session files. Each range the Sessions page keeps (7, 30, every day) held that copy beside the Summaries it was copied from: ~10 MB over the full history, made again on every 10 s refresh. Stats now keeps the gateway's Summaries in their own slice, sorted by Last, and a day shift instead of rewritten days. Overview walks both in the order the merged list had (the most recent first, a native session first of two as recent), adds the shift to each day, gives toolUse the shifted first day, and shifts the Top copies it hands out. AllSessions gives the merged list as one copy for the tests that read it. Overview is the only reader of the merged sessions outside tests: aliasStats and keepDesktop run before the merge, and the stats answer doesn't encode Sessions. Run on mote at |
||
|
|
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
|
||
|
|
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
|
||
|
|
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 |
||
|
|
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
|
||
|
|
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 |
||
|
|
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
|
||
|
|
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
|
||
|
|
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 (
|
||
|
|
b027ca264d |
sessions: a pass over every session looks at Codex's title index once (#3493)
assemble and assembleListed asked CodexTitles for each Codex session, and each ask took the index's lock and stat'ed session_index.jsonl. A start's stats step assembles every session, so on the owner's data (sbpairs copy: ~10G Claude, ~50G Codex rollouts) CodexTitles was 60ms of step 0's 860ms CPU profile. codexTitleOf gives a pass one function that looks at the index on its first ask and again only when another reader loaded a different index in between; every caller of assemble and assembleListed makes one per pass, beside its pricer(). Run at this head (rebased on origin/main below): - zzwarm step 0 CPU profile on the sbpairs real data: CodexTitles, codexTitlesAt and loadCodexTitles 60ms -> absent; statsRead 340ms -> 270ms cum. Wall times at load 40-76 were within noise both ways. - TestCodexTitleOfLooksOnce: no index, an index made mid-pass not seen in that pass, seen in the next, a rename mid-pass keeps the first name. Broken by hand (re-ask on every call): red at "an index made after the first ask". - go test ./internal/sessions ./internal/usage ./internal/gui ok; -race ./internal/sessions ok; GOOS=linux/windows go vet -tags nogui ./internal/sessions ok; gofmt clean. Not changed: gui's own CodexTitles callers (trace.go, context.go) ask for a few ids at a time already. Not tried: a Linux or Windows real-data run. |
||
|
|
ea9454d2d8 |
usage: count two ids of one model as one, magpie model alias (SlouchyQuill507 on Discord)
A vendor names one model two ways (deepseek-v4.1-flash and deepseek-flash),
and Usage, Usage > Sessions and `magpie usage` showed two rows. Now:
magpie model alias deepseek-v4.1-flash deepseek-flash
magpie model alias deepseek-v4.1-flash (what it is counted as)
magpie model alias deepseek-v4.1-flash --reset
magpie model aliases
kept as settings.json "usageAliases" {from: to}. Off until one is written.
Ids match as routing groups match them (provider.sameModel: vendor/ prefix,
case, "_", snapshot date), at every provider; a chain is followed to its
end; an alias to itself, a loop, or a flag as an id is refused. A loop
written into the file by hand counts each model under its own id.
Display only: requests, agents' model lists, /v1/models, routing groups,
Same as and prices never read it. Each call is priced by the id it was
made under and only then counted under the alias; the alias's own price
is never put on the other id's calls, and a merged row is priced only
when every id in it is. Applied in usage summarize/direct (Models
groups), the gateway sessions projection (alias read before
gatewayCache's lock; the cache key hashes usageAliases), and
sessions.List/Get/Find/Stats (read before storeMu/mu, merged into new
slices so the memo is untouched; ModelEffort rows merged too). A failed
settings.json read keeps the last aliases read, and SetUsageAlias refuses
to write over an unreadable file (EditUsageAliases under fileMu). The GUI
settings save carries usageAliases. No GUI control.
Not aliased: the Requests ledger's per-request model and its model
filter, which show each call's own id.
Run (worktree at
|
||
|
|
42e6aee534 |
sessions: the stats and id lookups don't build every session's subagents
Why: in a 48-minute heap profile of the user's magpie,
gui.combinedSessionStats → statsFor → StatsAndNative → statsIn
allocated 3.9 GB, and gui.warmSessions → Warm 5.7 GB. Their scans went
through assemble → subagentsOf → ccTask: the stats built every
session's subagents (each one's task read from its file), only to
count tokens and tell which sessions are listed. Every statsFor call
in the profile came from the warm-up's steps.
What changed:
- assemble is split. assembleListed holds the part that decides
whether a session is listed and gives its agent, id, title, models
and usage. assemble adds resume, carry, transcript and subagents on
top.
- These callers now use assembleListed: the stats' native-key and
summary loops (stats.go), Titles, the Codex provider lookup
(codex_provider.go) and manage's id lookup.
- List, One and manage's listing still use assemble.
- The docs/subsystems/gateway-sessions.md subagent section says
which callers build subagents.
Tests:
- TestStatsReadNoSubagentFile writes a subagent with no meta and no
task in its first lines, then simulates a restart (Saved, Reset,
memos cleared). It then runs StatsAndNative(0), StatsAndNative(30)
and StatsFor(7) three times and expects 0 scans of that file. List
still shows the subagent.
- Broken by hand: the stats back on assemble make it go red with
"the stats read an unchanged subagent's file 1 times". Green again
once restored.
Measured on a read-only APFS clone of the user's ~/.claude/projects
and ~/.codex/sessions/2026/10, in a sandbox HOME, at load ~500 from
other sessions. The whole series against origin/main dee5c9d75; this
commit is the change to the stats rows.
| Pass | origin/main | This series |
| --- | --- | --- |
| warm StatsAndNative(0) | 596.7 MB, 157,195 allocs, 6.2–9.0 s | 28.9 MB, 73,976 allocs, 0.08–1.1 s |
| warm StatsAndNative(30) | 594.9 MB, 6.8 s | 28.7 MB, 0.8 s |
| restart StatsAndNative(0) | 3,106.7 MB, 509,239 allocs, 30.0 s | 48.2 MB, 241,721 allocs, 1.9 s |
| restart StatsAndNative(30) | 594.9 MB, 9.6 s | 28.7 MB, 0.5 s |
Run at the final tree of this series:
- gofmt -l internal: nothing.
- GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean.
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/:
- sessions: ok, 366.7s.
- gui: only TestMainWindowCorners failed, "measuring the windows:
signal: killed". It also fails alone on an untouched origin/main
export, at load ~500. Filed as #1936 and #2645. Every other gui
test passed.
- go test -race -count=3 on the new tests: ok.
|
||
|
|
c381e4cd1e |
sessions: a read is never held by another read's refresh, only by a change to the files (#2776)
A read of the sessions (List, Stats, Manage, the agents' lists, Codex's threads) took dbReadMu, a plain mutex, for the whole call, parse included. The start's warm-up reads every session file with a quarter of the cores, so the first pages and API calls after a start waited for its whole read before they could even look at the cache. - dbReadMu becomes storeMu, an RWMutex: reads take it shared, and only the changes to the files (Delete, a Codex provider move, a Claude project relocation) take it alone. - A file another refresh is reading now is in `parsing`, with a channel closed when its parse is in the cache. A second read serves the parse it already has of such a file, and waits only for one it has never read; it never reads the same file twice at once. - Each parse is published as it finishes, not in checkpoint batches, so a waiting reader gets it at once. - The shared store handles (OpenCode, Hermes, Alma, Cursor) closed at the end of every read; with reads overlapping, one could close a handle another still used. They now live as long as their last user (useDBs). get() and the titles path closed them without the lock at all before. Tests (internal/sessions/refresh_shared_test.go), each broken by hand: - TestReadNotHeldByAnotherRead: the warm-up's parse of 12 grown files is held; List and Manage answer within 10s from the kept parses, each file is parsed once in all, and a later List parses none. With storeMu.Lock in List: red, "List waited for another read of the same files to end". - TestReadWaitsForAFirstReadUnderWay: a file never read is waited for, not served empty, and read once. Without the waits: red, "List answered without the files being read". Without the skip of a file being read: panic, close of nil channel. - TestStoresLiveAsLongAsTheirLastUser: with the release always closing: red, "closed while a read still used it". All three pass with -race. Measured on a sandbox instance (600k gateway calls, ~4,600 Claude Code and Codex sessions, 300 grown since the last start; 4 API calls asked 3.5s after the routes, when the warm-up starts), base |
||
|
|
81029fc63c |
sessions: the overview's stats and their native sessions come of one pass over the files (#2776)
combinedSessionStats, behind /api/sessions/stats and /overview (each
range read again in the background when its memo is over 10 s old, so
on every 15 s poll of the Sessions page), took sessions.StatsFor and then
sessions.List(All) only for the agent|id set that keeps a gateway session
the agent keeps too from counting twice: two passes over every agent's
files, each refreshing them all. sessions.StatsAndNative gives both from
StatsFor's one pass: the same set, a session List would list (one
nothing was said in still left out, as before), but with no 5000 limit,
so a gateway session whose native one is among the oldest of a long
history is no longer counted again.
Test: TestStatsAndNativeOnePass: one pass over the files (filesHook, new),
and the same keys as List(All) on the fixtures. Red with StatsAndNative
written as the old pair of calls: "2 passes over the files".
Measured on the synthetic sandbox HOME (3000 Claude Code, 1500 Codex,
2000 Hermes sessions), combinedSessionStats warm after a restart, CPU
time (load average ~250, wall times noisy), parent 8e2b1dce6 against
this change, 4 rounds each:
days=30 94-99 ms -> 57-62 ms CPU
days=0 107-130 ms -> 68-74 ms CPU
first after a restart (days=30) 558 -> 510 ms CPU
Run at this commit (the series' last; it covers 0179cef63, bbee24810
and 8e2b1dce6 too), on a machine at load average ~250-500:
- go test ./... -timeout 45m: 60 packages ok, sessions (869.8s), usage
ok. Red only under that load, all green when run again:
- internal/agent and internal/gateway timed out at 45m in tests that
don't touch sessions (TestPiOffersItsOwnOpenAICodexModels,
TestVisionSettingPicksTheDescriber). Run again with -timeout 90m:
agent ok (1394.2s), gateway ok (1546.9s).
- internal/gui TestSetAnswersWhileDevinAndProvidersHang: set took
44.6s under load; it is #1375. Alone: ok.
- internal/plugin TestGatewayHookMixedPiPackage: "starting plugins:
context deadline exceeded" after 718s (bun's install cache was slow).
Alone: ok (163.6s). No issue found for it.
- gofmt -l: clean.
- GOOS=windows go vet ./...: ok.
- GOOS=linux go vet -tags nogui ./...: ok. Without the tag, vet stops in
wails v3's own linux files (undefined: pointer, cgo off when vetting
across OSes from macOS); go.mod is untouched here.
- No GUI assets changed, so the GUI suite was not run.
|
||
|
|
6e17d58ebf |
usage: a top session only the gateway saw says "Gateway session", not "(no prompt)" with no folder (#2285)
The reporter's Usage › Sessions card listed seven Pi sessions on
deepseek-v4-pro as "(no prompt)" with no folder, and their routing group
has no DeepSeek. Those rows were gateway projections: Pi asked magpie for
deepseek/deepseek-v4-pro (every served model is in Pi's models.json), most
likely through a pi-subagents child, whose session file is in a temp folder
magpie never reads. The card gave no sign of that, so it read as Pi's own
sessions with an empty prompt, and our first reply took it that way.
The overview's summaries from MergeExternalStats now carry gateway: true,
as MergeExternal's list rows already did. The card shows "Gateway session"
where the folder would be, "(prompt not recorded)" as the title when no
text was kept, and a tooltip pointing to Record gateway conversations.
Strings in zh, zh-TW, ja and de. gateway-sessions.md says it.
Run in this worktree (
|
||
|
|
3c4b4dc973 |
sessions, usage: a Codex subagent with no title takes its parent's spawn_agent task_name, its nickname shows apart, and Usage requests say which calls were compactions (#1591, Hogeexxl)
Hogeexxl's change (his fork branch codex/codex-session-details, f7c176c9),
cherry-picked with his authorship:
- A Codex child thread whose title is still empty after the existing
precedence takes the task_name of the parent's spawn_agent call, linked by
the call id and the SubAgentActivity "started" item that names the child's
agent_thread_id. Conflicting links leave the title empty.
- session_meta.agent_nickname is exposed as `nickname` on the list, one,
manage and overview responses, beside the title, not in place of it.
- GET /api/usage/requests and /v1/magpie/usage/requests carry `compaction`
(true/false) for Codex calls with native evidence, and leave it out
otherwise. A gateway row matched by a unique response_id takes the marker
and keeps its own model, usage, cost and kind.
- Flags bits 1024 (rowCompactionKnown) and 2048 (rowCompaction) are new.
TestRowFlagsApart covers them, and they don't overlap 1..512. The sessions
cache goes to version 21 and the calls cache to calls-v15.
Review:
- Rollout format checked against Codex's source (openai/codex 669449b):
- v2 spawn_agent args carry task_name.
- A paginated rollout persists item_completed with a SubAgentActivity
item: kind "started", id = the call id, agent_thread_id.
- SessionMeta has a top-level agent_nickname, which Codex's own list.rs
and metadata.rs read too.
- compaction_response_id lives in token_usage_record.
Gaps in legacy rollouts and in calls without a response_id are fixed in
the next two commits.
- Privacy: only a title string the user's own Codex wrote and a boolean
are added to local API responses. Nothing new goes to a vendor or to
telemetry. The ingest POST parses fields one by one, so it is unchanged.
- No .github, dependency or network changes.
What was run:
- His tests pass: go test -tags nogui ./internal/sessions ./internal/usage,
and the two new internal/gui API tests.
- Broken by hand, each caught by his tests:
- the nickname read removed;
- the conflict checks removed;
- mergeCodexCompactions broken;
- the gateway pair's setCodexCompaction removed;
- the flag read forced to true.
- Not caught:
- the parent check on the title link (covered by a test in the next
commit);
- `copy.codexCompactions = nil` in cloneCodexChunks removed. That line is
defensive only: the shared chunks never hold the map.
- The gofmt, vet and full-suite record for the three commits is in the
last one.
|
||
|
|
644f4316f9 |
sessions, usage, gui: separate Codex thread relationships and consumption (#1591)
Preserve native Codex thread IDs and explicit parent chains. Associate gateway calls with their actual thread by unique response ID before legacy matching; fold identical native history copies and keep ambiguous actors unknown. Existing Sessions APIs expose optional Codex roles, parent/root relationships and per-thread model/effort consumption. The overview uses its existing calendar range. Usage request APIs expose query-time actor classification and reuse session/subagent/parent_agent for Codex. Other agents, pricing, gateway routing, UI assets, raw Usage logs and model-only aggregation retain their semantics. Verified after rebasing onto main |
||
|
|
ab1cefeed8 |
sessions, gui: Usage's Sessions list shows the sessions the range counted (#1251, wizzy-yang)
The Sessions tab listed every session whose last line fell in the range, and
counted only those stats found at work there. A session whose file goes on
being written after its last call (a setting, a fork's seed) was listed but
not counted, so the note beside the list said more than the KPI above it.
statsAt now returns keys (agent:id) for the sessions it counted, in the
list's order. app.js filters the list by them in every range and falls back
to the old last-line guess only when keys are missing.
The PR also made days with prompts or replies count as at work, so a
session that spoke but spent nothing (one user line, a Cursor chat) is not
dropped. Main's
|
||
|
|
1cd8140047 |
sessions: read Cursor editor history and Cursor/OpenCode conversations (#1743)
Discover editor project transcripts and cursorDiskKV histories without modifying the source. Share one SQLite/WAL snapshot across a scan, refresh metadata changes, deduplicate CLI histories, and reject deletion of read-only sessions. Count message-only sessions and expose an all-dates action when a filter hides existing history. Read Cursor CLI text, reasoning and tool parts, and OpenCode v1/v2 transcripts through the existing transcript API. |
||
|
|
71d2da1f42 |
catalog, usage, gateway, gui: a price can have a long-context tier and a 1-hour cache write, and the price boxes take decimals (PAMI on Discord)
OpenAI bills gpt-6-astra, gpt-6.1-sol and gpt-6-luna over 272K input at 2× input and cache and 1.5× output, for the whole request. A price now has tiers: `magpie model price <m> 10,50,1,12.5 --tier 272k 20,75,2,25` (--tier can repeat). A tier applies when input + cache reads + cache writes is over its size, so 272,000 is not over and 272,001 is. The built-in prices take tiers only where models.dev lists one (cost.tiers of type "context"), and it does list one for those three. The ledger, each request and OTLP are costed at the tier the call reached. Session and day totals sum many calls, so they stay at the base price.
Anthropic bills a cache write kept for an hour at 2× input and one kept for 5 minutes at 1.25×. Its usage reports which is which in cache_creation.ephemeral_5m/1h_input_tokens. The gateway (API and Claude subscription) and Claude Code's transcripts now keep that split. A price's fifth part is the 1-hour write. When it isn't given, it is 2× input: that is Anthropic's rule, and only Anthropic reports 1-hour writes. Claude list prices carry the 2× too. cache_write_tokens is still the total, and the usage CSV adds cache_write_5m_tokens and cache_write_1h_tokens at the end. The app shows the split on a request's Cache and on the usage tooltips. Old prices and old records, which have no 1-hour part, read as before. The sessions cache (18) and the call cache (calls-v8) are re-read once.
In the GUI, the price boxes were number inputs and dropped what they didn't parse ("0,25"). They are now decimal text boxes that take both "0.25" and "0,25". A model's price row has a 1-hour box (empty means 2× input) and a quiet Long-context price row. That row shows the list's tier greyed in, or sits behind a link when the list has none. A bad size is refused by name. en/zh/ja/de.
Tests:
- New: TestPriceTiers, TestCostSplit, TestPriceJSON, TestModelPriceTiers, TestModelPriceTierCmd, TestAnthropicCacheWriteSplit and TestClaudeCacheWriteSplit. The ledger CSV test expects the new columns.
- model-price-tiers.test.cjs is new; model-price-edit and provider-price-rate are updated. All of them fail against the old assets and pass in WebKit. Chromium couldn't be launched here.
- go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass.
|
||
|
|
c0f3fa012a |
usage: combine gateway and local session requests with model charts and account labels (#239)
* usage: Requests lists the agents' own session-file calls, put to the vendor and account their files prove, charts them by provider, agent or model, shows what was said, and the tray panel gets a Usage tab The Usage page's Requests tab now covers requests an agent sends with its own sign-in (Claude Desktop's Code tab and Cowork, Claude Code, Codex), which never pass the gateway, and shows more of every request: why it failed, what was said in it, who it was of. Requests tab: a strip of four totals (tokens, requests, cost, cache hit rate); the trend of one metric — tokens, cost or requests — as columns by the hour, day or week, told apart by provider, agent or model (both remembered), beside a ranking of the same that is its legend and a way in (a click lists only that provider's or agent's requests; a provider picker sits beside the agent's). The ranking is as tall as the chart and scrolls in itself, with no scrollbar: a slim rail in the card's margin shows how much there is and where it is (its thumb dragged, the rail clicked), and the edge with more beyond it fades; under the chart (860px and narrower) it shows whole. A row opens to its details: the vendor's error type and words, request id, endpoint, and what was said in it (input and output, read from the agent's session file when opened, the call that ended nearest the request — nothing stored). A refresh period (off / 5 s / 10 s / 30 s / 1 min) and refresh-now. The Overview says it counts gateway calls only; Requests and the panel say they count both. The tray panel gets a Usage tab (today / 7 / 30 days, provider picker, four totals, a small chart, top five, "Open Usage"), and is as tall as its tallest tab (#124). Provider and account of a session-file call: never magpie's "claude" or "codex" subscription. Anthropic's when Claude Desktop's session metadata (not Claude-3p) names the account and organization, with that account's email; OpenAI's when Codex's rollout names a provider that is OpenAI's in config.toml — the built-in "openai", or a named one at OpenAI's address or signed in with the ChatGPT account and no base_url (requires_openai_auth) — with the creator account's email when the file records it. Anything else is "Local session", its recorded provider id and session account kept (CSV: session_provider, session_account). The config read is today's: a file names the provider id only. Gateway: a failed call keeps the vendor's error text and type, request id and endpoint; a Claude subscription's failure uses the status Claude Code reports (api_error_status). A request turned away before any vendor was asked is logged, marked rejected, listed in Requests and left out of every total. The client's own session header is kept as native_session beside X-Magpie-Session, and a session-file call is matched to a gateway record by request id, then by that session, equal tokens and an end within 2 s, only when unique both ways. Reading: session-file calls live in the session index main keeps on disk, parsed incrementally and outside its lock (Claude Code, Cowork in both Claude folders, Codex); the usage log is read on from where it was; a page builds the ledger once. Days are counted on calendar dates (DST). CSV gains request_id, endpoint, error_message, error_type, source, session_provider, session_account. i18n: one "Endpoint" (终结点), which a second key had turned for Azure's field. Tested: go vet ./..., go build (also GOOS=linux/windows, -tags nogui) and go test -tags nogui ./... pass. The whole GUI suite in Chromium and WebKit, en and zh (Playwright 1.62.1): all 393 tests pass. On this computer's files (7 days): 3,330 Claude Desktop calls resolve to Anthropic with the account, 1,991 Codex calls on a named ChatGPT-signed-in provider to OpenAI (620 with the account; older rollouts don't record it), 9 Claude Code CLI calls stay Local session. Co-authored-by: yetone <yetoneful@gmail.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * usage: a session-file call of one of magpie's own Codex or Claude accounts is told as that provider, beside the gateway's calls on it — "OpenAI" and "Codex" (or "Anthropic" and "Claude Code") read as two vendors when they were one subscription Codex: an official route (above) whose creator account and user are one of magpie's Codex sign-ins (the CLI's own or a saved one) is magpie's "codex", with that account's email as the gateway's rows have it. Claude Desktop (not Claude-3p): an account and organization that are one of magpie's Claude sign-ins is magpie's "claude". Only while magpie has that provider signed in; another account, a rollout with no account recorded, or an ambiguous workspace stays OpenAI or Anthropic, and a relay stays Local session. Tested: TestSessionCallsOfMagpiesAccountsAreItsProviders (the account matched, another account, none recorded, magpie's account through a relay, Desktop in magpie's and another organization, Claude-3p, magpie signed out) and TestLedgerTellsCodexSessionCallsAsMagpiesCodex (a gateway Codex call and a session call of its account one provider of two calls, another account's OpenAI). On this computer (7 days): 3,439 Claude Desktop calls are magpie's Claude, 626 Codex calls its Codex, 1,322 older Codex rollouts with no account stay OpenAI. go test -tags nogui ./... and the usage GUI tests pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: 修复请求统计缓存膨胀与会话账号误归属 #239 调用明细改为按会话文件分片保存并限制内存缓存,汇总索引仅保留统计数据;网关日志按需读取。 严格匹配订阅账号与用户 ID,排除自定义渠道、非官方端点覆盖、外部 CODEX_HOME 及关闭的供应商。补齐零 token 失败去重、Codex 原始会话 ID、拒绝标记导出和面板显示修复。 通过全量 Go 测试、静态检查、受影响模块的并发检查、52 项浏览器测试及 macOS/Linux/Windows 构建;使用 35 万条合成调用验证索引体积与内存改善。 * fix: 降低请求统计刷新与写入开销并明确本地账号展示 #239 请求分片改为追加帧和字符串去重,分页复用未变化的紧凑快照,采用 LRU 并移出全局锁内的磁盘读取。缓存 Cowork 目录,补齐同前缀改写检测及崩溃临时文件清理。 本地记录仅显示匹配账号或本地会话,明确官方登录标记与请求路由的区别。默认今日与模型维度,Auto Review 复用共享目录定价并单独标注估价参考。 完整 Go 测试、vet、相关 race 和 52 项浏览器回归通过;提供 2000 文件及四个大会话连续追加的可复现性能对照。 * fix: 优化用量徽标与耗时分级并保护分页边界 #239 官方登录、API、订阅和本地会话采用独立颜色与柔和底色,兼容明暗主题。耗时按 10 秒及 30 秒阈值着色,保留估算标识与原始毫秒提示;无有效耗时显示短横线。 限制分页选取范围,避免超大偏移整数溢出及越界空页的无效堆构造。补充阈值、徽标对比度和极端分页参数回归。 * fix: 将账号与来源徽标分为两行展示 #239 * fix: 提高用量表格模型文字对比度 #239 发送模型和已知实际模型使用主题正文次级色,表头与时间同步加深。保留缺失值弱化、转发提示和本地日志来源说明。Chromium 与 WebKit 的中英文、浅深色主题 10 项界面检查通过。 --------- Co-authored-by: yetone <yetoneful@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
42d81bc1ff | sessions: Pi's and omp's sessions count their prompts, replies, tool calls and skills (#384) — Usage → Sessions filtered to Pi showed no session shape by messages or tool calls, no tools and no skills: piParse read only the title, the model and the usage, and the fast path dropped every user line after the first. Now, from Pi's v3 session format as its source writes it (packages/ai types.ts: AssistantMessage content ToolCall {type:"toolCall",name,arguments}, ToolResultMessage nestedCalls.calls; agent-session.ts: /skill:name sent as <skill name="…" location="…">; skills.ts: a skill is loaded by reading its SKILL.md), a typed user message is a prompt, an assistant message a reply, each toolCall part a tool call, a tool's nestedCalls (a codemode script's) calls too, and a read of a SKILL.md (or omp's skill://) or a /skill: prompt a skill; a fork's copied entries count in the session they came from. ToolCategory knows Pi's lowercase names (bash, powershell, read, write, find, ls). The sessions cache version goes to 6 so kept parses are read again. TestPiToolsAndMessages and TestToolCategoryPi fail without the change. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (TestUserPath and the Claude account tests flake under load, pass alone). | ||
|
|
901ee08280 |
Count usage at the configured provider/model price (#278)
Magpie reports models.dev's list price for every call. That is the right number for a vendor's own key and the wrong one for a provider that resells or exposes a model at a different tariff, and it leaves a model the catalogue does not list with no cost at all — a provider's own /models gives ids, not economics. magpie model price relay-a/gpt-5.5 0.12,1.20,0.01,0.15 magpie model price relay-a/* 0.12,1.20,0.01,0.15 magpie model price relay-a/gpt-5.5 --reset magpie model prices Absolute USD per million tokens. All four parts are required: a price missing one would understate the rest of every call, and a hand-edited file that left a part out would bill it at zero, so each part is a pointer and the setter refuses a price that is negative, NaN or infinite, naming the part at fault. Zero stays distinct throughout — a model served at no cost has a price, not the absence of one. A `<provider>/*` entry covers every model of that provider and an exact entry wins over it; --reset removes only the exact entry and says so when a provider-wide one is still in force. The order a price is looked for in is the price for this model, then `<provider>/*`, then the provider's own catalogue, then models.dev for the maker. A price is a provider's tariff, not the model's: the same model through two providers has two prices, and each keeps its own. A provider is resolved by its id, or by an id it was renamed from, and never by its display name — Find answers those too, and a record naming one was counted at another provider's price. provider.EffectivePrice is the one lookup every cost caller shares, so the usage ledger and a session's totals both go through it, and a session naming a model bare is still priced at its maker's list price, which is a different question from what one provider charges. catalog.PriceOf and PricedBy keep returning the models.dev price for anything wanting an unbiased number. The background-task pickers (draw, search, vision) still rank by catalogue price: they choose which model answers, not what a call is reported to cost. Unlike every other per-model preference this does not call catalog.Touched. What a call costs is not what an agent picks a model by, and the model lists magpie keeps in the agents' own files are not its to rewrite over a number in a cost report. A rename moves the prices with it through the walk #288 adds, so nothing here has to say so, and an id recorded before a rename still resolves. Validation happens where the entry is written, not in Save: one hand-edited bad price in the file must not make saving a theme or a window size fail. A price for a model the provider does not serve is refused the way `magpie model name` refuses the same id, since it is a price that never applies and nothing reports it as dead; a removal is exempt, so an entry left for a model that has since gone can still be taken away. |
||
|
|
317bc70875 |
sessions: one index run a page shows once, a spinner, a session-shape chart that reads, and every session counted in it (Image #9–#13: 排版不对…土土的; 这个原点的动画可以换成别的吗; 这个图我着实没看懂; 出现之后又消失又出现…跑完之后突然又出现; 为什么只有5个会话)
- The index hero flickered and ran again: the sessions list, the stats and a
range change each started their own refresh of just the files they wanted,
and the page showed a fallback hero after 700 ms whether or not anything was
being read. List and stats now refresh every changed file in one run, so the
read after it has nothing to do and a wider range finds the files read; the
hero shows only while the server says it is indexing, and once it is done it
stays at 100% ("Indexed · putting the page together…") and never starts over.
- The hero: a dot field in the accent alone, a big percentage, a hairline bar;
a thin spinning ring in place of the pulsing dot, still when done or for
reduced motion.
- Session shape: bars stand on a baseline with no grey column behind them,
an empty bin is "0" over a stub, the busiest bin is in full accent (only
when one is busiest), "Autonomy" is "Tool calls" (工具调用), and a line says
what each axis is (横轴:… · 柱高:会话数).
- Only 5 sessions in the shape: parses kept by an early cacheVersion 4 had no
prompts or replies, and were never read again, so the chart skipped them.
cacheVersion 5 reads them again (on real data 385 of 462 sessions over 30
days, rather than 5). Sessions of agents that tell no messages (pi, grok…)
now count by their minutes at work.
Tested: TestShapesMinutesWithoutMessages; sessions-overview.test.cjs in Chromium
and WebKit, en and zh (the bars, zero stub, peak, both footers, the tool-calls
label); go test -tags nogui ./..., builds for darwin, linux, windows. Two GUI
files failing in the parallel run (click-scroll WebKit, login-import chromium
zh) pass alone.
|
||
|
|
41841997d6 |
sessions: a fast index with an animated first run, searchable model and folder pickers, and the overview's session shape, tool use, top skills and heatmap by messages or output tokens (v: 感觉我们的Session可观测性页面也要做的这么的丰富、优雅、简洁…; 顶多第一次打开顶多需要个1分钟,然后之后都是靠索引能够极快的打开; 一定一定要特别炫酷的一个动画; Image #6/#7/#8)
The index: session files are read in parallel and each line told from its first bytes (a Claude line's type, message head and usage; a Codex line's type and payload), so tool results, attachments and compactions are never decoded; a cold index of this machine's sessions takes about 32 s, then the page opens from ~/.cache/magpie/sessions.json (version 4, which re-indexes once) and only changed files are read again. The page keeps showing the last answer while a fresh one is computed, and GET /api/sessions/progress says how far a first run is, which the page shows in an animated hero instead of a spinner (reduced motion respected). All models and All folders are searchable combo boxes that draw only the rows in sight, so 13k folders open at once. Each day now counts the prompts typed, replies, tool calls by name and skills called (a subagent's calls and tokens count, its messages don't). The overview adds: - Session shape (会话形态): sessions by messages (1–5 … 121+), minutes at work, or autonomy (tool calls a prompt, <1 … 21+), toggled and remembered; - Tool use (Tool 使用): calls and sessions, the top tools with their kind's dot, calls, sessions and share, the kinds (Bash, Edit, Read, Write, Grep, Glob, Task, MCP tools, other) as a stacked bar and by week; - Top skills (常用 Skills): each skill's calls, sessions, last use, agents' share and projects; - the activity heatmap by Output tokens (输出 Token) and Messages (消息) beside Tokens, Sessions, Cost and Active. No border stripes; a toggle leaves the page where it was. Tested with TestStatsToolsAndSkills (Claude reply blocks laid out both ways, a Skill call, an MCP tool, /clear, an interrupt, a subagent; a Codex rollout's function and custom tool calls) and the stats tests, and internal/gui/tests/sessions-overview.test.cjs in Chromium and WebKit, en and zh: the new metrics and their tips, the shape's buckets and toggles (the page not moved), the tools' rows, kinds and weeks, the skills' lines, nothing overflowing at 1100 and 560 px. go vet, go build -tags nogui (and GOOS=linux, GOOS=windows), go test -tags nogui ./... and the GUI suite pass (panel-fold flaked once in the parallel run, passes alone). |
||
|
|
44cd8fac4c | sessions: OpenCode's and Pi's sessions are listed too (貌似没有opencode和pi的session,能支持一下么) — Usage → Sessions, magpie sessions and the TUI read OpenCode's opencode.db (or $OPENCODE_DB) read-only, or its older storage/ JSON files when there is no database, under $XDG_DATA_HOME/opencode or ~/.local/share/opencode, a subagent's session counted under the one that started it; and Pi's JSONL sessions under $PI_CODING_AGENT_DIR or ~/.pi/agent, plus $PI_CODING_AGENT_SESSION_DIR or settings.json's sessionDir, a forked session not counting again what it copied from its parent. Each gets its title, folder, times, tokens per model with cache reads and writes, cost, and a resume command (opencode --session <id>, pi --session <id>); the folders note names only the agents that are there | ||
|
|
3dabb56ac9 | sessions: history by day in the CLI and the TUI — magpie sessions lists the latest Claude Code and Codex sessions (when, agent, folder, first prompt, tokens, cost; --limit, --json with the resume commands), and with --days N|today|all (stats alone is 7) prints the range's totals (tokens, list-price cost, cache read and hit rate, active time and on how many days), a line a day with its tokens, cost, cache read, active time and a bar, then the top models and folders; --model and --folder narrow either, matched exactly, by base name or by a unique part, an unknown one naming those there are. The TUI gets a sessions page after usage (5; the library is 6 now) with the ranges today, 7, 30, 90 days and all (←→, t w m A), M and f to pick a model or a folder from those the range has, x to clear them, the totals, and a chart of the days in block characters, a week a column when the days don't fit, of tokens or, with c, cost. Both sum sessions.StatsFor as GET /api/sessions/stats does, through Stats.Sum, which rolls the days up under a model and a folder as the app's view does — active time not kept by model, so none under one | ||
|
|
e3984b2442 | sessions: history by day — the Sessions view gets a range (today, 7, 30, 90 days or all), model and folder pickers, tiles for the range's cost, tokens, cache read and active time, and a daily bar chart of tokens or cost (weekly past 92 days). Each session file's cached reading now keeps its usage per local date and model, a message counted on the day of its timestamp, so a session that runs past midnight splits across both days and a file read on from where it stopped adds only what's new; Claude Code's repeated usage for one message moves with it to its last block's day. Totals come from every session file in the range, not the latest 200 the list shows: GET /api/sessions/stats?days=N returns each day's rows by agent, folder and model with their cost, so the view filters without asking again, and files last written before the range aren't read at all. Active time is the sum of gaps under five minutes between one line and the next in a session's main file (subagents run alongside it, so theirs aren't added), credited to the later line's day. The cache is version 2 and records the time zone, a change of which reads the files again; the list no longer drops the cached readings of files it doesn't show, only of files that are gone, and changed files are parsed in parallel. On 4000 synthetic files (880MB, 180 days) a cold read takes 0.74s, a warm one 22ms, a reload from the 4.7MB cache 49ms |