Commit Graph
19 Commits
Author SHA1 Message Date
yetoneandFlandern1211 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
ec7a18d12, which changes GUI strings and .cjs tests only, no Go):
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/
  ./internal/gateway/ ./internal/agent/: ok (sessions 30s, gui 158s,
  gateway 952s, agent 262s).
- CGO_ENABLED=0 GOOS=linux and GOOS=windows go vet -tags nogui of the
  three packages: clean; gofmt -l internal: clean.
- No GUI asset changed, so no .cjs run.

Broken by hand, each red: LastConvs not set in serve
(TestDshRoutesCarryTheSessionConvs on the real captured requests), no
turn/start reset, no cap, no guard on the turn lookup, no looseKeys
bound, no LastConvs keys in looseKeys (end-to-end Routing test stays on
the source), no strip of the page's routes, no tool_result skip, no
strip in saveRoute.

Not tried: a real dsh fork live (no dsh session files on this Mac or
mote); the contributor measured their version on magpie web.

Co-authored-by: Flandern1211 <163982805+Flandern1211@users.noreply.github.com>
2026-11-08 22:25:58 +08:00
yetone 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 e215d335a), on WSL (magpie-desktop, Linux;
mote rebooted mid-run):
- gofmt -l clean; go test -tags nogui -run
  'TestContextSessionLine|TestCoreScriptBudget|TestContext' ./internal/gui/: ok
  (also ok on mote at this head).
- node --test sessions-context-line (new: Chromium and WebKit, en zh zh-TW
  ja de, 1100 and 420 wide) and context-window: 44 of 44.
Run on mote before the rebase, at 627fd1a3b:
- the whole internal/gui package: its one red, TestCoreScriptBudget
  (1,536,110 > 1,533,802), is why the line moved into the plugin.
