ac4af582301a4e8a29245dbba767eba31334ddf9
19
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
16e79fc6b0 |
dsh: a request still answering shows under its fork, not its source (#5542)
The Routing page's live card for a dsh fork's request showed under the
source until the reply was written: it has no reply id yet, and the
opening it is keyed by is the one the fork copied. The messages of the
request's turn are in the branch's own session file before the request
goes out, so they name it:
- gateway: Route.LastConvs, the ids of the user messages the request's
turn carries, newest first (dshLastConvs, dsh only, at most 4);
- sessions: TurnConvs, the ids of the newest turn's user messages, reset
at turn/start, not kept from a fork's seed, at most 4 (dshTurnKept);
dsh's parse version goes to 3;
- gui: ownerBy asks the reply id, then the turn's messages, then the
opening (ownerOfRoute on the Routing page).
Changed from Flandern1211's patch (957caf84) in review:
- the turn lookup has the reply id's guard (forkedFrom): a "继续" in
another conversation's newest turn no longer takes a route;
- in dsh's captured requests (sessions/testdata/dsh-gateway) the newest
user message is the runtime context, the same for every session of a
folder, so it names no one: the gateway reads the whole run of the
turn's user messages (typed + context), and passes over Messages'
tool_result steps, where the patch returned nil;
- looseKeys asks for a turn's keys only while the route answers and for
convsKept, not for every older route: those keys are never listed
once a newer turn starts, and would relist every agent's sessions on
each 2s poll;
- one spelling per message and at most 4 kept (a v3 file has no
turn/start, so TurnConvs grew with every message, 3 ids each);
- no TurnConvs on Context's records (it counts done calls, named by
reply), LastConvs dropped from the history (saveRoute) and from what
the page is sent;
- dshLastConvs reads messages by their members, not decoded: 0.49 ms
on a 2.2 MB body of 800 tool steps (convOf 0.30 ms), 1.10 ms before.
Run on mote at 2be7aaeea (this change on 9730e0199; then rebased over
|
||
|
|
f418edffc3 |
sessions: a session's details show how full its context was, request by request
liang_yongxiang on Discord: Routing tells how full one request's context window was; does Sessions have the same, each turn's share? A session's details on the Sessions page (and in Usage's Sessions list, which draws the same details) get a Context line when the gateway sent calls of it (s.via): the Context tab's spark of its prompts, request by request against its window, and the fullest one's share beside it, toned as the tab tones it. A point's tip says "Request 2: 80K of 200K (40%)" (the tab's spark says it too now, where the window is known); a point clicked opens that request in Routing with its card. A session the gateway never saw asks nothing; one it kept no prompt of shows no line. The data is the routing history the Context tab already reads. A new GET /api/context/session?agent=&id=&from=&to= reads only the days from the session's first to its last (30 at most), through the tab's per-day cache (daysRecsLocked, split out of contextRecsLocked, so the tab's cached days are not evicted), and keeps that one session (contextOfRecsFor), with up to 1000 of its requests. The tab keeps the latest 80 sessions and would leave an older one out. Subagent and side calls are left out as the tab leaves them out; the same id under another agent is that agent's. The line's code is in plugins/usage/page.js (sessCtxLine). context.js only exports spark and health, and pays for its tip by cutting comments, so the core's scripts are 10 bytes under main's, no budget raise. Run at this head (rebased on |
||
|
|
b90e130902 |
dsh: a fork's call waiting for its reply counts on neither card, not its source's (#5542)
|
||
|
|
d052fec0e3 |
dsh: a fork without a parent gets its own row, named by its replies (#5542)
#5491 names a dsh fork's completed requests by the reply id dsh writes with them, over the conversation's opening only where the two agree: the reply's session owns the opening, or is a fork of its owner, which the fork header's parentSession says (Session.ForkOf). dsh 0.2.2's ordinary fork writes isSeeded and session/end-seed but no parentSession. ForkOf is empty, the guard refuses the reply id's own session, and the fork's requests stay under its source on Routing and Context; the fork's own row never appears (Flandern1211: 7 of 17 top-level seeded sessions on one computer are such forks). end-seed now keeps the conversation ids its copied events opened (SeedConvs) instead of dropping them with the seed's counts. That is the fork's own file saying it copied that opening, and forkedFrom accepts it when the fork names no parent, only to admit a reply id that is already one session's. A route with no reply id still goes by the opening, and a reply id two sessions share stays ambiguous. dsh's parse version rises so kept parses are read again; the Routing integration fixture leaves parentSession out, as current dsh does. Flandern1211's fix/dsh-fork-without-parent @ ead1abcce, as written; one conflict taken (parseVersions has antigravity 2 on main). ggbdpq's port on #5542 (0d7e18d1e) is the same change. Not ported: the follow-up fix/dsh-fork-unmatched @ 1bce689ed (Context page leaves a fork-shared opening's unread route out of both cards). Review findings are on #5542. Run at aca932bf7 (this change on |
||
|
|
8de63c8b5a |
gateway, usage, gui, otlp: a request its agent canceled is no failure (#2398)
An agent that cancels its request before it is answered is logged 499 "the agent canceled the request": a person stops the reply, or sends the next message while it is coming and Claude Desktop cancels it and asks again, or Codex takes a subagent's report (#2398). The gateway already says nobody failed (no rest, no reroute: TestCanceledRequestRestsNobody), but Record.Failed is a status >= 400 or an error, so every page counted it as a failure: the Requests card's "N failed" and success share, its Failed filter, the CSV's error column, the Routing page's "errors your agent saw", the Context page's error rate, the failed colour in the Requests list, Routing and Recent calls, and the OTLP export's error status. A Claude Desktop session on 2026-10-27 had four, each a message sent mid-reply; #2398 had 91 of a day's 92 failures. usage.CanceledBy tells the agent's cancel (499 with AgentCanceled) from magpie's own limit on a request it asked of itself, logged 499 too and still a failure (#2318). The cancel is logged with an error type of its own, agent_canceled (usage.CanceledErrType, set in failedWith), so the record says what it was and nothing guesses it from a 499, as #2398 asked. Record.Canceled reads the type, and a record logged before it by its status and message, so the old log reads the same with nothing migrated. A middleware's usage rows carry the type, so a module can tell the cancel from magpie's own limit, which its rows (no error text) couldn't. Record.Failed leaves the cancel out; Totals counts it apart (Canceled, in count and plus); RetriedRequest and the first-token and speed sums ask Answered, so a canceled request is timed nowhere, as before; Codex's memory of the last model still skips it. Routes and Recent calls say canceled (set as a route is done and as a day's history is read, so old days read the same); the Routing totals and the Context page's errors leave it out. Ledger rows say canceled, and the pages show it muted, in neither the failed nor the answered colour: the Requests list and its detail ("499 · canceled"), the Requests card ("N canceled", the success share of the requests not canceled), the overview tile, the Routing page (a "gone" outcome, no speed) and Recent calls (muted). New strings are in zh, zh-TW, ja and de. The OTLP export: the records the gateway gives its observers for a request and its try carry the type too (canceledAs), and a root span's error.type follows Record.Failed, so a canceled request's span and its try's go with status code 499, no error and no error.type. TestOTelWaterfallFailureAndCancellation's canceled case held two failed spans (the try the vendor refused as the agent left is recorded canceled, as the request is); it now holds neither failed, both 499 and no error.type. That change to the test is the point of this one. mdwsk88's patch (aea0027fd) ran its tests at |
||
|
|
e8df78f33e |
routing: a dsh fork's requests are named by the reply its client was given (#5491)
dsh's chat and messages routes send no session id, so Routing and Context found a dsh session by the hash of the conversation's opening. A fork repeats its source's opening, so every request the fork made showed under the source, and the fork's name never appeared. Flandern1211's patch, ported: - The gateway keeps the id of the reply it gave the client (Route.ResponseID). It is set from clientResponseID in the same update that marks the route done, so a poll that sees Done also sees the id, with no race against the usage ledger. When magpie translates, it is the id after translation, e.g. chatcmpl-…, not the upstream's msg_…. - sessions reads dsh's replayState.response.responseId into Session.ResponseIDs. Only main files are read, only replies served by the gateway, and only the fork's own replies after its session/end-seed (seedLength for version 1). - Routing (pricedRoutes) and Context (joinConvs) look up a finished request by its reply id first, then by its opening. A request logged before this keeps the opening's session. Changed from the patch: - A reply id names a session over the opening only when the opening is that session's own, or a session it was forked from, or the opening is unknown. Vendors' ids can repeat: an encoder keeps the upstream's id, and Ollama's is chatcmpl-<0..999>. Without the guard, two unrelated conversations could swap names. Session.ForkOf comes from the fork header's parentSession, isSeeded and delegationDepth 0, which is how dsh's buildForkSeed writes it. ownerOf walks that chain, so a fork of a fork works too. - Poll cost: dsh never writes down some reply ids (a title call, a refused turn). Under the patch, each such id made Routing list every session again every 2s, for as long as the route was on the page. Now an id is waited for only up to a minute (convsKept) after its request ended (looseKeys). After that the regular one-minute rebuild covers it. - A page whose loose routes carry only a reply id still builds the map (looseRoute). - The patch's synthetic fork headers gain parentSession, as dsh writes them. - docs/subsystems/gateway-routing.md describes the reply-id join. Tests: - TestDshForkNamedByTheReplyTheGatewayGave sends dsh 0.2.0-rc.2's real captured completions request (testdata/dsh-gateway) through gateway.New() twice, to an Anthropic-only upstream, so the reply is translated. It writes the source's real session file with the first client id, and a fork shaped like dsh's buildForkSeed output with the second. It then checks that pricedRoutes and contextOf put each request under its own session, and an old route without an id under the source. - TestDshForkOfARealSessionListsItsOwnReplies forks the real fixture session: the fork lists only its own reply and ForkOf, the source keeps [c1]. - TestDshReplyIDOfAnotherConversationNamesNoOne covers the guard. - TestRoutingWaitsForAReplyIDOnlyAWhile covers the poll bound. - The patch's own tests: TestDoneRouteKeepsTheClientResponseID (json and stream), TestDshResponseIDs*, TestRoutingTellsAForkByItsReply, TestContextTellsAForkByItsReply. Run on mote (mote-run), at this tree on origin/main |
||
|
|
6d9fb7ef0f |
routing: a dsh request names the dsh session its first prompt was read from
changqiu4890 on Discord: Routing -> Requests showed dsh's requests with no session id. dsh 0.2.1's pi-ai routes (openai-completions, anthropic), which magpie configures, send no session header (pi-ai's session affinity is withheld by dsh's compat gate), so a route had only its Conv, the hash of its first user message. The Context page already found dsh's session by that hash (dshConvs); the Routing page grouped by header session only. pricedRoutes now gives a dsh route with no session of its own the dsh session whose Convs hold its Conv (convOwners, shared with the Context page's joinConvs), from an index rebuilt at most every 2s when a conv is missing and every minute otherwise. Grouping and titles (dsh:<id>) follow. A route with its own session, another agent's route, and a conv two sessions share stay as they were. Run (mote-run, this tree): - go test -tags nogui ./internal/gui/ ./internal/sessions/: ok, ok - TestRoutingDshRoutesNameTheirSession and TestContext*: ok - GUI routing-sessions, routing-session-folder, routing-by-key, ctx-route, routing-day-window: Chromium 160/0, WebKit 80/0 - go vet darwin, linux (nogui), windows ./internal/gui; go build all three - gofmt -l clean Broken by hand: `r.Session = owners[k]` -> `_ = owners[k]`; the new test's dsh chat and messages routes went red. Not tried: a real dsh through magpie. A brand-new session's first request shows no session until dsh writes its session file and the index refreshes. The in-flight list (Active, concurrency endpoint) is unchanged. |
||
|
|
0872bc2a0e |
context: a request's text and reply from the request archive (wangbinyq)
wangbinyq on Discord: with the request archive on, clicking a block of
the context window card still said "只保留最近 10 个请求的原文", since the
card read only the last 10 bodies magpie keeps in memory.
What changed:
- /api/context/text tries memory first, then the request archive's copy
when the route names one (Route.Archive, the route found in the trace
or in the history file of the card's ?day=, HistoryRoute looks a day
either side). gateway.ArchivedPromptText parses it as PromptText does
and masks it through maskedCopy, as the body in memory is; it is
marked from "archive" and the card says so.
- New /api/context/reply: the reply to the request, from the Recent
calls (Server.ReplyBody) or the archive's Response. gateway.ReplyPieces
reads it into thinking/assistant/call pieces (conversationOutput, split
out of conversationTurn) after redact.ScrubJSON, and masks every piece
through maskedCopy. The card's text view has a Reply button beside
Close that shows it and goes back to the part.
- What is shown is what the archive stores, masked as the memory copy
would be, nothing more. A body or reply that can't be masked shows
nothing (404 "unread"); one the archive cut short isn't parsed ("cut");
one it names and doesn't have says so ("missing"), and one with no
archive copy keeps the old "only the last 10" line ("off"). A failed
bucket read is an error, not "gone".
- The archive read is capped at archiveReadMost and the last copy read is
kept 5 minutes, so the items opened one by one read it once.
- ctxtext.js takes the route (id and time) instead of the id; context.js
passes it (its one-line change paid for by a comment cut, core budget
not raised). New strings in zh, zh-TW, ja and de.
- docs/subsystems/gateway-routing.md (Prompt) and gui-shell.md.
Run on
|
||
|
|
6d154ef1e1 |
context: scripts (curl, Bun, python-httpx…) are one Scripts card, not an agent each
A request whose User-Agent names only an HTTP library or an SDK (curl, Bun, node-fetch, undici, python-httpx, requests, aiohttp, Go-http-client, okhttp, the OpenAI/Anthropic SDKs, …) or nothing at all got a Context scorecard of its own, as if it were an agent (theforeveriris on X: "Bun", "curl", "python-httpx" cards). usage.IsLibrary names those clients; contextOfRecs folds them and "other" into one "Scripts" card at read time, so older history reads the same way, and the card's meta line and tooltip list the libraries by count. The cached day records are not changed. No setting: it works as is. The Usage page's Agents list still shows each library by name, with its Hide and Count-as-agent controls. i18n for zh, zh-TW, ja, de. Existing context.js comments were condensed so TestCoreScriptBudget holds without a raise (core scripts -28 bytes). Run, at this head (rebased on |
||
|
|
fbeed7e7f7 |
usage: the Context tab reads each day and each session file once, not at every refresh (Yayoi_no_yume on X)
A user running magpie on a 1-core, 962 MB server opened Usage › Context.
CPU went to 100%, memory to 91%, and the server went down.
Cause: the tab asks /api/context and /api/tune at every refresh of the
Usage page (every 5s by default). Each ask:
- /api/context read up to 7 days of routing history again, as whole
gateway.Route values (prompt items, order, tries). A gzipped day not yet
counted was parsed whole, every route of it, before being cut to its
latest 2000 (gateway.History).
- /api/tune read every Claude Code and Codex session file in the range
again, whole, into []sessions.Call, then worked the advice out of all of
them.
Now:
- gateway.History counts a .gz day's lines first and then parses only its
latest historyMax+historySlack routes, as it already did for .jsonl.
- /api/context keeps each day's routes slimmed (ctxRec: the parts' tokens
without their items; the whole prompt only on the routes that can be a
session's latest), keyed by the size and mtime of the day's files. A
day is read again only when its files change. The answer is given again
while its days and the trace are unchanged, for at most a minute.
- /api/tune keeps each file's calls as tune.Call (~100 B each), keyed by
size, mtime and agent, read one file at a time through
sessions.ReadCallSource. A message copied into a resumed session is
still counted once (the earlier file owns it, as in sessions.Calls). The
advice stands for a minute, and apply or undo lets it go at once.
- tune's stable sorts use slices.SortStableFunc instead of
sort.SliceStable, which was most of the CPU over 300k calls.
Measured on mote with a generated fixture: 8 days of 20,000 routes each
(7 gzipped, built from a real 2.2 KB route), and 200 Claude Code files of
1,500 calls each (300k calls). The scratch bench was not committed. mote
was at load 130-170 from other suites, so wall times are noisy; CPU time
is from rusage and peak heap is sampled every 2 ms.
/api/context before: 1st ask 4.2s CPU, 158 MB peak heap, 202 MB RSS;
every refresh 0.63s CPU, 111-121 MB peak heap
after: 1st ask 0.84s CPU, 48-55 MB, 90-93 MB RSS;
every refresh 3-5 ms CPU, 21-34 MB
/api/tune before: 1st ask 4.3s CPU, 498 MB peak heap, 717 MB RSS;
every refresh 1.0s CPU, 370-494 MB peak heap
after: 1st ask 0.83s CPU, 373 MB, 409 MB RSS;
within a minute 0 CPU, nothing read;
after a minute with a file changed, that file is
read and the advice worked out again (~0.5s CPU)
Tests:
- TestContextReadsADayOnce: a day whose files are unchanged is not read
again; a grown day is, and only that day; each session's latest prompt
keeps its items; the kept answer equals contextOf over every route.
- TestTuneReadsAFileOnce: an unchanged file is not read again; a grown
one is; a copied message counts once; the call count matches
tuneOf(sessions.Calls(...)); within a minute nothing is read.
- TestHistoryParsesOnlyAGzDaysLatest: a 5,200-route gz day parses at
most 2,200 routes.
Broken by hand: always re-read the day, skip tune's file check, drop
History's count-first block. All three tests went red (days read 4
times, files read 5 times, 5,200 routes parsed), then green again once
restored.
Run on mote at this tree:
- gofmt -l: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows
go vet ./..., go build ./...: all ok.
- go test ./internal/gui ./internal/gateway ./internal/tune
./internal/sessions: tune and sessions ok. gui is red only on
TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27 on mote). gateway
is red only on the Antigravity turned-away tests and
TestCodexSpentGrokFailingIsTold, which are red on main (#4362). This
change touches neither.
- GUI (node --test, Chromium and WebKit): context-*.test.cjs,
compact-one-value, usage-refresh, usage-refresh-flight and
usage-stale-answer: 270 of 273 pass. The 3 reds are context-map's
"two tiles overlap" in WebKit at 420px (en, ja, de), the overlap
#3488 has under load (mote at load ~160). No .js changed, so app.js's budget is
untouched.
Not tried:
- A real 1-core, 1 GB box.
- Codex rollouts in the fixture: Codex files take the same path.
- internal/usage's codexCalls, which still uses sessions.AgentCalls
(Codex only, on the Usage identity path) and is unchanged.
- tune's first ask, and each ask after a minute with a file changed,
still works over the range's calls at once: ~30 MB kept per 300k calls,
and a few hundred MB peak while the advice is worked out. It is bounded
by the calls in the range, not by a fixed size.
|
||
|
|
3a47e377e0 |
usage: a call whose vendor counts no cache is left out of every hit rate (#3464)
#3464 (zeewell on X): Kiro caches on its side, but its replies give only credits and a context share, never cache tokens. Every hit rate outside the Routing page read those calls' CacheRead of 0 as a miss. A Kiro-heavy day showed "hit rate 6%" when the counted calls hit 90%. The plugin already says so (opencode-kiro-auth 0.1.16 sends usage.magpie_cache_unknown), and the gateway already kept it as RouteUsage.CacheUnknown for Routing. This carries it the rest of the way: - gateway: Usage.cacheNotCounted() (the vendor said so and no try reported a cache token) goes into usage.Record.CacheUnknown on every path that records a call: the gateway's own record, the OTel attempt path in observe.go, and trace's routeUsage. - usage: Record.CacheUnknown is kept as ledger row flag 8192 (rowCacheUnknown; grepped, no other flag uses that bit). Totals sums such calls' prompt into cache_unknown and counts them in cache_unknown_calls. Totals.HitRate leaves that prompt out of its denominator, and gives no rate when nothing is left. - Old records: calls kept before the plugin said so carry no flag. A Kiro call (provider kiro or kiro-plugin) with no cache counted is read as uncounted (usage.CountsNoCache): in the ledger's row read, in Totals, and for Routing's history in internal/gui/trace.go (cacheCounted). The rule is scoped to Kiro's two ids, so another vendor's 0 stays a miss (tested). - GUI: cacheHitOf in app.js drives the tray panel's card, the Usage page's agent rows and cache tile, the requests' Cache hit rate card and each ranking row. When only uncounted calls are left it shows "—" or nothing instead of 0%. Otherwise it says "{n} requests left out: their vendor doesn't count the cache". A request row's cache cells show "—", and its details say the vendor doesn't count the cache. The Context page (context.go, context.js) shows no cache for such a call and doesn't score it as a miss. - No budget raised. This adds 625 bytes to app.js (1,320,224 to 1,320,849, under its 1,321,336); |
||
|
|
83234fe920 |
gateway, gui: the skills an agent lists are their own part, not memory
The owner (10-24, on the Routing context map's "技能 / 记忆 · 9.6K"):
为什么这里又叫技能,又叫记忆?Skill 跟 Memory 应该是不一样的东西. The
gateway put Codex's <skills_instructions> in the memory part beside the
instruction files and reminders, so the tile said Skills of Memory.
Claude Code's skill list wasn't seen at all: it sat in its environment
message, counted as the system prompt.
- gateway: PartSkills ("skills") comes after tools. Codex's
<skills_instructions> goes there. So does Claude Code's list, from
"The following skills are available for use with the Skill tool:" to
the next blank line, taken out of whatever text holds it: its own
prompt, a harness message or a reminder.
- Routes kept before this (routing history) are read with an item
tagged skills moved out of memory into the skills part, so old
requests read the same way. The text view re-reads the body and finds
them under skills too.
- Usage's context baseline counts skills, as it did inside memory.
memory-heavy is now instruction files and reminders alone.
- gui: the card has a Skills part (slate, --c7), with its note in en,
zh, zh-TW, ja and de. The text view's "no longer kept" line is one
helper instead of two copies of the sentence, which makes the room for
it under the core script budget, with no room added.
Run (darwin):
- go test ./internal/gateway -run 'Text|Prompt|Context|History|Skill|Route'
ok; go test ./internal/gui ok; go vet both, gofmt clean.
- New: TestPromptOfClaudeCodeSkills (on testdata/workdir's real Claude
Code 2.1.296 body: 1502 tokens of skills out of the 2130-token
environment item), TestSplitSkillsEnds, TestSkillsApartOfKeptPrompt.
Broken by hand (splitSkills and skillsApart made no-ops): all three
red.
- GUI, chromium and webkit: context-map 22/22 (new: the skills tile's
tip names Skills and not Memory in every language, and it isn't
memory's colour), context-window 24/24, context-text 20/20,
context-scroll-end 14/14, routing-context-fold 24/24,
routing-ctx-still 16/16, i18n-keys 4/4.
Not run: the whole GUI suite (load ~400 on the box); a live Codex or
Claude Code request through the real app.
Not changed: the "system prompt, tools and memory" wording of the
baseline's tags, which now count skills too.
|
||
|
|
9572a35761 |
usage: dsh sessions in Context go by their titles (Kumo31 on Discord)
Usage -> Context listed DeepSeek Harness sessions as "magpie-a",
"magpie-f" and so on, while Usage -> Sessions showed their titles. Real
dsh 0.2.0-rc.2 sends no session header on its chat-completions and
messages routes. The gateway therefore keys each request by
conversationID, a hash of the first user message. contextOf joined
titles on agent + session id, and a hash never matches a dsh session
id. The responses route sends session_id and was already joined.
- The dsh reader (sessions) records the ids the gateway gives a
session's requests: the first typed user/message and the
session/title-llm-request message. Each is hashed in the forms dsh
sends it: a string, and a text part with or without a cache mark.
The text goes through a JSON.stringify-compatible encoder (jsString),
because encoding/json escapes <, > and &. These ids are
Session.Convs; cacheVersion goes to 22.
- contextOf (joinConvs) puts a route that names no session under the
session its conv id came from. An id two sessions share is left as
it is. The title call merges in and is skipped as a tool-less side
call. The existing title join then finds the session.
Fixture: internal/sessions/testdata/dsh-gateway holds two real dsh
session files and the four requests that dsh sent for them to a fake
upstream: a turn and a title call on each of the completions and
messages routes, headers and body as captured. Only the cwd is
rewritten to /work/proj.
Siblings: other agents that send no session header have the same gap,
but none was run to see what it sends. Filed as #3263.
Run at bc11b8a5f (on origin/main
|
||
|
|
0eb5cbe81a |
routing: the live view and Usage's Requested name a found group auto/<model>, not group/auto-<model> (未寒 on Discord)
Reported: 未寒 picked auto/claude-opus-5-5, and the Routing live view and
Usage's Requested column named it group/auto-claude-opus-5-5, an internal
id that agents never see.
Changed:
- internal/gateway/trace.go: GroupRef and SubGroup carry Ref
(Group.Ref(), the id agents pick the group by).
- internal/gui/trace.go: publicRoute rewrites a route's Model,
For.Model, Subagent.Asked/To and the group's and subs' Ref through
provider.PublicRef (memoised per answer). It copies the pointers
before writing, so the gateway's trace is left as it was.
- internal/gui/context.go: the Context page's model too.
- internal/usageapi/usageapi.go: the ledger page's Requested.
- routing/client.js: useName falls back to a sub's ref.
Test: TestRoutesNameFoundGroupsByTheirPublicID
(internal/gui/trace_publicref_test.go). Broken by hand, each one red:
- publicRoute made a no-op: red on model, group, subagent, For, Subs
and route.
- usageapi mapping removed: `the ledger's Requested:
["group/auto-claude-opus-5-5" "group/mine"]`.
- contextRoutes mapping removed: `the Context page's model:
"group/auto-claude-opus-5-5:high"`.
- Ref dropped from gateway/trace.go alone stays green, as expected:
publicRoute fills an empty Ref.
Not covered: the ledger's text search (usage.Filter.Query) still matches
the stored group/auto-… form, not the shown auto/… (package usage can't
import provider). client.js's ref fallback has no GUI test of its own.
Run, go1.26.8 darwin/arm64, sandbox HOME, private GOCACHE:
At this stack on origin/main
|
||
|
|
e98440ae6b |
gui, gateway: auto mode's classifier and other side calls in a Claude Code session are no compaction on the Context tab (Player on Discord)
Player (magpie 0.1.1234 in docker, Claude Code in auto mode on glm-5.3)
saw "137 requests · 45 compactions" on Usage → Context for a session
that never compacted (peak ~116K of 1M). Claude Code's auto mode
classifier ("You are a security monitor…", a transcript, no tools,
34–48K) goes under the conversation's own session id, so every one
after a 60–115K turn passed compacted()'s 60% drop. Title, quota
check and a subagent's turns share the id too, and the latest one of
any of them became the session's "latest request".
contextOf now keeps a session's line to its own turns:
- in a session whose turns carry tool definitions, a request without
any is a side call (classifier, title, quota check) and is left out
of the session and the agent's stats, as a Kind'd call already was
(toolSessions, read from the routes on disk, so existing history
reads right too);
- a Claude Code subagent's request is left out of the session's line
(still in the agent's stats). The route now records it: Route.Sub,
from x-claude-code-agent-id (subagentOf), set in serve's beginFor.
An agent that sends no tools at all keeps every request.
Tests:
- TestContextSideCallsAreNoCompaction: an interleaved session like the
reporter's (title, quota check, 7 turns 60K→120K each followed by two
classifier calls 34–48K, two subagent turns, then a real compaction
120K→33K). On origin/main's context.go it fails "compactions: session
10 agent 10, want the one real one"; with only the subagent check
removed it fails with 2. Passes now: 1 compaction, 10 points, latest
is the last turn, peak 120K, baseline 24K.
- TestContextToollessAgentKeepsItsTurns: a no-tools chat app's 70K→20K
still counts.
- TestRouteSaysItsSubagent (gateway, through Handler with a fake
upstream): fails "map[:2]" without the gateway line, passes with it.
Run at this head (go1.26.8, darwin): gofmt -l clean; go vet ./...,
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...; go build,
GOOS=linux go build -tags nogui, GOOS=windows go build; go test -tags
nogui -count=1 ./... under a scratchpad HOME with caches pinned. With the
machine at load ~180-260 the first full run timed out (10m default) in
agent, gateway, library, plugin and provider with no test FAIL; those
five were rerun with -p 2 -timeout 45m and all passed. Everything else
passed in the full run. No GUI asset changed (context.js reads the same
JSON), so the Playwright suite wasn't run. Not tried against the
reporter's own usage.jsonl or a live Claude Code auto-mode session.
|
||
|
|
cdb7b5ff7e |
sessions: a PI-Desktop chat goes by the title PI-Desktop gave it, not its id (#1967)
PI-Desktop (vastsa/PI-Desktop) sends its chats through magpie with
X-Magpie-Session set to its own session id. Those are gateway sessions
with no file magpie reads, so Sessions and the context page listed them
by id. PI-Desktop keeps the name only in its index database, pi.sqlite's
sessions table (id, title, deleted_at).
PIDesktopTitles reads that table from $PI_DESKTOP_DATA_DIR or
~/.pi-desktop. It opens the database only through openCursorStore:
immutable when there is no write-ahead log, or from a temp copy when
there is one (a running PI-Desktop keeps one). It is re-read when the
database or its log changes, at most once a second. Deleted and untitled
rows are skipped. A database that can't be read leaves the names last
read standing. MergeExternal, MergeExternalStats and the GUI's context
page use it for sessions attributed to pi-desktop (
|
||
|
|
067f39f406 |
sessions: Desktop titles read once per second, from every handle Desktop keeps, and reach stats and Context (#1675)
Follow-up to Koohoko's 3d6f8b8e, after review. - Cost: assemble asks DesktopTitles once per native Claude Desktop session, and each call globbed and stat'ed every local_*.json, so a list of N Cowork sessions looked at the metadata N times. The names are now one index, rebuilt at most once a second (desktopTitlesHeld); a rename in Desktop shows within that second. Files are read through filememo, the shared reader the usage resolver already uses for these same files, which also catches a same-size rewrite inside one mtime tick (the patch's own size+mtime cache didn't). - A record that is there but doesn't parse (Desktop midway through a write) keeps its last parse instead of dropping to the bare id; a record gone still takes its names with it. - Handles: Claude.app 2.7032's LocalSessionManager (app.asar, read-only) counts unarchivedCliSessionId as a live handle beside cliSessionId and preClearCliSessionId as lineage beside priorCliSessionIds, and runs a record with no cliSessionId under its sessionId without "local_". All are named now; the raw "local_..." id no longer is (no usage record carries it). - Siblings: MergeExternalStats (the Sessions page's stats summaries) and the Context page named gateway-only Desktop sessions by the recorded prompt or nothing; both use the Desktop name now. - docs/subsystems/gateway-sessions.md says all of the above. Real layout: no Desktop session records exist on this Mac or the Windows box (only claude_desktop_config.json), so field names and types were checked against Claude.app 2.7032's own reader/writer code: a string title, string cliSessionId/unarchivedCliSessionId/ preClearCliSessionId, an array priorCliSessionIds, files <account>/<org>/local_*.json under claude-code-sessions and local-agent-mode-sessions. Dirs come from desktopdir.Everywhere, the resolver the other Desktop session readers use (Windows %APPDATA% and MSIX LocalCache, Linux ~/.config); Windows/Linux not run. Run: new tests TestDesktopSessionTitleHandles, TestDesktopSessionTitleInStats, TestDesktopTitlesReadOncePerList, and context checks in TestDesktopSessionTitlesOnPages. Each broken by hand went red: rescan per call -> "metadata looked at 12 times, want once"; no last-good -> "a half-written file lost its names"; no unarchived/stem -> missing ids; stats without the name -> "stats titles map[cli-s:Recorded prompt ...]"; Context without it -> "context titles map[...: ...]". go test -race -count=20 -run TestDesktop ./internal/sessions; go test -tags nogui ./... (sandbox HOME, pinned caches): all ok but internal/plugin's TestPiPackage (pi-codemode export missing; passes alone, doesn't import sessions or gui), filed as #1879; gofmt -l; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...; go build, GOOS=linux go build -tags nogui, GOOS=windows go build. GUI: routing-sessions, session-identity, sessions-overview, sessions-bar-names, sessions-gateway-delete, sessions-manage, context-window in Chromium and WebKit (84/84 each). Real binary: magpie web under a sandbox HOME with Claude-3p Code and Claude Cowork fixture records and five claude-desktop usage records; the Sessions page (Chromium, WebKit) showed both titles on current, prior and unarchived ids and the bare id on the unmatched one; /api/gateway/session-titles named them; a rename showed after 1.3s; a half-written file kept the name; deleting the record went back to the id. Co-authored-by: Koohoko <koohoko@gmail.com> |
||
|
|
a98ab77fde |
gui, gateway: a context window's part, cell or item clicked opens the text the request sent there (masaka)
masaka on Discord asked to see the whole context behind the context window
card: click the agent's prompt, or any other part, and read it.
What changed:
- gateway: the trace keeps the last 10 request bodies in memory only
(promptBodies; at most 32 MiB each and 64 MiB together, oldest dropped
first), masked as the vendor got them. For a model the user let have
the request unmasked, the masked copy is kept all the same. Never
written to disk, never in telemetry. Route.Prompt and the routing
history keep names and sizes only, as before.
- gateway: Server.PromptText re-reads a part's items and their text from
that body (prompt_text.go). promptBuilder gains a keep mode that records
each item's pieces: system text, tool definitions laid out as JSON, each
turn's user/thinking/assistant/call pieces, tool results, and images
or sealed reasoning named with their size. Sizes are unchanged.
- gui: GET /api/context/text?id=&kind=[&item=] (no-store; 404 "not kept"
when the body is gone or another process serves the gateway).
- gui: in the card, a legend part, a waffle cell or a content row
(click, Enter or Space) opens a wide modal: one item alone with "All of
{part}", or the part's list 100 rows at a time, each item's text
fetched when it is opened and shown 20000 characters at a time, with
copy buttons. Strings in zh, zh-TW, ja and de.
- docs: gateway-routing and gui-shell subsystem pages; the site's start
page (en, zh, ja) says the text is kept for the last 10 requests in
memory and sent nowhere. The README Privacy is unchanged, since nothing
more is sent.
What was run:
- go test -tags nogui ./... (temp HOME). internal/gateway hit the 10m
default under the full parallel run, in TestRequestTailAfterOldLimit,
which takes 57s alone on the base commit too; the package run alone
with -timeout 30m: ok (700s, the machine shared with other runs). Every other package: ok.
- New tests TestPromptTextIsWhatWasSent, ...KeepsOnlyTheLastBodies,
...ChatPieces, TestContextTextAPI. Broken by hand: keeping the unmasked
body fails (the key shows), and dropping keepBody fails ("not kept").
- gofmt -l; go vet, GOOS=linux and GOOS=windows go vet on internal/gateway
and internal/gui.
- GUI: tests/context-text.test.cjs in Chromium and WebKit, en/zh/zh-TW/
ja/de, at 1100 and 420px: legend, row, cell and keyboard open the text,
long text grows on demand, the page never scrolls, and a gone body is
named. It fails with the click wiring removed. Under a load average of
~140 one case failed once: the test read the list while the dialog
still said "Reading…". Reproduced with a 400ms reply, fixed by waiting
for the list; the mock now always answers after 200ms. A second case
("a click doesn't move the page", 662 vs 605 on the contents row) came
from taking the page's top while a wheel scroll was still easing: the
test now wheels to the row like the other cases, and wheelTo waits for
three equal looks. Four full runs at load ~150 then passed (80 cases). context-window,
i18n-keys, held-animations and the modal tests (dialog-backdrop-drag,
editor-short-window, readable-focus, ux-safety, whats-new, add-sheet,
api-key-theme) pass in both engines.
- Real use: a sandbox magpie (own HOME, ports 3486/3487, the Codex login)
served a real `claude -p` (Claude Code) request on codex/gpt-6-luna
that read a file. In its web UI, Usage > Context: each of System
prompt, Tools, Memory, Files and Conversation, a waffle cell and a
contents row opened the request's real text (Claude Code's system
prompt, 21 tool definitions, the CLAUDE.md reminder, main.go's Read
result, the turn with its thinking and call). No page errors.
|
||
|
|
586f2bce8f |
context: magpie inspects the context window of every request, session and agent
The gateway reads each request's prompt into its parts (system prompt, tools and MCP servers, memory, files, tool results, chat), measured against the model's window and calibrated to the tokens the vendor counted. Routing shows a request's window as a card: a 400-cell grid by part, a hover naming what is largest in a cell, and the contents by part. The Usage page's Context tab scores each agent out of 100 (cache reuse, how lean it starts, how fast it grows, how reliably it answers), tags it (lean, cache-friendly, mcp-heavy, compacts, near-full…), and draws each session's growth with its latest request's card. Older Safari (15) gets media-query and solid-colour fallbacks for the card's container queries and color-mix. |