diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index b3038e01e..b034c719f 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -42,7 +42,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md).
| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. A conversation is kept by its id (`conversationID`), and a Claude Code subagent's apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (`remoteUpstream`, `candidate.vendor`, `sameVendor`): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its sealed reasoning was refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; `TestRemoteMagpieStrictKeepsTheRemotesProvider`, `TestRemoteMagpieOtherProviderIsNotTheSameAccount`). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. | [`affinity.go`](../../internal/gateway/affinity.go) |
| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one with no frame for 20s is pinged, and dropped when no answer comes within 10s (`netproxy.HTTP2Health`, on `http.DefaultTransport` too), so a connection gone silent without closing (a proxy's way out died, a NAT forgot the flow) fails the requests on it, which move on as a 502 does, and the next request dials a new one. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut by it (#2843: a group's requests hung with no first byte until a restart; `TestGroupMovesOnFromSilentHTTP2Connection`). A large body (64KB or more, or of no stated length) is pinged too, as a silent connection takes a body that fits its send buffer, but its ping's answer is queued behind the body's own DATA, so on a slow uplink a working connection loses it (#3909: a ~680KB turn on a 2-10KB/s uplink failed every try). Such a body whose connection was dropped for a lost ping is sent once more, through `GetBody`, on a new connection that is not pinged and is given up on when a write moves no bytes for a minute (`uploadTransport`); for 30 minutes after, large bodies go there at once (`drawsApart.slow`; `TestUploadStillUnderwayIsNotCutByHealthPing`, `TestSlowUplinkSkipsTheLostTry`, `TestLargeBodyOnSilentConnectionIsSentAgain`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`, `catalog.WrongEndpoint`: the English wordings and AgentRouter's Chinese one, #3766, read escaped too; a model's test reads them as well, see [Providers and accounts](providers-accounts.md)) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. It goes to the first API `usable` gives, Chat where the provider has a Chat URL too, except one that asks an image's size or shape (`generationConfig.imageConfig`), which only a Gemini API takes: that one is translated on the Gemini URL (#3820, `TestGeminiImageConfigGoesToTheGeminiAPIBesideChat`). | [`gateway.go`](../../internal/gateway/gateway.go) |
| Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) A request outside the chat path gets a route of its own too ([`media_route.go`](../../internal/gateway/media_route.go), `sideRoute`): an image (`images`, each account `drawOnAccounts` asks a try), a video's start (`videosCreate`; its polls and download are the same video and add none) and an embedding, rerank, transcription or speech (`retrieve`). Each try's key or account is put in `Order` so the page finds its seat, the route's `Kind` stays empty, and the one usage row names it in `RouteID` (zzzkl3994 on Discord: a video the magpie-image MCP made was in Usage's requests and not on Routing; `TestVideoIsOnRoutingOnce`, `TestImageIsOnRouting`, `TestEmbeddingAndRerankAreOnRouting`). |
-| Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the body is kept as it went and masked when `PromptText` first reads it, so the request itself never waits on masking (#3973). `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`; once a body is dropped, or magpie quits, its text is gone. It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). A session's line and its compactions are its own turns': a call with a `Kind`, a Claude Code subagent's (`Route.Sub`, from `x-claude-code-agent-id`), and, in a session whose turns carry tool definitions, a request without any (auto mode's classifier, the title, the quota check) are left out, so a classifier's 40K after a 100K turn is no compaction (`toolSessions`, `TestContextSideCallsAreNoCompaction`). | [`prompt.go`](../../internal/gateway/prompt.go) |
+| Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the body is kept as it went and masked when `PromptText` first reads it, so the request itself never waits on masking (#3973). `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`. Once a body is dropped, or magpie quits, the GUI reads the request archive's copy when the route names one (`Route.Archive`; wangbinyq on Discord): `ArchivedPromptText` parses it the same way and masks it as the body in memory is (`maskedCopy`), and the reply beside it comes from `ReplyBody` (the Recent calls' reply) or the archive's, read into pieces by `ReplyPieces` and masked alike (`prompt_reply.go`, served as `/api/context/reply`). A body or reply that can't be masked shows nothing, and one the archive cut short isn't parsed (`TestArchivedPromptTextIsMasked`, `TestReplyPiecesAreMasked`, `TestContextTextFromTheArchive`). It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). A session's line and its compactions are its own turns': a call with a `Kind`, a Claude Code subagent's (`Route.Sub`, from `x-claude-code-agent-id`), and, in a session whose turns carry tool definitions, a request without any (auto mode's classifier, the title, the quota check) are left out, so a classifier's 40K after a 100K turn is no compaction (`toolSessions`, `TestContextSideCallsAreNoCompaction`). | [`prompt.go`](../../internal/gateway/prompt.go) |
| Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini for its Gemini models, chat completions for its partner models, and Anthropic's Messages API for Claude. Claude (`provider.VertexClaude`: `claude-opus-5-5`, `claude-sonnet-4-5@20250929`) is relayed or translated as at any Anthropic vendor, and `forwardOnce`, after every other change to the body, moves the request to where Anthropic's Vertex SDK sends it (`provider.VertexClaudeRequest`): `/publishers/anthropic/models/:streamRawPredict` when the body streams, `:rawPredict` when it doesn't, the model out of the body; count_tokens to `count-tokens:rawPredict` with the model kept (`countTokens` counts at a provider whose `Base(Anthropic)` is set); `anthropic_version` `vertex-2023-10-16` added unless the body has one; Claude Code's `?beta=true` never sent. `thinkingOffAsTaken` and `samplingAsTaken` run before, so they read the model from the body. Tool search's beta goes as `tool-search-tool-2025-10-19`, the name Claude Code gives it for Vertex as for Bedrock (`bedrockBetas`); Bedrock's left-out betas aren't left out for it. Gemini's effort rules (`vertexEffort`) don't touch it (`TestVertexClaudeModel`). A partner model (`provider.VertexPartner`: a `publisher/model` id such as `deepseek-ai/deepseek-v4.1-flash-maas`) goes to Google's OpenAI-compatible `/endpoints/openapi/chat/completions` (`Base(Chat)`, `ListedAPIs`), signed with the same token, its full id in the body. It is relayed or translated there as any chat completions vendor is, and none of the Gemini rules below (`vertexEffort`, `vertexThinking`, signatures) touch it (`TestVertexPartnerModel`). A Gemini model's request goes to `/publishers/google/models/:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` is asked again with every call sent so (`withoutSignatures`), for that request only. A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) |
| Bedrock Mantle | A request on chat completions or Responses to an [Amazon Bedrock Mantle provider](providers-accounts.md#responsibilities-and-sources-of-truth) goes to the prefix that serves its model (`mantleRoutes`, `provider.MantleBase` in `forwardOnce`): `/openai/v1` for OpenAI's closed GPTs and xAI's Grok, `/v1` for the rest. A model Mantle refuses there with "model `x` isn't supported on this route" (a maker the rule doesn't know yet) is asked once more at the other prefix, and when it is taken there that prefix is remembered for the model in `unfit` (`mantleRouteKey`) until the gateway restarts. A model refused at both gets the first refusal and nothing is remembered (`mantleReroute`). Messages go to `/anthropic` alone. | [`mantle.go`](../../internal/gateway/mantle.go), [`gateway.go`](../../internal/gateway/gateway.go) |
diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md
index e88797d8c..ddda0f32a 100644
--- a/docs/subsystems/gui-shell.md
+++ b/docs/subsystems/gui-shell.md
@@ -17,7 +17,7 @@ three.
| Settings from the terminal | `POST /api/settings` saves through `settingsapi.Apply` (`internal/settingsapi`, outside the GUI so the `nogui` build has it): the carry of keys a page leaves out (`Merge`), the vision, image and searcher checks, `settings.Save`'s own checks, and `catalog.Touched`. `magpie settings list\|get\|set\|reset` (#4745) builds the same body with `settingsapi.Body` (the whole file with one key changed, so a key the save keeps when it isn't sent is set even to off) and calls the same `Apply`; a refused value writes nothing. `settingsapi.Keys` names what the save writes; `TestKeysAreWhatTheSaveWrites` fails when a field of `settings.Settings` is saved without it, `TestSettingsCLISetsWhatTheWindowSaves` when a key the page's `savePrefs` sends isn't one, and `TestEveryRouteHasACommandOrIsNamed` when an `/api` route has neither a command nor a reason in `notYet` (`internal/cli/settings_parity_test.go`). The running app's in-process follow-ups (fonts, Dock, tray menu, alerts, language, update check) run only from the window's save; a change from the terminal is read from the file. | [`internal/settingsapi/settingsapi.go`](../../internal/settingsapi/settingsapi.go), [`settings_cli.go`](../../internal/cli/settings_cli.go) |
| Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Added to a phone's home screen the page opens as an app of its own, with no browser bars (ninja_s6114 on Discord): `index.html` names `manifest.json` (display standalone), an apple-touch-icon and the iOS meta tags, the status bar keeps its own ground (`default`), and its theme colours match only `(display-mode: standalone)`, so a browser's tab and the app's windows take none. `webGuard` serves those three files (`webAppFiles`: the manifest, `icons/apple-touch-icon.png`, `icons/icon-512.png`) without the key, to GET and HEAD at those exact paths alone, as a home screen may ask without the cookie; see `TestWebAppAddsToHomeScreen` and `web-app-standalone.test.cjs`. Gateway mode shows Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings on a machine that is only a gateway. `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304; never an event stream, which gzip would hold back until its buffer fills); the app's own windows read the page in-process and get it uncompressed. The page's port answers the gateway's client routes too (`onePort`, `gateway.ClientPath`: `/v1/…`, `/v1beta/…`, `/mcp/…`, the Codex backend path and the routes without `/v1`; never `/api/*` or `/_magpie/*`, never a path that isn't clean), so one reverse-proxy location serves the page and the agents (zgcwkj on Discord). They skip the page's key and gzip and go to the gateway's own guards, always as a request from another machine (`gateway.FromPagePort`, the `X-Magpie-Page-Port` mark: `local` is false for it, from loopback too and under `MAGPIE_TRUST_PROXY`, so magpie must be shared and the request carry an enabled gateway key), since a raw TCP forward or a proxy that adds no forwarding header reaches this port from loopback looking like an agent here (reported privately by Coffemon); agents here use the gateway's own port. `Server.Front` (lanGuard over Handler) serves them in process when this process serves the gateway, or `toGateway`, a reverse proxy to `gateway.URL()`, when another magpie does; it keeps the Host, the forwarding headers and the mark, adds X-Forwarded-For for a peer that isn't loopback, and the peer's loopback address as X-Forwarded-For when none came, so a gateway of an older magpie that doesn't know the mark still asks for a key. `lanGuard` moves the mark into the request's context and takes the header off, so it never goes upstream. The page itself calls no client route. See `TestWebOnePortServedHere`, `TestWebOnePortServedElsewhere`, `TestWebOnePortAgentsHereUseTheGatewayPort`, `TestPagePortMarkIsNeverLocal` and `TestClientPathCoversHandler`. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go), [`oneport.go`](../../internal/gateway/oneport.go) |
| The app's page in a browser | Settings › Network and sharing › Browser access (`renderWebPage` in `plugins/gateway/settings.js`, drawn with the Web pages rows) has the app serve its own page to a browser while it runs, so a tunnel (Cloudflare Tunnel, SSH) or a computer on the network can reach it without `magpie web` kept running in a terminal (jiakun_zhao on X). Off, This computer (`127.0.0.1`, which a tunnel's service points at) or Local network (every address; a "Not encrypted" row without `--tls-cert`). It is `magpie web`'s page and guard, not a second kind: `startAppPage` (from `Run`, after `startBackend`) serves `webServed` over a `Handler` of its own, whose `Windows` is `appWebHost` (a browser tab for `isWeb`, but not `ownWeb`, so the app's windows aren't taken for `magpie web`'s: `webPage` and gateway mode stay the app's; quitting quits the app, and a restart to update from it brings back the windows the app has up, `restartFrom`). The key is always asked for: no mode serves without it. It lives with the mode and port in `web-page.json` beside settings.json (0600, never in settings.json, so sync and backup don't carry it), is made the first time the page is turned on, kept across restarts (a browser's cookie stays good), and replaced by New key, which turns away every browser signed in with the old one (the guard is swapped atomically, `appPage.cur`). A file that can't be read, or names no known mode, is off and says why; Settings rewrites it only given a whole choice. A port another program holds (`magpie web`; the magpie before a restart to update) is said and tried again every 4 s (`appPageRetry`); the port must be 1024 up and not the gateway's. `GET/POST /api/web-page` are on the app's own windows' API only, never a browser's, so a browser on the page can neither read the key it came in without nor turn the page off under itself. `magpie web` on the port the app serves prints the app's link and opens it rather than starting a second (`gui.AppPage`, `samePort`). Sessions are warmed once a process however many `Handler`s there are (`warmOnce`). See `TestAppPageServesOnlyWithItsKey`, `TestAppPageWaitsForABusyPort`, `TestAppPageUnreadFileServesNothing`, `TestAppPageTurnsDownBadChoices`, `TestAppPageBrowserIsATab` and `browser-access.test.cjs`. | [`apppage.go`](../../internal/gui/apppage.go), [`web_cli.go`](../../internal/cli/web_cli.go) |
-| The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `plugins.js` and `context.js`, and those a plugin adds under `assets/plugins//` (the Gateway, Sessions, Library, Routing and Usage pages, see [plugin runtime](plugin-runtime.md)) (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; a client whose User-Agent names only an HTTP library, a runtime or an API SDK (`usage.IsLibrary`: curl, Bun, python-httpx, Go-http-client, OpenAI/Python), or nothing (`other`), is no agent and goes on one card, `scripts`, named Scripts with its libraries listed, read from each route's kept agent so older history folds too, while the Usage page's Agents list keeps each by its own name (theforeveriris on X, `context_scripts_test.go`, `context-scripts.test.cjs`); clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory (`openCtxText`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js`, and a plugin's own in its `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) |
+| The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `plugins.js` and `context.js`, and those a plugin adds under `assets/plugins//` (the Gateway, Sessions, Library, Routing and Usage pages, see [plugin runtime](plugin-runtime.md)) (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; a client whose User-Agent names only an HTTP library, a runtime or an API SDK (`usage.IsLibrary`: curl, Bun, python-httpx, Go-http-client, OpenAI/Python), or nothing (`other`), is no agent and goes on one card, `scripts`, named Scripts with its libraries listed, read from each route's kept agent so older history folds too, while the Usage page's Agents list keeps each by its own name (theforeveriris on X, `context_scripts_test.go`, `context-scripts.test.cjs`); clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory, else the request archive's copy masked the same way, with a 404 saying why there is none (`archive`: off, missing, cut, unread; `context_archive.go`), and its Reply the reply from `/api/context/reply` (`openCtxText`, in `ctxtext.js`, `context-text.test.cjs`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js`, and a plugin's own in its `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) |
| Window navigation | In the window from 1024 points wide (`SIDE_AT`, the same width as app.css's `side-nav` rules), `layoutNav` moves the brand, the pages (`#nav`) and Settings into the sidebar (`#side`): the pages in four groups (Work, Models, Insights, Extend; a group none of whose pages shows, as in gateway mode, leaves out its name), the gateway's address at its foot (`sideGwRead`, read from `/api/providers` only while there is a sidebar, or drawn at once from boot.js's `sideGateway`; on a page other machines open, `magpie web`, it is `MAGPIE_PUBLIC_URL` while they are let in, as the Gateway page's address and About's Gateway URL are, noahhrreion on Discord; a port applied in Settings redraws it), and the header a breadcrumb (`renderCrumb`). A page whose head holds only its tools (Library, Plugins, Settings) has them in the title bar after the breadcrumb, `tools` setting the room between it and the window's own buttons. When they don't fit there the tools show their icons alone (`tools-tight`; each keeps its name as `aria-label` and in its tooltip), then the breadcrumb drops its leading parts, and last the page's name is cut at its end, so no tool lies over the title (#2625, `title-bar-tools.test.cjs`). The open page's own tabs (`NAV_SUBS`: Usage, Library, Plugins, Settings) are listed under it as `.nav-s` rows (`role="tab"`, `data-of` the page tab's id) and the page's strip is hidden; a row's click clicks that tab at once, the selection (`.nav-hl`) having set off as the row was pressed (`navSubGlide`; back if the press leaves the row), and is the list's only shape: a row hovered or pressed has no ground of its own, and a `MutationObserver` draws the list again when the strip changes. A page's tabs share its one scroll, so a row that picks another tab opens it at its top (`scrollOnPurpose` with the row's click); the tab already open, picked again, leaves the page where it is (`sidebar-tab-top.test.cjs`). The list opens and folds with an iOS-like spring (`navSubEnter`, `navSubLeave`; none under reduced motion), and a folding list is out of reach at once. The open page's own row is marked the same way, by one shape (`.nav-top-hl`, the rows' own ground given up to it, hovered or pressed too) that `navTopGo` moves to the row picked on a damped spring, as iOS moves a selection (`NAV_SPRING`, SwiftUI's response 0.42s and damping 0.84; `navTopStep` steps it each frame): it sets off as the row is pressed and comes back if the press leaves the row or the page isn't left, turns with the speed it has when the press changes its mind, and follows its row while the list above it folds, landing where the row ends up. It is put in place, not sent, when the window opens on a page or the rows move under it at rest (a `ResizeObserver`), is away while Settings is open (it has its own selection at the foot), comes back fading in on its row, jumps under reduced motion, and isn't drawn in the header's tabs, which have their `.thumb`. `#nav` is `position: relative` in the sidebar for it, so `.seg`'s centring `left` and `top` are reset. See `sidebar-glide.test.cjs`. Narrower, the page beside a sidebar would be narrower than Usage's requests table needs (768 points), so they go back into the header's row, as a Mac sidebar gives way in a narrow window. At every width the reader can pick the sidebar or the header's tabs from the title bar's button (`#sideToggle`, ⌃⌘S or Ctrl+Shift+S; `toggleSideNav`), kept in localStorage `magpie.navLayout` (`side` or `top`) and so laid out from the first frame; none picked, the sidebar comes from `SIDE_AT`. Picked in a narrow window the sidebar is narrower (184 points under 860), and magpie web on a phone keeps its own tab bar and has no button. The two layouts trade places in a view transition (`navMorph`, app.css `.nav-morph`): the sidebar slides, each page's tab flies to its place in the other, and the page slides as one (its old image dropped, so no line prints twice); without view transitions, under reduced motion, or in the Linux app the change is at once: WebKitGTK with compositing off (`WEBKIT_DISABLE_COMPOSITING_MODE`, which `webkit_linux.go` sets under Wayland) crashes in a view transition. Elsewhere a transition still going after `MORPH_MAX` (1.5s) is skipped, so a webview that never ends one can't leave the window on the old layout's picture. See `side-toggle.test.cjs`. A window made wider or narrower drops what a click held (`heldWidth`): the page laid out again isn't the click's doing. The reader's own place is kept instead for a second while the page is laid out again (`relaid`, a `ResizeObserver` on the open page's parts calling `backToReader`): crossing `SIDE_AT` the browser clamps the scroll to each layout it passes through, and the page ended short of its foot (#1672, `text-size.test.cjs`). See `sidebar.test.cjs`. A sidebar longer than a short window keeps no scroll bar beside its pages: the native bars of `.side-scroll` and `.side-foot` are hidden, and `sideBars` lays a thin bar over each box's edge that shows while it scrolls, fades about a second after it stops (kept while hovered or dragged), can be dragged or clicked to page, and is gone when the box fits, the same in WebKit, WebView2 and WebKitGTK. See `sidebar-overlay-scrollbar.test.cjs`. The window opens on the page the reader last left, as a Mac app comes back as it was (molvqingtai and lc on Discord): `show` keeps the page in localStorage `magpie.lastView` (which the app's webview keeps across restarts, as it keeps `magpie.navLayout`), and `keptView` opens it at start. A page asked for in the address (`?view=`, the tray's links, a reload) wins, Agents too; a kept name that is no page opens the first page, and one gateway mode leaves out opens Providers (`show`). Opening on it scrolls nothing. See `last-page.test.cjs`. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/app.css`](../../internal/gui/assets/app.css) |
| Settings › Privacy | The page opens on what masking kept from vendors (`drawMaskObs` in app.js, fed by `/api/masking/summary`): the values masked over 7 or 30 days with a chart of the days, the kinds, what only the local model found, agents to providers, and the values masked most, each shown only while pointed at (`maskTip`, `/api/masking/value`, which says it is gone after a restart). Its records (`drawMaskRecs`, `/api/masking/records` and `/api/masking/record`) take the page's place, filtered by kind, finder, agent or provider, a day at a time, each opening on the text the vendor saw with its placeholders marked. `maskedBadge`, on the Gateway page's recent calls and the Routing page's log, opens a request's own record (`openMaskRecord`), in amber with the count sent as written when every value found was on Warn. Below the card, *What to mask*, *How it's found* (the rules, always on while anything is masked, and the local model on top of them), *When a value is found* (Mask, Warn or Block per kind, the secret kinds first and the personal ones behind *Show all kinds*, and the *Never mask* list; `renderMaskActions`), *Try it* (`renderMaskTry`, the text as the vendor would get it from `/api/masking/preview`, kept in no storage) and *Sharing*. *Agents' session history* (`renderSessionReads`, read from `/api/sessions/reads` only while the Privacy part is shown) has *Agents found later* and a row per agent found, the choice the Sessions page asks first on a fresh install; see [gateway sessions](gateway-sessions.md#which-agents-sessions-magpie-reads). While anything is masked, *Instead of masking, send to* (`redactRouteRow` in `plugins/redact/settings.js`, the redact plugin's part of Settings, which wraps `renderRedact` so app.js carries none of it) picks, in the app menu, a model a request masking would change goes to as written: Off by default, and only the models `/api/settings` lists as `maskRouteModels` (every route of theirs unmasked, `gateway.MaskRoute`), saved with `POST /api/settings/redact-route` (`redact-route.test.cjs`). See [gateway routing](gateway-routing.md) for what is recorded. | [`assets/app.js`](../../internal/gui/assets/app.js), [`masking.go`](../../internal/gui/masking.go) |
| Built-in plugins | Plugins › Built-in, the page's first tab (`drawBuiltin` in `plugins.js`, rows by `renderBuiltins` in `app.js`), lists magpie's built-in plugins, each with a name, a line on what it is and a switch: Routing groups, Library, Observability, Sessions, Warm-up and check-in, and the Gateway and Routing pages (Essential). A plugin on with settings has their rows under its row, drawn from its schema by the kernel's `ui.form`, and a change posts `{id, config}`. The Gateway page is drawn by its plugin's own scripts through the window's kernel (`kernel.js`, `assets/plugins/gateway/`); see the [plugin runtime](plugin-runtime.md), "The window's kernel". They are `plugins/*` registered with the [plugin runtime](plugin-runtime.md); `GET /api/plugins/builtin` says each one (`builtinJSON`: on is active, the user's own choice, what of it is in use) and `POST {id, on}` (or `{id, config}`) writes plugins.yml. A page marks what goes with a plugin `data-feature=""`. Off, `featureStyle` hides everything so marked (rows drawn later too), `navHides` leaves its page's tab out of the sidebar and the header, `show` opens Agents for an address kept for it, and `setSetTab`, `partShows` and `findSettings` leave its Settings tab and rows out, of the search too. One in use stays on: its switch is disabled and the row says what uses it, and the POST refuses it off. A plugins.yml that doesn't parse is said above the list and no switch moves. `boot.js` says which are off (`featuresOff`) and their settings (`pluginConfig`) before the first paint, and `settings.builtins` carries the list on every state read. The TUI doesn't follow them. See `builtins.test.cjs`, `builtins_test.go`. | [`builtins.go`](../../internal/gui/builtins.go), [`assets/plugins.js`](../../internal/gui/assets/plugins.js), [`assets/app.js`](../../internal/gui/assets/app.js) |
diff --git a/internal/gateway/conversations.go b/internal/gateway/conversations.go
index fe88e54be..cb42c78eb 100644
--- a/internal/gateway/conversations.go
+++ b/internal/gateway/conversations.go
@@ -140,6 +140,20 @@ func conversationTurn(proto provider.Protocol, input, output []byte) sessions.Ga
t.Input = append(t.Input, conversationParts(m.Role, m.Parts)...)
}
}
+ var cut bool
+ t.Output, cut = conversationOutput(proto, output)
+ t.Cut = t.Cut || cut
+ return t
+}
+
+// conversationOutput reads a reply, a whole JSON body or a stream, into
+// parts; cut when it couldn't all be read or ended before it was whole.
+func conversationOutput(proto provider.Protocol, output []byte) ([]sessions.Part, bool) {
+ t := struct {
+ Output []sessions.Part
+ Cut bool
+ }{Output: []sessions.Part{}}
+ var err error
trim := bytes.TrimSpace(output)
if json.Valid(trim) {
t.Output, err = conversationJSON(proto, trim)
@@ -197,7 +211,7 @@ func conversationTurn(proto provider.Protocol, input, output []byte) sessions.Ga
} else if len(trim) > 0 {
t.Cut = true
}
- return t
+ return t.Output, t.Cut
}
// Reuse the request readers for whole replies by placing the actual output in
diff --git a/internal/gateway/prompt_archive_test.go b/internal/gateway/prompt_archive_test.go
new file mode 100644
index 000000000..a0889630a
--- /dev/null
+++ b/internal/gateway/prompt_archive_test.go
@@ -0,0 +1,88 @@
+package gateway
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/provider"
+ "github.com/yetone/magpie/internal/settings"
+)
+
+// wangbinyq on Discord: with the request archive on, the context window
+// card still said a request's text was gone once it left memory. The
+// archive's copy is read instead, masked as the copy in memory is: a phone
+// number in it shows as its placeholder, as it would from memory.
+func TestArchivedPromptTextIsMasked(t *testing.T) {
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ t.Setenv("XDG_CACHE_HOME", t.TempDir())
+ if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true}); err != nil {
+ t.Fatal(err)
+ }
+ const phone = "13800138000"
+ body := []byte(`{"model":"m","system":"You are the release agent.","messages":[
+ {"role":"user","content":"call me at ` + phone + ` once it ships"},
+ {"role":"assistant","content":"Shipping."}]}`)
+ pt, ok := ArchivedPromptText(provider.Anthropic, body, 7, PartChat, true, 0)
+ if !ok || pt.From != "archive" || len(pt.Items) == 0 {
+ t.Fatalf("%v %+v", ok, pt)
+ }
+ b, _ := json.Marshal(pt)
+ if strings.Contains(string(b), phone) || !strings.Contains(string(b), "once it ships") {
+ t.Fatalf("archived text %s", b)
+ }
+ sys, ok := ArchivedPromptText(provider.Anthropic, body, 7, PartSystem, true, 0)
+ if b, _ := json.Marshal(sys); !ok || !strings.Contains(string(b), "You are the release agent.") {
+ t.Fatalf("system %s", b)
+ }
+ // a body cut short reads as nothing
+ if _, ok := ArchivedPromptText(provider.Anthropic, []byte(`{"model":`), 8, PartChat, true, 0); ok {
+ t.Fatal("read a body cut short")
+ }
+}
+
+// The reply beside the prompt: its text, its thinking and its calls, from
+// a whole reply or a stream, masked as the prompt's text is.
+func TestReplyPiecesAreMasked(t *testing.T) {
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ t.Setenv("XDG_CACHE_HOME", t.TempDir())
+ if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true}); err != nil {
+ t.Fatal(err)
+ }
+ const phone = "13800138000"
+ whole := `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[
+ {"type":"thinking","thinking":"The user wants a call."},
+ {"type":"text","text":"I will call ` + phone + ` when it ships."},
+ {"type":"tool_use","id":"c1","name":"Deploy","input":{"env":"prod","notify":"` + phone + `"}}],
+ "stop_reason":"tool_use","usage":{"input_tokens":3,"output_tokens":9}}`
+ pieces, cut, ok := ReplyPieces(provider.Anthropic, []byte(whole), false)
+ if !ok || cut {
+ t.Fatalf("%v %v", ok, cut)
+ }
+ var roles []string
+ for _, p := range pieces {
+ roles = append(roles, p.Role+":"+p.Name)
+ if strings.Contains(p.Text, phone) {
+ t.Fatalf("%s unmasked: %s", p.Role, p.Text)
+ }
+ }
+ if got := strings.Join(roles, " "); got != "thinking: assistant: call:Deploy" {
+ t.Fatalf("pieces %s", got)
+ }
+ if !strings.Contains(pieces[1].Text, "when it ships") || !strings.Contains(pieces[2].Text, `"prod"`) {
+ t.Fatalf("%+v", pieces)
+ }
+ stream := sse(
+ "event: message_start\ndata: "+`{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[],"usage":{"input_tokens":3,"output_tokens":0}}}`,
+ "event: content_block_start\ndata: "+`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
+ "event: content_block_delta\ndata: "+`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Reach me at `+phone+`."}}`,
+ "event: content_block_stop\ndata: "+`{"type":"content_block_stop","index":0}`,
+ "event: message_stop\ndata: "+`{"type":"message_stop"}`)
+ pieces, _, ok = ReplyPieces(provider.Anthropic, []byte(stream), false)
+ if !ok || len(pieces) != 1 || pieces[0].Role != "assistant" || strings.Contains(pieces[0].Text, phone) || !strings.Contains(pieces[0].Text, "Reach me at") {
+ t.Fatalf("stream %v %+v", ok, pieces)
+ }
+ if _, _, ok := ReplyPieces(provider.Anthropic, nil, false); ok {
+ t.Fatal("read an empty reply")
+ }
+}
diff --git a/internal/gateway/prompt_reply.go b/internal/gateway/prompt_reply.go
new file mode 100644
index 000000000..ad8e5de7c
--- /dev/null
+++ b/internal/gateway/prompt_reply.go
@@ -0,0 +1,100 @@
+package gateway
+
+// The reply beside the prompt's text (wangbinyq on Discord): the context
+// window card's text view shows what the model answered too, read from the
+// reply as the agent got it, from the Recent calls in memory or from the
+// request archive's copy. It is masked as the prompt's text is, so the view
+// shows no value the prompt's own text would have masked.
+
+import (
+ "context"
+ "encoding/json"
+
+ "github.com/yetone/magpie/internal/provider"
+ "github.com/yetone/magpie/internal/redact"
+)
+
+// PromptReply is a request's reply, piece by piece: the answer's text, its
+// thinking and its tool calls.
+type PromptReply struct {
+ ID int64 `json:"id"`
+ Pieces []PromptPiece `json:"pieces"`
+ // Cut: only the reply's start was kept, or it ended before it was whole
+ Cut bool `json:"cut,omitempty"`
+ // From: "memory" (the Recent calls) or "archive"
+ From string `json:"from"`
+}
+
+// ReplyBody is the reply to request route id as the Recent calls keep it,
+// with the protocol it was written in; false once the call has left them.
+func (s *Server) ReplyBody(id int64) (provider.Protocol, []byte, bool, bool) {
+ c, ok := s.RouteCall(id)
+ if !ok || c.ResponseBody == "" {
+ return "", nil, false, false
+ }
+ return c.From, []byte(c.ResponseBody), c.ResponseTruncated, true
+}
+
+// ReplyPieces reads a reply body (JSON or a stream) written in proto into
+// pieces, masked as a prompt's text is; false when nothing in it can be
+// read, or masking failed.
+func ReplyPieces(proto provider.Protocol, body []byte, cut bool) ([]PromptPiece, bool, bool) {
+ parts, outCut := conversationOutput(proto, redact.ScrubJSON(body))
+ var pieces []PromptPiece
+ for _, p := range parts {
+ pc := PromptPiece{Role: "assistant", Text: p.Text}
+ switch p.Kind {
+ case "thinking":
+ pc.Role = "thinking"
+ case "tool_use":
+ pc.Role, pc.Name = "call", p.Name
+ }
+ pieces = append(pieces, pc)
+ }
+ if len(pieces) == 0 {
+ return nil, false, false
+ }
+ if !maskReplyPieces(pieces) {
+ return nil, false, false
+ }
+ for i := range pieces {
+ if pieces[i].Role == "call" {
+ pieces[i] = rawPiece("call", pieces[i].Name, []byte(pieces[i].Text)).read()
+ }
+ }
+ return pieces, cut || outCut, true
+}
+
+// maskReplyPieces masks the pieces' text in place, through the masker a
+// request's body goes through: put as a conversation's assistant turns, so
+// each text is masked as message text is.
+func maskReplyPieces(pieces []PromptPiece) bool {
+ type msg struct {
+ Role string `json:"role"`
+ Content string `json:"content"`
+ }
+ in := struct {
+ Messages []msg `json:"messages"`
+ }{}
+ for _, pc := range pieces {
+ in.Messages = append(in.Messages, msg{Role: "assistant", Content: pc.Text})
+ }
+ body, err := json.Marshal(in)
+ if err != nil {
+ return false
+ }
+ masked := maskedCopy(context.Background(), body)
+ if masked == nil {
+ return false
+ }
+ var out struct {
+ Messages []msg `json:"messages"`
+ }
+ if json.Unmarshal(masked, &out) != nil || len(out.Messages) != len(pieces) {
+ return false
+ }
+ for i := range pieces {
+ pieces[i].Text = out.Messages[i].Content
+ }
+ return true
+}
diff --git a/internal/gateway/prompt_text.go b/internal/gateway/prompt_text.go
index 9f56aa473..e7bd2f58f 100644
--- a/internal/gateway/prompt_text.go
+++ b/internal/gateway/prompt_text.go
@@ -14,10 +14,12 @@ package gateway
import (
"bytes"
"context"
+ "crypto/sha256"
"encoding/json"
"slices"
"strconv"
"strings"
+ "sync"
"github.com/yetone/magpie/internal/provider"
)
@@ -104,6 +106,10 @@ type PromptText struct {
Items []PromptEntry `json:"items"`
// Kept is how many requests' text is kept, for the GUI to say so
Kept int `json:"kept"`
+ // From is "archive" when the text was read from the request archive's
+ // copy, the body having left memory (wangbinyq on Discord); "" from
+ // memory
+ From string `json:"from,omitempty"`
}
// PromptKept is how many requests' text the trace keeps.
@@ -126,7 +132,74 @@ func (s *Server) PromptText(id int64, kind string, withText bool) (PromptText, b
}
s.trace.maskedBody(id, kb.body)
}
- b, ok := promptPieces(kb.from, kb.body)
+ tokens := 0
+ s.trace.mu.Lock()
+ for _, r := range s.trace.routes {
+ if r.ID == id && r.Prompt != nil {
+ tokens = r.Prompt.Tokens
+ }
+ }
+ s.trace.mu.Unlock()
+ return promptTextOf(kb.from, kb.body, id, kind, withText, tokens)
+}
+
+// ArchivedPromptText is PromptText read from the request archive's copy of
+// request id's body, for a request whose body has left memory (wangbinyq
+// on Discord: the card said the text was gone with the archive on). The
+// archive keeps the body as the agent sent it, its secrets taken out; it
+// is masked here as the body in memory is, so the card shows no more from
+// the archive than from memory. tokens is the route's prompt as counted,
+// to scale the sizes as the card does. One masked body is kept, in memory,
+// for the item clicked next. False when the body can't be read: the
+// archive kept only its start, or masking failed.
+func ArchivedPromptText(from provider.Protocol, body []byte, id int64, kind string, withText bool, tokens int) (PromptText, bool) {
+ if !slices.Contains(partOrder, kind) {
+ return PromptText{}, false
+ }
+ body, ok := archivedMasked(id, body)
+ if !ok {
+ return PromptText{}, false
+ }
+ pt, ok := promptTextOf(from, body, id, kind, withText, tokens)
+ pt.From = "archive"
+ return pt, ok
+}
+
+// lastArchived is the archived body last masked for the card, so opening
+// its items one by one masks it once
+var lastArchived struct {
+ sync.Mutex
+ id int64
+ sum [32]byte
+ body []byte
+}
+
+func archivedMasked(id int64, body []byte) ([]byte, bool) {
+ if len(body) == 0 || len(body) > promptBodyMax {
+ return nil, false
+ }
+ sum := sha256.Sum256(body)
+ lastArchived.Lock()
+ if lastArchived.id == id && lastArchived.sum == sum {
+ b := lastArchived.body
+ lastArchived.Unlock()
+ return b, true
+ }
+ lastArchived.Unlock()
+ masked := maskedCopy(context.Background(), body)
+ if masked == nil {
+ return nil, false
+ }
+ lastArchived.Lock()
+ lastArchived.id, lastArchived.sum, lastArchived.body = id, sum, masked
+ lastArchived.Unlock()
+ return masked, true
+}
+
+// promptTextOf is the part kind of a prompt read from body, its sizes
+// scaled to tokens, the prompt as the vendor counted it.
+func promptTextOf(from provider.Protocol, body []byte, id int64, kind string, withText bool, tokens int) (PromptText, bool) {
+ b, ok := promptPieces(from, body)
if !ok {
return PromptText{}, false
}
@@ -138,13 +211,9 @@ func (s *Server) PromptText(id int64, kind string, withText bool) (PromptText, b
}
}
scale := 1.0
- s.trace.mu.Lock()
- for _, r := range s.trace.routes {
- if r.ID == id && r.Prompt != nil && r.Prompt.Tokens > 0 && est > 0 {
- scale = float64(r.Prompt.Tokens) / float64(est)
- }
+ if tokens > 0 && est > 0 {
+ scale = float64(tokens) / float64(est)
}
- s.trace.mu.Unlock()
out := PromptText{ID: id, Kind: kind, Items: []PromptEntry{}, Kept: promptBodies}
for key, it := range b.parts[kind] {
e := PromptEntry{Name: it.Name, Tag: it.Tag, Tokens: int(float64(it.Tokens)*scale + 0.5)}
diff --git a/internal/gui/assets/context.js b/internal/gui/assets/context.js
index 89969a465..da4c4a136 100644
--- a/internal/gui/assets/context.js
+++ b/internal/gui/assets/context.js
@@ -724,7 +724,7 @@
parts = cur = null;
return;
}
- rid = r.id;
+ rid = r;
const window = p.window || 0;
const full = window ? p.tokens / window : 0;
const live = !r.done;
@@ -971,11 +971,7 @@
// A part of the card clicked opens what the request sent there, read
// from the request's body: an item alone (a tool, a file, a turn), or
- // the part's items, each opened to its text. magpie keeps the last few
- // requests' bodies, masked, in memory only, so an older one's text is
- // gone. A long text comes a stretch at a time, so a prompt of megabytes
- // doesn't hold the window up.
- // in ctxtext.js, loaded when a part is first opened
+ // the part's items, each opened to its text (ctxtext.js, loaded then)
const openCtxText = (...a) => import("./ctxtext.js").then((m) => m.open({ fmtK, partName, itemName, itemLabel, tagOf }, ...a)).catch(statusErr);
window.openCtxText = openCtxText;
window.ctxFmt = fmtK;
diff --git a/internal/gui/assets/ctxtext.js b/internal/gui/assets/ctxtext.js
index 79e3f8ce6..5c2f34eb0 100644
--- a/internal/gui/assets/ctxtext.js
+++ b/internal/gui/assets/ctxtext.js
@@ -1,19 +1,28 @@
// The text of a part of the context window card (context.js): what the
// request sent there, opened from the card. context.js imports this when a
-// part is first opened, so it weighs nothing on the core.
+// part is first opened, so it weighs nothing on the core. A request whose
+// body has left memory is read from the request archive, when it kept one,
+// and the reply beside it (wangbinyq on Discord).
const TEXT_STEP = 20000, ITEM_STEP = 100;
const ROLE_NAMES = {
system: "System prompt", user: "You", assistant: "Assistant", thinking: "Thinking",
call: "Tool call", result: "Tool result", tool: "Tool definition", image: "Image", sealed: "Sealed",
};
-async function readText(id, kind, item) {
- const q = "id=" + encodeURIComponent(id) + "&kind=" + encodeURIComponent(kind) + (item === undefined ? "" : "&item=" + item);
+// read: /api/context/; a 404 is {archive: why}, why it is gone
+async function read(what, q) {
// fetched, not api(): the text isn't looked through for accounts
- const res = await fetch("/api/context/text?" + q);
- if (res.status === 404) return null;
+ const res = await fetch("/api/context/" + what + "?" + new URLSearchParams(q));
+ if (res.status === 404) return { gone: (await res.json().catch(() => ({}))).archive || "off" };
if (!res.ok) throw new Error((await res.text()).trim() || res.statusText);
return res.json();
}
+const GONE = {
+ off: "This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.",
+ missing: "Not in the request archive: it is saved just after the call, the oldest are removed past the archive's size, or the save failed (magpie's log says why)",
+ cut: "The request archive kept only the start of this request, so it can't be read",
+ unread: "The request archive's copy couldn't be read or masked, so none of it is shown",
+};
+const gone = (why, n) => el("p", "ctx-view-gone", t(GONE[why] || GONE.off, { n }));
// a stretch of text, and a button for the next
function longText(text) {
const box = el("div", "ctx-text-box");
@@ -77,9 +86,13 @@ function pieceView(pc) {
}
return box;
}
-export async function open(kit, id, kind, pick) {
+export async function open(kit, route, kind, pick) {
const { fmtK, partName, itemName, itemLabel, tagOf } = kit;
+ const id = route?.id;
if (!id) return;
+ // the day the history keeps it under, for one the gateway no longer holds
+ const day = String(route.time || "").slice(0, 10);
+ const readText = (kind, item) => read("text", { id, kind, day, ...(item === undefined ? {} : { item }) });
const ed = el("div", "editor ctx-view wide");
const head = el("div", "ehead");
const title = el("b", "", partName(kind));
@@ -90,19 +103,50 @@ export async function open(kit, id, kind, pick) {
const bar = el("div", "bar");
const close = el("button", "text primary", t("Close"));
close.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); };
- bar.append(el("span", "grow"), close);
+ // the reply beside it: what the model answered, from memory or the archive
+ const reply = el("button", "text", t("Reply"));
+ reply.type = "button";
+ let view = null;
+ reply.onclick = async (e) => {
+ e.stopPropagation();
+ if (reply.classList.toggle("on")) {
+ reply.textContent = partName(kind);
+ title.textContent = t("Reply");
+ total.textContent = "";
+ body.replaceChildren(el("div", "ctx-view-wait", t("Reading…")));
+ let r;
+ try { r = await read("reply", { id, day }); } catch (err) { r = { err }; }
+ if (confirmAsk !== ed || !reply.classList.contains("on")) return;
+ if (r.err) return body.replaceChildren(el("p", "ctx-view-gone", r.err.message));
+ if (r.gone) return body.replaceChildren(gone(r.gone, 10));
+ const note = el("p", "ctx-view-note", t(r.from === "archive" ? "The reply as the agent got it, read from the request archive, masked where masking is on." : "The reply as the agent got it, masked where masking is on."));
+ body.replaceChildren(note, ...r.pieces.map(pieceView));
+ if (r.cut) body.append(el("p", "ctx-view-note", t("Only the start of the reply was kept")));
+ } else {
+ reply.textContent = t("Reply");
+ title.textContent = partName(kind);
+ if (view) view(); else body.replaceChildren(el("div", "ctx-view-wait", t("Reading…")));
+ }
+ };
+ bar.append(reply, el("span", "grow"), close);
ed.append(head, body, bar);
confirmAsk = ed;
openModal(ed);
$("#modal").classList.add("lib");
- const gone = (n) => el("p", "ctx-view-gone", t("This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.", { n }));
let list;
- try { list = await readText(id, kind); } catch (err) { body.replaceChildren(el("p", "ctx-view-gone", err.message)); return; }
+ const failed = (err) => { view = () => body.replaceChildren(el("p", "ctx-view-gone", err.message)); };
+ try { list = await readText(kind); } catch (err) { failed(err); }
if (confirmAsk !== ed) return;
- if (!list) return body.replaceChildren(gone(10));
+ if (!list) return reply.classList.contains("on") || view();
+ if (list.gone) {
+ view = () => body.replaceChildren(gone(list.gone, 10));
+ return reply.classList.contains("on") || view();
+ }
const items = list.items || [];
- total.textContent = fmtK(items.reduce((s, it) => s + it.tokens, 0)) + " " + t("tokens");
- const note = el("p", "ctx-view-note", t("As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.", { n: list.kept }));
+ const sum = () => fmtK(items.reduce((s, it) => s + it.tokens, 0)) + " " + t("tokens");
+ const note = el("p", "ctx-view-note", list.from === "archive"
+ ? t("As magpie sent it, read from the request archive, masked where masking is on.")
+ : t("As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.", { n: list.kept }));
// an item: its text alone; "N more" or the earlier turns: the part's list
const at = pick && pick.tag !== "more" && pick.tag !== "turns"
? items.findIndex((it) => it.name === pick.name && (it.tag || "") === (pick.tag || "")) : -1;
@@ -127,9 +171,9 @@ export async function open(kit, id, kind, pick) {
box.classList.toggle("open", on);
if (!on || read) return;
text.replaceChildren(el("div", "ctx-view-wait", t("Reading…")));
- read = readText(id, kind, i).then((one) => {
+ read = readText(kind, i).then((one) => {
const pieces = one?.items?.[i]?.pieces;
- if (!pieces) { read = null; text.replaceChildren(gone(list.kept)); return; }
+ if (!pieces) { read = null; text.replaceChildren(gone(one?.gone, list.kept)); return; }
text.replaceChildren(...(pieces.length ? pieces.map(pieceView) : [el("div", "ctx-piece-note", t("Empty"))]));
}).catch((err) => { read = null; text.replaceChildren(el("p", "ctx-view-gone", err.message)); });
};
@@ -139,7 +183,9 @@ export async function open(kit, id, kind, pick) {
return box;
};
const showAll = () => {
+ view = showAll;
title.textContent = partName(kind);
+ total.textContent = sum();
const rows = el("div", "ctx-vi-list");
let shown = 0;
const more = el("button", "text ctx-text-more");
@@ -155,18 +201,23 @@ export async function open(kit, id, kind, pick) {
step();
body.replaceChildren(note, items.length ? rows : el("div", "ctx-empty", t("Nothing in it")), more);
};
- if (at < 0) return showAll();
- // the item alone, the part's other items a click away
- title.textContent = partName(kind) + " · " + itemName(items[at]);
- total.textContent = fmtK(items[at].tokens) + " " + t("tokens");
- const all = el("button", "text ctx-view-all", t("All of {part} · {n}", { part: partName(kind), n: items.length }));
- all.type = "button";
- all.onclick = (e) => {
- e.stopPropagation();
- all.remove();
- total.textContent = fmtK(items.reduce((s, it) => s + it.tokens, 0)) + " " + t("tokens");
- showAll();
- };
- if (items.length > 1) bar.prepend(all);
- body.replaceChildren(note, entry(items[at], at, true));
+ if (at < 0) view = showAll;
+ else {
+ // the item alone, the part's other items a click away
+ const all = el("button", "text ctx-view-all", t("All of {part} · {n}", { part: partName(kind), n: items.length }));
+ all.type = "button";
+ all.onclick = (e) => {
+ e.stopPropagation();
+ all.remove();
+ if (reply.classList.contains("on")) reply.click();
+ showAll();
+ };
+ if (items.length > 1) bar.prepend(all);
+ view = () => {
+ title.textContent = partName(kind) + " · " + itemName(items[at]);
+ total.textContent = fmtK(items[at].tokens) + " " + t("tokens");
+ body.replaceChildren(note, entry(items[at], at, true));
+ };
+ }
+ if (!reply.classList.contains("on")) view();
}
diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js
index 5ac9dbed0..b61623aec 100644
--- a/internal/gui/assets/i18n.js
+++ b/internal/gui/assets/i18n.js
@@ -94,6 +94,13 @@ const I18N = {
"Sealed by the vendor, {n} bytes: only the vendor can read it": "服务商已加密,{n} 字节:只有服务商能读",
"This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.": "这个请求的原文已不再保留:magpie 只在运行期间、仅在内存中保留最近 {n} 个请求的原文。",
"As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.": "即 magpie 发出的内容,开启脱敏时为脱敏后的内容。仅在内存中保留最近 {n} 个请求。",
+ "Not in the request archive: it is saved just after the call, the oldest are removed past the archive's size, or the save failed (magpie's log says why)": "不在请求存档中:存档在调用结束后才保存,超出存档大小时最早的会被删除,也可能保存失败了(原因见 magpie 的日志)",
+ "The request archive kept only the start of this request, so it can't be read": "请求存档只保留了这个请求的开头,无法读取",
+ "The request archive's copy couldn't be read or masked, so none of it is shown": "无法读取或脱敏请求存档中的副本,因此不显示任何内容",
+ "As magpie sent it, read from the request archive, masked where masking is on.": "即 magpie 发出的内容,读自请求存档,开启脱敏时为脱敏后的内容。",
+ "The reply as the agent got it, read from the request archive, masked where masking is on.": "即 agent 收到的回复,读自请求存档,开启脱敏时为脱敏后的内容。",
+ "The reply as the agent got it, masked where masking is on.": "即 agent 收到的回复,开启脱敏时为脱敏后的内容。",
+ "Only the start of the reply was kept": "只保留了回复的开头",
"All of {part} · {n}": "全部{part} · {n}",
"{n} on {date}": "{date} {n}",
"roles": "角色",
@@ -4580,6 +4587,13 @@ const I18N = {
"Sealed by the vendor, {n} bytes: only the vendor can read it": "服務商已加密,{n} 位元組:只有服務商能讀",
"This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.": "這個請求的原文已不再保留:magpie 只在執行期間、僅在記憶體中保留最近 {n} 個請求的原文。",
"As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.": "即 magpie 送出的內容,開啟遮罩時為遮罩後的內容。僅在記憶體中保留最近 {n} 個請求。",
+ "Not in the request archive: it is saved just after the call, the oldest are removed past the archive's size, or the save failed (magpie's log says why)": "不在請求存檔中:存檔在呼叫結束後才儲存,超出存檔大小時最早的會被刪除,也可能儲存失敗了(原因見 magpie 的日誌)",
+ "The request archive kept only the start of this request, so it can't be read": "請求存檔只保留了這個請求的開頭,無法讀取",
+ "The request archive's copy couldn't be read or masked, so none of it is shown": "無法讀取或遮罩請求存檔中的副本,因此不顯示任何內容",
+ "As magpie sent it, read from the request archive, masked where masking is on.": "即 magpie 送出的內容,讀自請求存檔,開啟遮罩時為遮罩後的內容。",
+ "The reply as the agent got it, read from the request archive, masked where masking is on.": "即 agent 收到的回覆,讀自請求存檔,開啟遮罩時為遮罩後的內容。",
+ "The reply as the agent got it, masked where masking is on.": "即 agent 收到的回覆,開啟遮罩時為遮罩後的內容。",
+ "Only the start of the reply was kept": "只保留了回覆的開頭",
"All of {part} · {n}": "全部{part} · {n}",
"{n} on {date}": "{date} {n}",
"roles": "角色",
@@ -9041,6 +9055,13 @@ const I18N = {
"Sealed by the vendor, {n} bytes: only the vendor can read it": "ベンダーが暗号化済み、{n} バイト:読めるのはベンダーだけです",
"This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.": "このリクエストの本文はもう保持されていません。magpie は直近 {n} 件のリクエストの本文を、実行中にメモリ内だけで保持します。",
"As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.": "magpie が送信したとおりの内容です(マスキングが有効ならマスク済み)。直近 {n} 件のリクエストだけをメモリ内に保持します。",
+ "Not in the request archive: it is saved just after the call, the oldest are removed past the archive's size, or the save failed (magpie's log says why)": "リクエストアーカイブにありません。アーカイブは呼び出しの直後に保存され、サイズを超えると古いものから削除されます。保存に失敗した可能性もあります(理由は magpie のログにあります)",
+ "The request archive kept only the start of this request, so it can't be read": "リクエストアーカイブにはこのリクエストの先頭しか残っていないため、読み取れません",
+ "The request archive's copy couldn't be read or masked, so none of it is shown": "リクエストアーカイブのコピーを読み取れないかマスクできないため、何も表示しません",
+ "As magpie sent it, read from the request archive, masked where masking is on.": "magpie が送信したとおりの内容です。リクエストアーカイブから読み取り、マスキングが有効ならマスク済みです。",
+ "The reply as the agent got it, read from the request archive, masked where masking is on.": "エージェントが受け取ったとおりの返信です。リクエストアーカイブから読み取り、マスキングが有効ならマスク済みです。",
+ "The reply as the agent got it, masked where masking is on.": "エージェントが受け取ったとおりの返信です(マスキングが有効ならマスク済み)。",
+ "Only the start of the reply was kept": "返信の先頭だけが残っています",
"All of {part} · {n}": "{part}をすべて · {n}",
"{n} on {date}": "{date} {n}",
"roles": "ロール",
@@ -13509,6 +13530,13 @@ const I18N = {
"Sealed by the vendor, {n} bytes: only the vendor can read it": "Vom Anbieter versiegelt, {n} Bytes: nur der Anbieter kann es lesen",
"This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.": "Der Text dieser Anfrage wird nicht mehr aufbewahrt: magpie behält den Text der letzten {n} Anfragen nur im Arbeitsspeicher, solange es läuft.",
"As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.": "So, wie magpie es gesendet hat, maskiert, wo Maskierung an ist. Nur für die letzten {n} Anfragen im Arbeitsspeicher aufbewahrt.",
+ "Not in the request archive: it is saved just after the call, the oldest are removed past the archive's size, or the save failed (magpie's log says why)": "Nicht im Anfragearchiv: Es wird direkt nach dem Aufruf gespeichert, die ältesten werden über der Archivgröße entfernt, oder das Speichern ist fehlgeschlagen (magpies Protokoll sagt, warum)",
+ "The request archive kept only the start of this request, so it can't be read": "Das Anfragearchiv hat nur den Anfang dieser Anfrage behalten, daher lässt sie sich nicht lesen",
+ "The request archive's copy couldn't be read or masked, so none of it is shown": "Die Kopie im Anfragearchiv ließ sich nicht lesen oder maskieren, daher wird nichts davon gezeigt",
+ "As magpie sent it, read from the request archive, masked where masking is on.": "So, wie magpie es gesendet hat, aus dem Anfragearchiv gelesen, maskiert, wo Maskierung an ist.",
+ "The reply as the agent got it, read from the request archive, masked where masking is on.": "Die Antwort, wie der Agent sie bekam, aus dem Anfragearchiv gelesen, maskiert, wo Maskierung an ist.",
+ "The reply as the agent got it, masked where masking is on.": "Die Antwort, wie der Agent sie bekam, maskiert, wo Maskierung an ist.",
+ "Only the start of the reply was kept": "Nur der Anfang der Antwort wurde behalten",
"All of {part} · {n}": "Alle: {part} · {n}",
"{n} on {date}": "{n} am {date}",
"roles": "Rollen",
diff --git a/internal/gui/context.go b/internal/gui/context.go
index 496e6552a..d0f6fd2fe 100644
--- a/internal/gui/context.go
+++ b/internal/gui/context.go
@@ -766,7 +766,8 @@ func contextRoutesAPI(mux *http.ServeMux) {
// the text of a part of a request's prompt (masaka on Discord): the
// part's items, and one item's text when item is given. From the
// gateway this GUI runs, which keeps the last requests' masked bodies
- // in memory only; 404 when the request's is no longer kept.
+ // in memory only, else from the request archive; 404 with why when
+ // neither has it.
mux.HandleFunc("GET /api/context/text", func(rw http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
id, err := strconv.ParseInt(q.Get("id"), 10, 64)
@@ -781,15 +782,17 @@ func contextRoutesAPI(mux *http.ServeMux) {
return
}
}
- gw := served.Load()
- if gw == nil {
- http.Error(rw, "not kept", http.StatusNotFound)
- return
+ var pt gateway.PromptText
+ ok := false
+ if gw := served.Load(); gw != nil {
+ pt, ok = gw.PromptText(id, q.Get("kind"), item >= 0)
}
- pt, ok := gw.PromptText(id, q.Get("kind"), item >= 0)
if !ok {
- http.Error(rw, "not kept", http.StatusNotFound)
- return
+ // gone from memory: the request archive's copy, when it
+ // kept one (context_archive.go)
+ if pt, ok = archivedPromptText(rw, r, id, q.Get("kind"), item >= 0); !ok {
+ return
+ }
}
if item >= 0 {
// the one item's text; the rest by name and size only
@@ -809,4 +812,5 @@ func contextRoutesAPI(mux *http.ServeMux) {
rw.Header().Set("Cache-Control", "no-store")
writeJSON(rw, pt)
})
+ contextReplyAPI(mux)
}
diff --git a/internal/gui/context_archive.go b/internal/gui/context_archive.go
new file mode 100644
index 000000000..b7758fbf1
--- /dev/null
+++ b/internal/gui/context_archive.go
@@ -0,0 +1,248 @@
+package gui
+
+// The context window card's text, and the reply beside it, read from the
+// request archive once a request's body has left memory (wangbinyq on
+// Discord: with the archive on, the card still said the text was gone, as
+// magpie keeps only the last 10 requests' bodies in memory). The archive
+// keeps the body as the agent sent it and the reply as the agent got it,
+// their secrets taken out; gateway.ArchivedPromptText and
+// gateway.ReplyPieces mask them as the body in memory is, so the archive
+// shows nothing the memory's copy wouldn't.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/yetone/magpie/internal/davsync"
+ "github.com/yetone/magpie/internal/gateway"
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// ctxGone says why a request's text can't be shown, for the card to say:
+// "off" when the archive has no copy named for the request (it was off,
+// or the route is gone), "missing" when it names one the archive doesn't
+// have (not saved or uploaded yet, or removed past its size), "cut" when
+// the archive kept only the start of it, "unread" when it can't be read
+// or masked: nothing is shown unmasked in its place.
+type ctxGone struct {
+ Archive string `json:"archive"`
+}
+
+func writeGone(rw http.ResponseWriter, why string) {
+ rw.Header().Set("Content-Type", "application/json")
+ rw.Header().Set("Cache-Control", "no-store")
+ rw.WriteHeader(http.StatusNotFound)
+ json.NewEncoder(rw).Encode(ctxGone{Archive: why})
+}
+
+// ctxRouteOf is request id's route, from the gateway this GUI runs or, for a
+// request it no longer holds, the history of day (the page's ?day=).
+func ctxRouteOf(r *http.Request, id int64) (gateway.Route, bool) {
+ if gw := served.Load(); gw != nil {
+ for _, route := range gw.Trace(r.Context(), 0, 0).Routes {
+ if route.ID == id {
+ return route, true
+ }
+ }
+ }
+ day, err := time.Parse("2006-01-02", r.URL.Query().Get("day"))
+ if err != nil {
+ return gateway.Route{}, false
+ }
+ return gateway.HistoryRoute(id, day)
+}
+
+// archivedCopy is a call as the archive kept it, read from this computer's
+// archive, else the bucket, as the Routing page's archivePanel reads it
+// (openArchive). The last one read is kept, in memory, so the items opened
+// one by one read it once.
+type archivedCopy struct {
+ name string
+ from provider.Protocol
+ request gateway.ArchivePart
+ response gateway.ArchivePart
+}
+
+// lastCallFor is how long the last call read is kept
+const lastCallFor = 5 * time.Minute
+
+var lastCall struct {
+ sync.Mutex
+ c archivedCopy
+}
+
+var errNotArchived = errors.New("not archived")
+
+func readArchived(ctx context.Context, archive string) (archivedCopy, error) {
+ date, id, ok := strings.Cut(archive, "/")
+ if !ok {
+ return archivedCopy{}, errNotArchived
+ }
+ name, ok := gateway.ArchiveName(date, id)
+ if !ok {
+ return archivedCopy{}, errNotArchived
+ }
+ lastCall.Lock()
+ if lastCall.c.name == name {
+ c := lastCall.c
+ lastCall.Unlock()
+ return c, nil
+ }
+ lastCall.Unlock()
+ body, size, err := openArchiveName(ctx, name)
+ if err != nil {
+ return archivedCopy{}, err
+ }
+ defer body.Close()
+ if size > archiveReadMost {
+ return archivedCopy{}, errArchiveCut
+ }
+ data, err := io.ReadAll(io.LimitReader(body, archiveReadMost+1))
+ if err != nil {
+ return archivedCopy{}, err
+ }
+ if len(data) > archiveReadMost {
+ return archivedCopy{}, errArchiveCut
+ }
+ var a gateway.Archived
+ if err := json.Unmarshal(data, &a); err != nil {
+ return archivedCopy{}, errArchiveCut
+ }
+ c := archivedCopy{name: name, from: a.Call.From, request: a.Request, response: a.Response}
+ lastCall.Lock()
+ lastCall.c = c
+ lastCall.Unlock()
+ // let go of it once the card is likely closed: it can be two bodies
+ // of the archive's 32 MiB
+ time.AfterFunc(lastCallFor, func() {
+ lastCall.Lock()
+ if lastCall.c.name == name {
+ lastCall.c = archivedCopy{}
+ }
+ lastCall.Unlock()
+ })
+ return c, nil
+}
+
+var errArchiveCut = errors.New("the archive's copy can't be read whole")
+
+// openArchiveName opens the archive's file name, this computer's first;
+// errNotArchived when neither it nor the bucket has it.
+func openArchiveName(ctx context.Context, name string) (io.ReadCloser, int64, error) {
+ if body, size, err := localArchive().Open(ctx, name); !errors.Is(err, gateway.ErrNotArchived) {
+ return body, size, err
+ }
+ b, ok := archiveBucket()
+ if !ok {
+ return nil, 0, errNotArchived
+ }
+ body, size, err := b.Open(ctx, name)
+ if errors.Is(err, davsync.ErrNoObject) {
+ return nil, 0, errNotArchived
+ }
+ return body, size, err
+}
+
+// archiveGone is the ctxGone of an error reading a route's archive; ""
+// for one the page shows as it is (a bucket that failed to answer: not
+// known to be gone).
+func archiveGone(err error) string {
+ switch {
+ case errors.Is(err, errNotArchived):
+ return "missing"
+ case errors.Is(err, errArchiveCut):
+ return "cut"
+ }
+ return ""
+}
+
+// archivedPromptText answers /api/context/text from the archive, for a
+// request whose body has left memory.
+func archivedPromptText(rw http.ResponseWriter, r *http.Request, id int64, kind string, withText bool) (gateway.PromptText, bool) {
+ route, ok := ctxRouteOf(r, id)
+ if !ok || route.Archive == "" {
+ writeGone(rw, "off")
+ return gateway.PromptText{}, false
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
+ defer cancel()
+ c, err := readArchived(ctx, route.Archive)
+ if err != nil {
+ if why := archiveGone(err); why != "" {
+ writeGone(rw, why)
+ } else {
+ fail(rw, err)
+ }
+ return gateway.PromptText{}, false
+ }
+ if c.request.Truncated {
+ writeGone(rw, "cut")
+ return gateway.PromptText{}, false
+ }
+ tokens := 0
+ if route.Prompt != nil {
+ tokens = route.Prompt.Tokens
+ }
+ pt, ok := gateway.ArchivedPromptText(c.from, []byte(c.request.Body), id, kind, withText, tokens)
+ if !ok {
+ writeGone(rw, "unread")
+ return gateway.PromptText{}, false
+ }
+ return pt, true
+}
+
+// contextReplyAPI serves the reply to a request the card shows: from the
+// gateway's Recent calls while it holds the call, else from the archive.
+func contextReplyAPI(mux *http.ServeMux) {
+ mux.HandleFunc("GET /api/context/reply", func(rw http.ResponseWriter, r *http.Request) {
+ id, err := strconv.ParseInt(r.URL.Query().Get("id"), 10, 64)
+ if err != nil || id <= 0 {
+ http.Error(rw, "invalid route id", http.StatusBadRequest)
+ return
+ }
+ out := gateway.PromptReply{ID: id, From: "memory"}
+ var (
+ from provider.Protocol
+ body []byte
+ cut bool
+ have bool
+ )
+ if gw := served.Load(); gw != nil {
+ from, body, cut, have = gw.ReplyBody(id)
+ }
+ if !have {
+ route, ok := ctxRouteOf(r, id)
+ if !ok || route.Archive == "" {
+ writeGone(rw, "off")
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
+ defer cancel()
+ c, err := readArchived(ctx, route.Archive)
+ if err != nil {
+ if why := archiveGone(err); why != "" {
+ writeGone(rw, why)
+ } else {
+ fail(rw, err)
+ }
+ return
+ }
+ from, body, cut, out.From = c.from, []byte(c.response.Body), c.response.Truncated, "archive"
+ }
+ pieces, cut, ok := gateway.ReplyPieces(from, body, cut)
+ if !ok {
+ writeGone(rw, "unread")
+ return
+ }
+ out.Pieces, out.Cut = pieces, cut
+ rw.Header().Set("Cache-Control", "no-store")
+ writeJSON(rw, out)
+ })
+}
diff --git a/internal/gui/context_archive_test.go b/internal/gui/context_archive_test.go
new file mode 100644
index 000000000..ee4b554b9
--- /dev/null
+++ b/internal/gui/context_archive_test.go
@@ -0,0 +1,107 @@
+package gui
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/gateway"
+ "github.com/yetone/magpie/internal/gwmw"
+ "github.com/yetone/magpie/internal/masking"
+ "github.com/yetone/magpie/internal/provider"
+ "github.com/yetone/magpie/internal/settings"
+)
+
+// wangbinyq on Discord: clicking a block of the context window card said
+// its text was gone, as magpie keeps only the last 10 requests' bodies in
+// memory, with the request archive on. The archive's copy is read instead,
+// the reply beside it, masked as the copy in memory is; a request the
+// archive has no copy of says why.
+func TestContextTextFromTheArchive(t *testing.T) {
+ h := archiveHome(t, fakeArchive{objs: map[string][]byte{}})
+ archiveBucket = func() (archiveStore, bool) { return nil, false }
+ unmask := gwmw.Mask(masking.Masker{})
+ t.Cleanup(unmask)
+ prev := served.Swap(nil)
+ t.Cleanup(func() { served.Store(prev) })
+ if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true, RequestArchiveLocal: true}); err != nil {
+ t.Fatal(err)
+ }
+ lastCall.Lock()
+ lastCall.c = archivedCopy{}
+ lastCall.Unlock()
+
+ const phone = "13800138000"
+ req := `{"model":"m","system":"You are the release agent.","messages":[{"role":"user","content":"call me at ` + phone + ` once it ships"}]}`
+ res := `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"I will call ` + phone + ` when it ships."}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":9}}`
+ obj, _ := json.Marshal(gateway.Archived{ID: "2026-10-02/101010-00000000000000aa", Call: gateway.Call{Model: "p/m", Status: 200, From: provider.Anthropic},
+ Request: gateway.ArchivePart{Method: "POST", Path: "/v1/messages", Body: req, Size: int64(len(req))},
+ Response: gateway.ArchivePart{Status: 200, Body: res, Size: int64(len(res))}})
+ if err := gateway.LocalArchive().Put(context.Background(), archiveObject, obj); err != nil {
+ t.Fatal(err)
+ }
+ day := time.Date(2026, 10, 2, 10, 10, 10, 0, time.Local)
+ route := func(id int64, archive string) []byte {
+ r := ctxRoute(id, "claude", "s1", 3000, 1000, 200000, 0)
+ r.Time, r.Archive = day, archive
+ b, _ := json.Marshal(r)
+ return append(b, '\n')
+ }
+ os.MkdirAll(gateway.HistoryDir(), 0o700)
+ lines := append(route(41, "2026-10-02/101010-00000000000000aa"), route(42, "")...)
+ lines = append(lines, route(43, "2026-10-02/101010-00000000000000bb")...)
+ os.WriteFile(filepath.Join(gateway.HistoryDir(), "2026-10-02.jsonl"), lines, 0o600)
+
+ get := func(url string) (int, string) {
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, httptest.NewRequest("GET", url, nil))
+ return rec.Code, rec.Body.String()
+ }
+ code, body := get("/api/context/text?id=41&kind=chat&item=0&day=2026-10-02")
+ var pt gateway.PromptText
+ json.Unmarshal([]byte(body), &pt)
+ if code != 200 || pt.From != "archive" || len(pt.Items) != 1 || !strings.Contains(body, "once it ships") || strings.Contains(body, phone) {
+ t.Fatalf("text: %d %s", code, body)
+ }
+ if code, body := get("/api/context/text?id=41&kind=system&item=0&day=2026-10-02"); code != 200 || !strings.Contains(body, "You are the release agent.") {
+ t.Fatalf("system: %d %s", code, body)
+ }
+ code, body = get("/api/context/reply?id=41&day=2026-10-02")
+ var rp gateway.PromptReply
+ json.Unmarshal([]byte(body), &rp)
+ if code != 200 || rp.From != "archive" || len(rp.Pieces) != 1 || !strings.Contains(body, "when it ships") || strings.Contains(body, phone) {
+ t.Fatalf("reply: %d %s", code, body)
+ }
+ // no copy named for it: the archive was off
+ for _, url := range []string{"/api/context/text?id=42&kind=chat&day=2026-10-02", "/api/context/reply?id=42&day=2026-10-02", "/api/context/text?id=99&kind=chat"} {
+ if code, body := get(url); code != http.StatusNotFound || !strings.Contains(body, `"archive":"off"`) {
+ t.Fatalf("%s: %d %s", url, code, body)
+ }
+ }
+ // one named and not there
+ if code, body := get("/api/context/text?id=43&kind=chat&day=2026-10-02"); code != http.StatusNotFound || !strings.Contains(body, `"archive":"missing"`) {
+ t.Fatalf("missing: %d %s", code, body)
+ }
+ // with masking wanted and the masker failing, nothing is shown: one
+ // served last serves, whatever another test left registered
+ broken := gwmw.Mask(failingMasker{})
+ defer broken()
+ if code, body := get("/api/context/reply?id=41&day=2026-10-02"); code != http.StatusNotFound || !strings.Contains(body, `"archive":"unread"`) || strings.Contains(body, phone) {
+ t.Fatalf("unmasked: %d %s", code, body)
+ }
+}
+
+// failingMasker is a masker that can't mask: Safely takes its panic as a
+// failure
+type failingMasker struct{}
+
+func (failingMasker) JSON([]byte) ([]byte, int) { panic("can't mask") }
+func (failingMasker) Text(string) (string, int) { panic("can't mask") }
+func (failingMasker) Restore(s string, _ bool) string { return s }
+func (failingMasker) Writer(w http.ResponseWriter) (http.ResponseWriter, func()) { return w, func() {} }
diff --git a/internal/gui/tests/context-map.test.cjs b/internal/gui/tests/context-map.test.cjs
index d90603e30..29455ea7b 100644
--- a/internal/gui/tests/context-map.test.cjs
+++ b/internal/gui/tests/context-map.test.cjs
@@ -230,7 +230,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// an image the request sent inline is shown in its turn; one it
// didn't send that way is named
- await page.evaluate(() => window.openCtxText(19, "chat"));
+ await page.evaluate(() => window.openCtxText({ id: 19 }, "chat"));
await view.locator(".ctx-vi-head").nth(1).click();
const pic = view.locator(".ctx-vi.open .ctx-pic");
await pic.locator("img").waitFor();
diff --git a/internal/gui/tests/context-text.test.cjs b/internal/gui/tests/context-text.test.cjs
index f9426e412..c4b5ec27c 100644
--- a/internal/gui/tests/context-text.test.cjs
+++ b/internal/gui/tests/context-text.test.cjs
@@ -3,7 +3,10 @@
// the request sent there. A part of the legend opens its items, each
// opened to its text; a row or a cell opens its item alone, the part's
// other items a click away; a long text comes a stretch at a time; a
-// request whose text is no longer kept says so. Nothing moves the page,
+// request whose text is no longer kept says so. wangbinyq on Discord: with
+// the request archive on, an older request's text is read from it, and a
+// request's reply opens beside its text, from memory or the archive; one
+// the archive has no copy of says why. Nothing moves the page,
// the keyboard opens it too, in every language, at a desk and a phone's
// width.
const assert = require("node:assert/strict");
@@ -62,11 +65,22 @@ const texts = {
chat: [{ name: "1", tag: "turn", tokens: 300, pieces: [{ role: "user", text: "port the parser" }, { role: "thinking", text: "", size: 900 }, { role: "call", name: "exec_command", text: "{\"cmd\": \"ls\"}" }] },
{ name: "2", tag: "turn", tokens: 500, pieces: [{ role: "image" }, { role: "assistant", text: "Done." }] }],
};
+// 19's in memory, 31's read from the archive; 30's the archive never
+// kept, 32's it named and doesn't have
function text(url, r) {
- if (url.searchParams.get("id") !== "19") return r.fulfill({ status: 404, body: "not kept" });
+ const id = url.searchParams.get("id");
+ if (id === "30") return r.fulfill({ status: 404, json: { archive: "off" } });
+ if (id === "32") return r.fulfill({ status: 404, json: { archive: "missing" } });
+ if (id !== "19" && id !== "31") return r.fulfill({ status: 404, body: "not kept" });
const kind = url.searchParams.get("kind"), item = url.searchParams.get("item");
const items = (texts[kind] || []).map((it, i) => item !== null && +item === i ? it : { ...it, pieces: undefined });
- return r.fulfill({ json: { id: 19, kind, items, kept: 10 } });
+ return r.fulfill({ json: { id: +id, kind, items, kept: 10, ...(id === "31" ? { from: "archive" } : {}) } });
+}
+function reply(url, r) {
+ const id = url.searchParams.get("id");
+ if (id === "30") return r.fulfill({ status: 404, json: { archive: "off" } });
+ const pieces = [{ role: "thinking", text: "Look first." }, { role: "assistant", text: "Ported, call me at [PHONE_1]." }, { role: "call", name: "exec_command", text: "{\"cmd\": \"go test\"}" }];
+ return r.fulfill({ json: { id: +id, pieces, cut: id === "31", from: id === "31" ? "archive" : "memory" } });
}
function serve(lang, asked) {
@@ -78,12 +92,13 @@ function serve(lang, asked) {
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/context") {
- asked.push(url.searchParams.get("days"));
+ asked.push("days=" + url.searchParams.get("days"));
return json(context(+url.searchParams.get("days")));
}
// the text comes a moment after it is asked, as it does under load:
// the dialog says "Reading…" first, and the test waits past it
- if (url.pathname === "/api/context/text") { await new Promise((ok) => setTimeout(ok, 200)); return text(url, r); }
+ if (url.pathname === "/api/context/text") { asked.push("text?" + url.searchParams); await new Promise((ok) => setTimeout(ok, 200)); return text(url, r); }
+ if (url.pathname === "/api/context/reply") { await new Promise((ok) => setTimeout(ok, 200)); return reply(url, r); }
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {});
return json({ mine: true, now: new Date().toISOString(), seq: 0, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
@@ -125,11 +140,11 @@ async function wheelTo(page, l) {
}
const words = {
- en: { tools: "Tools", files: "Files", close: "Close", sys: "System prompt", all: "All of" },
- zh: { tools: "工具", files: "文件", close: "关闭", sys: "系统提示词", all: "全部" },
- "zh-TW": { tools: "工具", files: "檔案", close: "關閉", sys: "系統提示詞", all: "全部" },
- ja: { tools: "ツール", files: "ファイル", close: "閉じる", sys: "システムプロンプト", all: "すべて" },
- de: { tools: "Tools", files: "Dateien", close: "Schließen", sys: "Systemprompt", all: "Alle" },
+ en: { tools: "Tools", files: "Files", close: "Close", sys: "System prompt", all: "All of", reply: "Reply", archive: "request archive" },
+ zh: { tools: "工具", files: "文件", close: "关闭", sys: "系统提示词", all: "全部", reply: "回复", archive: "请求存档" },
+ "zh-TW": { tools: "工具", files: "檔案", close: "關閉", sys: "系統提示詞", all: "全部", reply: "回覆", archive: "請求存檔" },
+ ja: { tools: "ツール", files: "ファイル", close: "閉じる", sys: "システムプロンプト", all: "すべて", reply: "返信", archive: "リクエストアーカイブ" },
+ de: { tools: "Tools", files: "Dateien", close: "Schließen", sys: "Systemprompt", all: "Alle", reply: "Antwort", archive: "Anfragearchiv" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
@@ -219,10 +234,49 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(await view.locator(".ctx-vi.open .ctx-piece-note").count(), 1, "the sealed reasoning is named");
await close();
- // a request whose text is no longer kept says so
- await page.evaluate(() => window.openCtxText(30, "tools"));
+ // the text asks for the request's day, for the archive to find it
+ assert.ok(asked.some((q) => /^text\?id=19&kind=\w+&day=\d{4}-\d\d-\d\d/.test(q)), asked.join(" "));
+
+ // a request's reply beside its text, and back
+ const replyBtn = () => view.locator(".bar button", { hasText: w.reply });
+ await leg.click();
+ await view.locator(".ctx-vi-head").first().waitFor();
+ await replyBtn().click();
+ await view.locator(".ctx-text", { hasText: "Ported, call me at [PHONE_1]." }).waitFor();
+ assert.equal(await view.locator(".ctx-piece").count(), 3);
+ assert.match(await view.locator(".ehead b").innerText(), new RegExp(w.reply));
+ assert.doesNotMatch(await view.locator(".ctx-view-note").first().innerText(), new RegExp(w.archive));
+ await view.locator(".bar button", { hasText: w.tools }).click();
+ await view.locator(".ctx-vi-head", { hasText: "exec_command" }).waitFor();
+ assert.match(await view.locator(".ehead b").innerText(), new RegExp(w.tools));
+ await close();
+
+ // an older request's text from the archive, its reply too, cut short
+ const old = { id: 31, time: ago(60 * 30) };
+ await page.evaluate((r) => window.openCtxText(r, "tools"), old);
+ await view.locator(".ctx-vi-head", { hasText: "exec_command" }).waitFor();
+ assert.match(await view.locator(".ctx-view-note").innerText(), new RegExp(w.archive));
+ await replyBtn().click();
+ await view.locator(".ctx-text", { hasText: "Ported" }).waitFor();
+ assert.equal(await view.locator(".ctx-view-note").count(), 2, "the reply says it is read from the archive, and cut short");
+ assert.match(await view.locator(".ctx-view-note").first().innerText(), new RegExp(w.archive));
+ await close();
+
+ // a request whose text is no longer kept says so, its reply too
+ await page.evaluate(() => window.openCtxText({ id: 30, time: new Date().toISOString() }, "tools"));
await view.locator(".ctx-view-gone").waitFor();
assert.match(await view.locator(".ctx-view-gone").innerText(), /10/);
+ await replyBtn().click();
+ await view.locator(".ctx-view-gone").waitFor();
+ assert.match(await view.locator(".ctx-view-gone").innerText(), /10/);
+ await close();
+
+ // one the archive named and doesn't have says the archive lost it
+ await page.evaluate(() => window.openCtxText({ id: 32, time: new Date().toISOString() }, "tools"));
+ await view.locator(".ctx-view-gone").waitFor();
+ const lost = await view.locator(".ctx-view-gone").innerText();
+ assert.match(lost, new RegExp(w.archive));
+ assert.doesNotMatch(lost, /10/);
await close();
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), "the page scrolls sideways");