- sessions-context-line: 20 of 20.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- i18n-keys: "a plugin's words are its own" red, the same on origin/main
  e215d335a (#5327, #5332, #5426, #5482); the new strings pass its other
  checks.

Broken by hand:
- the one-session filter dropped: TestContextSessionLine red ("its
  requests' prompts: [21000]", another session's line).
- the tip back to "Request {n}: {tokens} tokens": sessions-context-line red
  in de ("Anfrage 2: 80K Token" for "Anfrage 2: 80K von 200K (40%)").
- the details line turned off: sessions-context-line red in en and zh.

Not tried: the whole GUI suite (it was running under mote's suite lock
when mote rebooted; not run at push); a real magpie with real routing history (the GUI test stubs
/api/context/session; the Go test reads real history files in a sandbox
config); the Linux app's WebKitGTK.

Reported-by: liang_yongxiang (Discord)
2026-11-08 18:13:30 +08:00
yetoneandFlandern1211 b90e130902 dsh: a fork's call waiting for its reply counts on neither card, not its source's (#5542)
d052fec0e gave a dsh fork without a parentSession its own row, named by
the reply ids it gets. A call whose reply dsh hasn't written down yet
still went by the opening, which the fork copied and only the source
owns, so the source's context line climbed with the fork's turns
(Flandern1211: the source's card showed the fork's 30,778 while its own
last call was 21,944).

routeOwners keeps each opening a fork's seed carried a second time
(ownerCopied). joinConvs leaves a call that names no session out of both
cards (ctxRec.Unmatched) only when its opening is such a shared one, it
has a reply id, and it ended within convsKept: the window Routing's
looseKeys waits in. A call with no reply id (routes from before
e8df78f33, a dsh that writes none) and one past that window go by their
opening as before, so the source keeps its history. An answer that left
a call out stands ctxWhileUnmatched (5s) instead of ctxAgain's minute,
and only while such a call is inside that window. This answers both
review points on 1bce689ed.

Ported from Flandern1211's ad461f7d4, with these changes:
- ctxRec.End time.Time is now Millis int64. The tab keeps one ctxRec
  per route in the range (up to 30 days); End took it from 240 to 264
  bytes, Millis to 248.
- The conflict with #2398's Canceled is resolved by keeping both.
- TestDshForkRouteAwaitingItsReplyIsNeithers also has a long call
  (begun 2m ago, ended 20s ago), and clears Session as well as
  Unmatched before its second join.
- New TestContextHeldAnswerStandsOnlyWhileAReplyIsAwaited covers
  contextFor's cache: an answer without held stands past 6s, one with
  held does not, one with held stands for 1s.

Run (mote, HOME=$(mktemp -d), -tags nogui):
- go test -run 'Dsh|Fork|Routing|Context|Conv' ./internal/gui/, and
  -run 'Dsh|ResponseID' ./internal/gateway/ ./internal/sessions/: ok.
- go test -count=1 ./internal/gui/ ./internal/sessions/: ok (117s, 60s).
- go vet ./internal/gui/ for darwin, linux and windows; gofmt -l: clean.
- node --test internal/gui/tests/context-*.test.cjs and
  compact-one-value.test.cjs (11 files): 474 of 474 pass. No GUI file
  changed; they guard the Context page it draws.
- Benchmark (temporary, not committed), 300k dsh routes over 2000
  sources and 2000 forks: joinConvs 125-135ms per pass with the change,
  140-270ms without; contextOfRecs 130-145ms with, 140-150ms without;
  allocations the same (108MB per pass). mote was at load ~120.

Broken by hand, each red: the age check, the reply-id check, the
Unmatched skip (phantom magpie-… row), held never set, held not
shortening the cache, Millis ignored, sharedOpening always false.

Not tried: a real dsh fork on this side. Flandern1211 measured the pair
on their computer: the source kept its 8 pre-#5491 calls, and a second
/api/context 6s later took 9ms instead of 575ms. Not changed: Routing
still goes by the opening for such a call (its looseKeys retries every
2s), and a fork call whose reply never comes goes back to the source
after a minute.

Reported-by: Flandern1211
Co-authored-by: Flandern1211 <163982805+Flandern1211@users.noreply.github.com>
2026-11-07 20:10:28 +08:00
Flandern1211 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 5c5160c94), on mote; the pushed head
adds only e20517a88 under it, a one-line Qoder mover min:
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./..., go build ./..., GOOS=linux go build -tags nogui ./...,
  GOOS=windows go build ./...: all ok.
- go test -tags nogui -count=1 ./internal/sessions/ ./internal/gui/
  ./internal/gateway/: ok (18.8s, 82.8s, 783.9s).
- gofmt -l on the six files: nothing.

Broken by hand (mote, -run 'Dsh|Fork|Routing|Context'):
- end-seed dropping SeedConvs: TestDshForkWithoutAParentKeepsItsSeedOpenings
  red ("seed openings [], want [magpie-e2f7b8e6… …]") and
  TestRoutingTellsAForkByItsReply red ("route 1: session
  \"session-source\", want \"session-fork\"").
- forkedFrom ignoring the seed: TestDshForkWithoutAParentIsNamedByItsReply
  red ("reply \"chatcmpl-fork\", opening \"magpie-open\": \"source\",
  want \"fork\"") and TestRoutingTellsAForkByItsReply red.
- assembleListed not carrying SeedConvs onto the Session:
  TestRoutingTellsAForkByItsReply red.
- Review check: the source's routes from before reply ids were kept (no
  ResponseID) still make the source's Context card, 3 of 3 requests.

Not tried: a replay of real dsh session files (the reporter's numbers
are on #5542; ~/.dsh here is a live config and was not read); dsh's
parse version bump is not pinned by a test of its own (the generic
re-read on a raise is, in cache_decode_test.go).

Reported-by: Flandern1211
Co-authored-by: Flandern1211 <163982805+Flandern1211@users.noreply.github.com>
2026-11-07 13:54:24 +08:00
yetoneandmdwsk88 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 e056779a, a3768cdd,
c86fa2a3 and fcc0daa2, broke each check by hand (each red), and sent
real Claude Desktop cancels through a nogui build with a stand-in
upstream and OTLP collector. Its full record is on aea0027fd. Since
58541e5b (#4866) Codex's own-sign-in relay logs Codex gone mid-reply as
499 through canceled() too, so it counts as canceled
(TestCodexGoneMidReplyIsNoFailure). drawing_route.go still reads a
canceled request as not served when it decides whether a picture's
next request may stay on its provider: that is routing, not a count.

Ported to origin/main 400b66ec3 on 2026-11-07, reviewed line by line.
Two siblings it left on the old rule, and a colour, now covered:
- usage.Row.Floor (the Claude Code speed floor) asked !Failed, so a
  canceled row, whose Failed is now false, told a floor: "3000 tokens
  in 4000 ms" for a reply no one waited for. It asks Answered now, as
  the speed and first-token sums do. TestAgentCanceledTellsNoFloor.
- The route-events feed (activityOf, #3387) told a canceled try and
  done route as failed. It leaves usage.CanceledBy out, and still
  counts magpie's own 499 limit. TestRouteEventsCanceledIsNoFailure.
- routing.css: a canceled Routing row ("rt-req gone") had the
  answered green dot. Its dot is muted now.
  routing-canceled-row.test.cjs checks the row, its dot and the errors
  stat in Chromium and WebKit, in en, zh, zh-TW, ja and de.

Run at this tree (mote-run, macOS):
- go test -count=1 internal/usage, usageapi, otlp, settings,
  settingsapi and cli: ok. internal/gateway: ok with -timeout 45m
  (847s; the default 10m ran out under load). internal/gui: ok but
  TestMainWindowCorners/macOS_26_SDK (#3949, mote is on macOS 27).
- Broken by hand: Floor on Failed again makes
  TestAgentCanceledTellsNoFloor fail ("a canceled row tells a speed
  floor: 3000 tokens in 4000 ms"). activityOf without CanceledBy makes
  TestRouteEventsCanceledIsNoFailure fail ("a done route its agent
  canceled is told failed"). Restored, both pass.
- GUI: node --test --test-concurrency=4 over routing-*, usage-*,
  ledger-*, panel-*, call-*, search-*, searcher-*, settings-*, i18n-*
  and gui-* (Chromium and WebKit; the files cover en, zh, zh-TW, ja
  and de), with #2398 and #5545 in one tree: 4961 of 5016 ok. The 55
  reds are in 12 files. i18n-keys' "a plugin's words are its own"
  names other files' strings (#5327, #5426, #5482). The other 11 files
  were run alone at dc49feca9 (this tree without either change) and at
  this tree: 52 and 51 reds, the same tests. The one apart is
  usage-focus-steady, which flakes (#3501). Each is filed: #5392,
  #3414, #5048, #3799, #3415, #3954, #4627, #4628, #5223, #1529.
  routing-canceled-row.test.cjs: 10 of 10. With the .rt-req.gone rule
  taken out, its dot is the answered green rgb(24, 154, 88) and it
  fails. Restored, it passes.
- Not tried: a real Claude Desktop cancel through this tree; Windows
  and Linux runs.

Co-authored-by: mdwsk88 <11055210+mdwsk88@users.noreply.github.com>
Reported-by: mdwsk88 (dawei on Discord)
2026-11-07 04:03:01 +08:00
yetoneandFlandern1211 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 be5e8f29f. The vet and
go test lines below were run again after rebasing on e6b9d1199, which
changed only the README and library (ok):
- gofmt -l internal/ printed nothing.
- go vet ./internal/... . is clean.
- GOOS=linux go vet -tags nogui and GOOS=windows go vet of
  internal/{sessions,gui,gateway} are ok.
- go test ./internal/sessions ./internal/gateway ./internal/gui -run
  'Dsh|ResponseID|Fork|Routing|Context|Conv' -count=1: ok.
- GUI: routing-by-key, routing-ctx-sessions, routing-request-metrics,
  routing-sessions, routing-session-folder, sessions-empty-range,
  ctx-route, context-map and panel-routing pass in chromium (120/120)
  and webkit (120/120).

Broken by hand, each red, then restored:
- guard off: TestDshReplyIDOfAnotherConversationNamesNoOne;
- poll bound off: TestRoutingWaitsForAReplyIDOnlyAWhile;
- end-seed keeps the inherited reply ids: TestDshResponseIDsSkipTheSeed,
  TestDshResponseIDsEndSeedAcrossReads and
  TestDshForkOfARealSessionListsItsOwnReplies;
- ForkOf not set: TestDshForkOfARealSessionListsItsOwnReplies,
  TestDshForkNamedByTheReplyTheGatewayGave,
  TestRoutingTellsAForkByItsReply and TestContextTellsAForkByItsReply;
- gateway keeps no id: TestDoneRouteKeepsTheClientResponseID and
  TestDshForkNamedByTheReplyTheGatewayGave.

Not tried:
- a real dsh fork against a running magpie. The session shapes come from
  the real rc.2 fixture and dsh's fork source.
- A request still running, or a failed one, still shows under the source
  until it has a reply id. The patch says the same.
- Delegated subagent files (delegationDepth > 0) are not read for reply
  ids; they stay under their parent as before.
- Not changed: the gateway's turn clock (sessionTurnKey) also falls back
  to the opening's hash, so a fork and its source running at once share
  one. Filed as #5496.

The full suite runs after the push.

Co-authored-by: Flandern1211 <163982805+Flandern1211@users.noreply.github.com>
Reported-by: flandern1211_58540 (Discord)
2026-11-06 17:22:52 +08:00
yetone 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.
2026-11-05 17:25:26 +08:00
yetone 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 f3335dd1b (main has since d73f2254d, textcalls_anthropic.go and
its test only, none of these files), on mote (macOS 27):
- go test -run 'TestArchivedPromptText|TestReplyPieces|TestPromptText|
  TestConversation|TestContext|TestCoreScriptBudget' ./internal/gateway
  ./internal/gui: ok.
- Whole ./internal/gui and ./internal/gateway (before the last rebase,
  same change): ok except TestMainWindowCorners/macOS_26_SDK (#3949) and
  TestCodexPoolSaysTheClientsVersion (#4807, fixed on main by 17f2387e1
  since).
- GOOS=linux go vet -tags nogui and GOOS=windows go vet of both: ok;
  gofmt -l clean.
- GUI, both engines, every language, 1100 and 420 wide: every file that
  reaches the context card (context-text, context-map, context-window,
  context-map-live, context-scroll-end, context-scripts, context-tune,
  ctx-route, compact-one-value, routing-ctx-*, routing-context-fold,
  routing-live-patch, routing-return-cost) plus i18n-keys: 514 of 518.
  The 4 reds are context-map's webkit 420px "two tiles overlap", red the
  same on origin/main f3335dd1b run alone (5 of 10 webkit there), #3488.
- The whole GUI suite is running on the Linux box (wsl-run) as this is
  pushed; mote had another session's full suite on it.

Broken by hand (each went red):
- maskReplyPieces skipped: TestReplyPiecesAreMasked (phone unmasked).
- ArchivedPromptText's masking skipped: TestArchivedPromptTextIsMasked
  and TestContextTextFromTheArchive (phone in the 200 body).
- ctxtext.js's "missing" reason dropped: context-text.test.cjs, 10 of 10
  chromium.

Not tried: a real archived request in the running app, the bucket
(WebDAV) archive with a real server, and a reply cut short by the
archive's size in a real call.
2026-11-03 13:34:35 +08:00
yetone 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 40af66027):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  (mote) for usage and gui; earlier the whole tree on all three, exit 0.
- mote: go test -count=1 -tags nogui -timeout 45m ./internal/usage
  ./internal/gui: ok, ok.
- Windows box: context-scripts + i18n-keys 26/26 (chromium, webkit,
  5 languages, 360 and 1100px). Before the rebase, every reachable file
  (context-*, compact-one-value, group-context, routing-context-fold,
  routing-ctx-fold, routing-ctx-still, i18n-keys, gui-de/ja/zh-tw,
  header-relang): 333/349; the 16 reds are routing-ctx-still, red the
  same on origin/main 40af66027 on that box, listed in #4124.
Broken by hand: IsLibrary false and no fold -> TestIsLibrary and
TestContextScriptsAreOneCard red (cards python-httpx, claude, Bun, ...);
the JS label/clients removed -> context-scripts.test.cjs 0/22.
Not tried: a real app run with real curl/Bun traffic; Linux WebKitGTK;
GUI files on mote (its browsers were busy with another suite).
2026-10-30 16:05:58 +08:00
yetone 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.
2026-10-30 13:23:19 +08:00
yetone 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); d08b6118b had already moved the
  masking page's maskWho, maskProv and stillMotion out to
  plugins/redact, which an earlier version of this change did too.
- Strings in zh, zh-TW, ja and de. docs/subsystems/provider-plugins.md
  now describes the ledger side and what is not covered.

Not covered, filed: hit rates read from the agents' own session files
(the TUI and CLI session lists, the Sessions tab's totals) still count
Kiro's 0 as a miss (#3470). Found on the way: System One's calls are
recorded without their cache tokens (#3471).

Run at this tree (on origin/main e57e78563, fetched just before; the
54-file GUI run was at a84d2ec80, and the 14 files that main's
redact page change since could reach were run again here):
- gofmt -l . prints nothing. go build ./... ok. go vet ./... ok,
  GOOS=linux go vet -tags nogui ./... ok, GOOS=windows go vet ./... ok.
- go test -count=1 -timeout 45m ./internal/usage ./internal/gui
  ./internal/gateway: all ok (gateway 388s), TestCoreScriptBudget
  included.
- GUI, 54 files (ledger-*, panel-*, i18n-*, context-*, request*,
  usage-card*, usage-ledger and the masking/redact files),
  concurrency 2: WebKit 439/452, Chromium 444/457. The new
  ledger-cache-unknown test passed in both. Again here (ledger-*,
  masking-*, redact-*, mask-*, usage-ledger): WebKit 104/117,
  Chromium 109/122, the same reds. The reds, both already
  red alone on main before this change:
  - redact-words-any-case, 10/10 in each engine (#3500)
  - usage-ledger "newest live route needs no return-to-live button",
    en and zh in each engine (#3104)
- At earlier bases, with the same change: usage-agents-hide (#3414),
  usage-checkin's WebKit Qoder tab (#3091), usage-fold (#3415),
  usage-focus-steady (#3501) were red, each red alone on main too;
  usage-card-refresh read a row before it was laid out, under load
  (#3509); context-picks (#3483) and
  context-map's tile overlap (#3488) in Chromium. Filed while doing
  this: TestUsageReadAfterAppendHashesNothingOnAFineClock goes red
  about 1 in 20 on main aa3112f4e (#3511); it passed in this run.
- Red on the old code: the new Go tests in usage, gateway and gui, and
  ledger-cache-unknown.test.cjs (the old page shows "hit rate 6%"
  where this shows 90%). Each changed piece was broken by hand and
  turned a test red. The exception is the OTel attempt path in
  observe.go, which no test reaches.

Not tried: a real Kiro account through the GUI.
2026-10-25 01:23:42 +08:00
yetone 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.
2026-10-24 21:03:52 +08:00
yetone 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 ccbc72781):
- gofmt -l: clean.
- go vet: darwin, GOOS=linux -tags nogui and GOOS=windows ./...: clean.
- set -o pipefail; go test -timeout 45m ./... | tee: exit 0, every
  package ok.
- No GUI or page files changed, so the GUI suite was not run.

Broken by hand:
- joinConvs commented out: TestContextDshSessionTitles red, the
  sessions keyed magpie-950998..., magpie-3dc586... and so on, with no
  titles.
- json.Marshal in place of jsString: TestDshSessionConvsAreTheGatewayIDs
  red on all four requests.
- title-llm-request not collected: that test red on both title calls.

New tests:
- TestDshRoutesCarryTheSessionConvs sends the captured requests
  through the gateway's handler and finds each route's Conv among its
  session's Convs.
- On the old code the tests don't build, because Convs doesn't exist.

Not tried:
- a masked first prompt (the hash is taken after masking, so the
  session stays untitled);
- a first prompt with an image or several parts;
- dsh's subagent files and forks (seeded sessions);
- a conv after compaction;
- the DSH desktop app;
- Kumo31's own history. Old routes keep their Conv, so they should
  join on the next read, but that was not seen.
2026-10-22 19:03:32 +08:00
yetone 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 df6bd3efe (head 48522d851):
    gofmt -l: nothing
    go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
      GOOS=windows go vet ./...: ok
    set -o pipefail; go test -timeout 45m ./...: ok, EXIT=0
      (68 ok, 19 with no test files; agent 528s, gateway 628s,
      library 482s)
    GUI, playwright 1.62.0, chromium and webkit, concurrency 3: the
      171 files near this change (routing*, panel-routing*,
      window-mask, privacy*, usage*, quota*, providers*): 2217 tests,
      2183 pass, 34 fail. Every red is also red alone on origin/main:
      quota-count-wrap and quota-name-translated (#2228),
      usage-agents-hide (#2276), usage-checkin (#3091), usage-fold
      (#2163), usage-ledger (#3104, red since df6bd3efe, green at its
      parent). window-mask: 20 of 20.
  At this stack on origin/main c922225f1 (head 91baa7adb), before
  df6bd3efe's routing trace change:
    set -o pipefail; go test -timeout 45m ./...: ok, EXIT=0
      (66 ok, 20 with no test files)
    the whole GUI suite (823 files, both engines, concurrency 3):
      11589 tests, 11554 pass, 35 fail. The 9 files red were run again
      alone at --test-concurrency=1 on the head and on origin/main
      a8ecf4020. The same 7 files were red on both: the five issues
      above plus s3-sync (#2448) and library-row-remove (#3099).
      nav-sub-unroll (#1950) and plugin-updates (#3103) were red only
      under the full run. codex-predictions (#2624) was 20 of 20.
2026-10-21 08:40:49 +08:00
yetone 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.
2026-10-15 00:17:23 +08:00
yetone 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 (aec6908c6) or pi,
which PI-Desktop was counted as before.

Run:
- TestPIDesktopTitlesNameGatewaySessions builds pi.sqlite with
  PI-Desktop's schema in WAL mode with checkpoints off. It checks that
  pi and pi-desktop sessions get the title, a claude session with the
  same id doesn't, deleted and untitled rows don't, a rename shows up on
  the next read, and the folder's files are unchanged.
- Broken by hand: isPIDesktop returning false made it red (titles
  stayed the id), and so did dropping `deleted_at IS NULL` (the deleted
  row got its title).
- go test -tags nogui ./internal/sessions/ ./internal/gui/ passes.
- gofmt -l is clean. go vet passes on darwin, linux (nogui) and windows.

Not tried: a real PI-Desktop install. The schema is from its source. A
data folder the user picked in PI-Desktop's own settings, other than
$PI_DESKTOP_DATA_DIR, isn't followed.
2026-10-13 17:10:25 +08:00
yetoneandKoohoko 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>
2026-10-13 07:14:22 +08:00
yetone 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.
2026-10-11 00:49:01 +08:00
yetone 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.
2026-10-08 05:36:17 +08:00