From 6d154ef1e1fdad522b88ea617dc2e2f32eeeea38 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 30 Oct 2026 16:00:21 +0800 Subject: [PATCH] =?UTF-8?q?context:=20scripts=20(curl,=20Bun,=20python-htt?= =?UTF-8?q?px=E2=80=A6)=20are=20one=20Scripts=20card,=20not=20an=20agent?= =?UTF-8?q?=20each?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A request whose User-Agent names only an HTTP library or an SDK (curl, Bun, node-fetch, undici, python-httpx, requests, aiohttp, Go-http-client, okhttp, the OpenAI/Anthropic SDKs, …) or nothing at all got a Context scorecard of its own, as if it were an agent (theforeveriris on X: "Bun", "curl", "python-httpx" cards). usage.IsLibrary names those clients; contextOfRecs folds them and "other" into one "Scripts" card at read time, so older history reads the same way, and the card's meta line and tooltip list the libraries by count. The cached day records are not changed. No setting: it works as is. The Usage page's Agents list still shows each library by name, with its Hide and Count-as-agent controls. i18n for zh, zh-TW, ja, de. Existing context.js comments were condensed so TestCoreScriptBudget holds without a raise (core scripts -28 bytes). Run, at this head (rebased on 40af66027): - gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows (mote) for usage and gui; earlier the whole tree on all three, exit 0. - mote: go test -count=1 -tags nogui -timeout 45m ./internal/usage ./internal/gui: ok, ok. - Windows box: context-scripts + i18n-keys 26/26 (chromium, webkit, 5 languages, 360 and 1100px). Before the rebase, every reachable file (context-*, compact-one-value, group-context, routing-context-fold, routing-ctx-fold, routing-ctx-still, i18n-keys, gui-de/ja/zh-tw, header-relang): 333/349; the 16 reds are routing-ctx-still, red the same on origin/main 40af66027 on that box, listed in #4124. Broken by hand: IsLibrary false and no fold -> TestIsLibrary and TestContextScriptsAreOneCard red (cards python-httpx, claude, Bun, ...); the JS label/clients removed -> context-scripts.test.cjs 0/22. Not tried: a real app run with real curl/Bun traffic; Linux WebKitGTK; GUI files on mote (its browsers were busy with another suite). --- docs/subsystems/gui-shell.md | 2 +- internal/gui/assets/context.js | 41 ++++--- internal/gui/assets/i18n.js | 8 ++ internal/gui/context.go | 32 ++++++ internal/gui/context_scripts_test.go | 81 +++++++++++++ internal/gui/tests/context-scripts.test.cjs | 120 ++++++++++++++++++++ internal/usage/usage.go | 28 +++++ internal/usage/usage_test.go | 18 +++ 8 files changed, 307 insertions(+), 23 deletions(-) create mode 100644 internal/gui/context_scripts_test.go create mode 100644 internal/gui/tests/context-scripts.test.cjs diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index d72323850..a0aebf4ea 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -16,7 +16,7 @@ three. | API and assets | `Handler` serves `assets/` (embedded with `//go:embed assets`) and the `/api/*` routes, such as `/api/state`, `/api/set`, `/api/agents/{action}/{id}` and `/api/agents/restart/{id}` (a desktop app's Restart, after the row's confirm). `held` lets one API request's reads share one catalog build (`provider.Hold`), and drops it after any write. `revalidated` and `versionedPage` name each script by its content hash, so a cache never serves an old `app.js` under a new page; a file asked for under its current hash (`?v=`) is cached for good (`immutable`), anything else is revalidated by its ETag. | [`api.go`](../../internal/gui/api.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; 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 (`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) | | 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/gui/assets/context.js b/internal/gui/assets/context.js index d7322baa7..71094f8ac 100644 --- a/internal/gui/assets/context.js +++ b/internal/gui/assets/context.js @@ -40,7 +40,8 @@ return s[s.length >> 1]; }; const agentMeta = (id) => (state.clients || state.agents || []).find((a) => a.id === id); - const agentLabel = (id) => agentMeta(id)?.name || id || t("your agent"); + // "scripts": requests naming only a library (context.go's scriptsAgent) + const agentLabel = (id) => (id === "scripts" ? t("Scripts") : agentMeta(id)?.name || id || t("your agent")); const agentIcon = (id) => icon(agentMeta(id)?.icon || "generic"); // what an item of the prompt is called: a file's path or a tool's name @@ -179,12 +180,10 @@ return box; } - // A card's narrow layouts go by its own width, as container queries - // would, set here as classes (max520: 520px wide or less). Not by - // container queries: WebKit pulled a view scrolled to its end back up by - // a card's height each time the card was drawn again (#1249). A card - // drawn again starts with the width the last one in its place had, so it - // doesn't lay out wide for a moment and pull the page up as it narrows + // Narrow layouts go by the card's own width, as classes (max520), not + // container queries: WebKit pulled a view scrolled to its end up by a + // card's height on each redraw (#1249). A redrawn card starts at the last + // width in its place, so it never lays out wide and pulls the page up const cardWidth = {}; const sizeCard = (card, w) => { card.classList.toggle("max520", w <= 520); @@ -202,12 +201,10 @@ } }); - // morph makes old what neu is, keeping old's nodes wherever they are of - // the same kind: a card drawn again for the next request is patched in - // place, not put in afresh (Zhenzhen on Discord: each live request - // flashed the whole card, its cells coming in again). Handlers set as - // properties come along; one added with addEventListener wouldn't, so - // nothing morphed has one. + // morph makes old what neu is, keeping old's nodes of the same kind: a + // redrawn card is patched in place (Zhenzhen on Discord: each live + // request flashed the whole card). Only handlers set as properties come + // along, so nothing morphed uses addEventListener. const HANDLERS = ["onclick", "onpointerenter", "onpointerleave", "onkeydown"]; function morph(old, neu) { if (old.nodeName !== neu.nodeName || (old.nodeType !== 1 && old.nodeType !== 3)) { old.replaceWith(neu); return neu; } @@ -386,14 +383,12 @@ // ctxCard draws a route's prompt. opts: series (the session's prompts, // [{id, tokens, time}]), onPoint (a point of it clicked), cache ({read, // total}, when the route carries no usage), crumbs (the footer's path), - // place (where it is drawn, for its width: see cardWidth). The card's - // ctxUpdate(r, opts) draws another route, or the same one further on, in - // it: what is the same stays the same nodes, its grid's cells among them, - // so nothing flashes or comes in again and the grid keeps its height - // a card that folds (Routing's, opts.foldable) keeps the reader's - // choice: folded, it is its head alone, with how full the window is - // beside the title, so the request list under it has the room - // (0xBCD18E on X: it took most of the height, three rows were left) + // place (for its width: see cardWidth). The card's ctxUpdate(r, opts) + // draws another route in it, keeping the nodes that are the same (grid + // cells too), so nothing flashes and the grid keeps its height. + // A foldable card (Routing's) keeps the reader's choice: folded, it is its + // head alone with how full the window is, so the request list has room + // (0xBCD18E on X: it took most of the height) let ctxShut = false; try { ctxShut = localStorage.getItem("magpie.ctxShut") === "1"; } catch {} // opts.open: this request was opened to see its context window (the @@ -1185,7 +1180,9 @@ const head = el("div", "ctx-agent-head"); const who = el("div", "ctx-who"); who.append(agentIcon(a.agent), el("b", "", agentLabel(a.agent))); - const meta = el("div", "ctx-who-sub", [count(a.requests, "1 request", "{n} requests"), count(a.sessions, "1 session", "{n} sessions")].join(" · ")); + const cl = a.clients || []; + const meta = el("div", "ctx-who-sub", [...(cl.length ? [cl.slice(0, 3).join(", ") + (cl.length > 3 ? " +" + (cl.length - 3) : "")] : []), count(a.requests, "1 request", "{n} requests"), count(a.sessions, "1 session", "{n} sessions")].join(" · ")); + if (cl.length) who.title = t("Requests whose User-Agent names only an HTTP library or an SDK, not an agent: {clients}", { clients: cl.join(", ") }); const name = el("div", "ctx-who-box"); name.append(who, meta); const [tone, word] = grade(a.score); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 15604804e..5e691abe1 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -216,6 +216,8 @@ const I18N = { "{n} turns": "{n} 轮", "This session": "本会话", "Lean start": "起步轻", + "Scripts": "脚本", + "Requests whose User-Agent names only an HTTP library or an SDK, not an agent: {clients}": "请求的 User-Agent 只写了 HTTP 库或 SDK、没有写是哪个 agent:{clients}", "Pace": "增速", "Reliability": "可靠性", "How much of its prompts the vendor read from its cache: full marks at 90%": "服务商从缓存读取的提示词占比:90% 即满分", @@ -4410,6 +4412,8 @@ const I18N = { "{n} turns": "{n} 輪", "This session": "本會話", "Lean start": "起步輕", + "Scripts": "腳本", + "Requests whose User-Agent names only an HTTP library or an SDK, not an agent: {clients}": "請求的 User-Agent 只寫了 HTTP 函式庫或 SDK、沒有寫是哪個 agent:{clients}", "Pace": "增速", "Reliability": "可靠性", "How much of its prompts the vendor read from its cache: full marks at 90%": "服務商從快取讀取的提示詞占比:90% 即滿分", @@ -8551,6 +8555,8 @@ const I18N = { "{n} turns": "{n} ターン", "This session": "このセッション", "Lean start": "軽いスタート", + "Scripts": "スクリプト", + "Requests whose User-Agent names only an HTTP library or an SDK, not an agent: {clients}": "User-Agent に HTTP ライブラリか SDK の名前しかなく、エージェントを名乗らないリクエスト:{clients}", "Pace": "増え方", "Reliability": "信頼性", "How much of its prompts the vendor read from its cache: full marks at 90%": "ベンダーがキャッシュから読んだプロンプトの割合:90% で満点", @@ -12713,6 +12719,8 @@ const I18N = { "{n} turns": "{n} Runden", "This session": "Diese Sitzung", "Lean start": "Schlanker Start", + "Scripts": "Skripte", + "Requests whose User-Agent names only an HTTP library or an SDK, not an agent: {clients}": "Anfragen, deren User-Agent nur eine HTTP-Bibliothek oder ein SDK nennt, keinen Agenten: {clients}", "Pace": "Tempo", "Reliability": "Zuverlässigkeit", "How much of its prompts the vendor read from its cache: full marks at 90%": "Wie viel seiner Prompts der Anbieter aus dem Cache las: volle Punktzahl ab 90 %", diff --git a/internal/gui/context.go b/internal/gui/context.go index 192f7a5a4..496e6552a 100644 --- a/internal/gui/context.go +++ b/internal/gui/context.go @@ -9,6 +9,7 @@ package gui import ( "fmt" + "maps" "math" "net/http" "os" @@ -22,6 +23,7 @@ import ( "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/sessions" + "github.com/yetone/magpie/internal/usage" ) // defaultWindow is the window a prompt is measured against when the @@ -91,8 +93,19 @@ type ctxAgent struct { Models []string `json:"models"` LatestID int64 `json:"latestId"` LatestTime time.Time `json:"latestTime"` + // Clients are the libraries scriptsAgent's card is of, the most used + // first + Clients []string `json:"clients,omitempty"` } +// scriptsAgent is the card the requests of a script go under: those whose +// User-Agent names only an HTTP library, a runtime or an API SDK +// (usage.IsLibrary: curl, Bun, python-httpx), or nothing at all ("other"). +// Each had a card of its own, scored as an agent's (theforeveriris on X). +// Read from each route's agent as kept, so the history's older days go +// there too; the Usage page's Agents list still has each by its own name. +const scriptsAgent = "scripts" + type ctxJSON struct { Days int `json:"days"` Agents []ctxAgent `json:"agents"` @@ -357,6 +370,17 @@ func contextOfRecs(routes []ctxRec, days int) ctxJSON { return listed } joinConvs(routes, list) + // routes are the tab's copies, so the history kept (ctxKept) keeps + // each route's own agent + scripts := map[string]int{} + for i := range routes { + if a := routes[i].Agent; a == "other" || usage.IsLibrary(a) { + if a != "other" { + scripts[a]++ + } + routes[i].Agent = scriptsAgent + } + } tooled := toolSessions(routes) var order []string for i := range routes { @@ -522,6 +546,14 @@ func contextOfRecs(routes []ctxRec, days int) ctxJSON { if len(a.Models) > 3 { a.Models = a.Models[:3] } + if a.Agent == scriptsAgent { + a.Clients = slices.SortedFunc(maps.Keys(scripts), func(x, y string) int { + if scripts[x] != scripts[y] { + return scripts[y] - scripts[x] + } + return strings.Compare(x, y) + }) + } scoreAgent(a, acc.counted > 0) out.Agents = append(out.Agents, *a) } diff --git a/internal/gui/context_scripts_test.go b/internal/gui/context_scripts_test.go new file mode 100644 index 000000000..798ba8137 --- /dev/null +++ b/internal/gui/context_scripts_test.go @@ -0,0 +1,81 @@ +package gui + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/yetone/magpie/internal/gateway" +) + +// A request whose User-Agent names only an HTTP library, a runtime or an +// SDK is no agent (theforeveriris on X: Bun, curl and python-httpx each +// had an agent's scorecard). The Context tab puts them on one card, +// "scripts", which names them, the most used first; an agent keeps its +// own. Read from the history as it was kept before, so days already on +// disk read the same way, and the days kept for the next refresh keep each +// route's own agent. +func TestContextScriptsAreOneCard(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + mux := keptMux(t) + ctxKept.Lock() + ctxKept.days, ctxKept.key = map[string]ctxDay{}, "" + ctxKept.Unlock() + + now := time.Now() + var b bytes.Buffer + id := int64(0) + add := func(agent, session string, n int) { + for range n { + id++ + r := ctxRoute(id, agent, session, 3000, int(id)*100, 200000, 0) + r.Time = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).Add(time.Duration(id) * time.Second) + j, _ := json.Marshal(r) + b.Write(append(j, '\n')) + } + } + add("python-httpx", "p1", 4) + add("Bun", "b1", 2) + add("curl", "", 1) + add("other", "", 1) + add("OpenAI", "o1", 1) + add("claude", "c1", 3) + dir := gateway.HistoryDir() + os.MkdirAll(dir, 0o700) + os.WriteFile(filepath.Join(dir, now.Format("2006-01-02")+".jsonl"), b.Bytes(), 0o600) + + for round := range 2 { + var out ctxJSON + getJSON(t, mux, "/api/context?days=1", &out) + var ids []string + for _, a := range out.Agents { + ids = append(ids, a.Agent) + } + if !slices.Equal(ids, []string{"scripts", "claude"}) { + t.Fatalf("round %d: cards %v", round, ids) + } + s := out.Agents[0] + if s.Requests != 9 || !slices.Equal(s.Clients, []string{"python-httpx", "Bun", "OpenAI", "curl"}) { + t.Fatalf("round %d: scripts' card %+v", round, s) + } + for _, x := range out.Sessions { + if x.Agent != "scripts" && x.Agent != "claude" { + t.Fatalf("round %d: a session under %q", round, x.Agent) + } + } + } + ctxKept.Lock() + defer ctxKept.Unlock() + for _, d := range ctxKept.days { + for _, r := range d.recs { + if r.Agent == "scripts" { + t.Fatalf("the kept day's route %d lost its own agent", r.ID) + } + } + } +} diff --git a/internal/gui/tests/context-scripts.test.cjs b/internal/gui/tests/context-scripts.test.cjs new file mode 100644 index 000000000..cf36daeab --- /dev/null +++ b/internal/gui/tests/context-scripts.test.cjs @@ -0,0 +1,120 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A request whose User-Agent names only an HTTP library or an SDK (curl, +// Bun, python-httpx) is no agent (theforeveriris on X: each had a +// scorecard of its own). /api/context puts them on one card, "scripts", +// which the Context tab names Scripts and under it the libraries, the +// most used first; the Sessions filter names it so too. In every language, +// in both engines, at a phone's width and a desk's, nothing wider than the +// page. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const now = Date.now(); +const ago = (m) => new Date(now - m * 60000).toISOString(); +const card = (agent, requests, sessions, more = {}) => ({ + agent, requests, sessions, errors: 0, calls: requests, median: 3000, p90: 6000, baseline: 1200, window: 200000, cache: 0, growth: 0, peakFill: 0, compacts: 0, + shares: { system: 0.4, chat: 0.6 }, mcp: 0, score: 65, + scores: [{ key: "cache", points: 0, most: 35 }, { key: "lean", points: 25, most: 25 }, { key: "pace", points: 20, most: 20 }, { key: "reliable", points: 20, most: 20 }], + tags: [], models: ["deepseek-v4"], latestId: 9, latestTime: ago(3), ...more, +}); +const point = (id, m) => ({ id, time: ago(m), tokens: 3000 }); +const context = { + days: 7, + agents: [ + card("scripts", 300, 37, { clients: ["python-httpx", "Bun", "curl", "OpenAI"] }), + card("codex", 20, 1), + ], + sessions: [ + { agent: "scripts", key: "s-httpx", model: "deepseek-v4", first: ago(9), last: ago(3), requests: 2, peak: 3000, window: 200000, latestId: 9, points: [point(8, 9), point(9, 3)] }, + { agent: "codex", key: "s-codex", title: "Port the parser", model: "gpt-5.6", first: ago(20), last: ago(5), requests: 2, peak: 3000, window: 200000, latestId: 7, points: [point(6, 20), point(7, 5)] }, + ], +}; + +function serve(lang) { + const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + 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/tune") return json({ days: 7, agents: [] }); + if (url.pathname === "/api/context") return json(context); + 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: [] }); + } + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await r.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType, status: 200 }); + }; +} + +const name = { en: "Scripts", zh: "脚本", "zh-TW": "腳本", ja: "スクリプト", de: "Skripte" }; +const why = { + en: "Requests whose User-Agent names only an HTTP library or an SDK, not an agent: python-httpx, Bun, curl, OpenAI", + zh: "请求的 User-Agent 只写了 HTTP 库或 SDK、没有写是哪个 agent:python-httpx, Bun, curl, OpenAI", + "zh-TW": "請求的 User-Agent 只寫了 HTTP 函式庫或 SDK、沒有寫是哪個 agent:python-httpx, Bun, curl, OpenAI", + ja: "User-Agent に HTTP ライブラリか SDK の名前しかなく、エージェントを名乗らないリクエスト:python-httpx, Bun, curl, OpenAI", + de: "Anfragen, deren User-Agent nur eine HTTP-Bibliothek oder ein SDK nennt, keinen Agenten: python-httpx, Bun, curl, OpenAI", +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: scripts are one card, named Scripts, not an agent each`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + }); + for (const lang of Object.keys(name)) for (const [width, height] of [[360, 760], [1100, 760]]) { + await t.test(`${lang}, ${width}x${height}`, async () => { + const ctx = await browser.newContext({ viewport: { width, height }, reducedMotion: "reduce" }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.usageTab", "context"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/?view=usage"); + const cards = page.locator(".ctx-agents:not(.ctx-tunes) .ctx-agent"); + await cards.nth(1).waitFor(); + assert.equal(await cards.count(), 2); + const s = cards.nth(0); + assert.equal(await s.locator(".ctx-who b").textContent(), name[lang]); + assert.equal(await s.locator(".ctx-who").getAttribute("title"), why[lang]); + assert.match(await s.locator(".ctx-who-sub").textContent(), /^python-httpx, Bun, curl \+1 · /); + // an agent's card names no clients; its name comes with the state, + // which can answer after the history + await cards.nth(1).locator(".ctx-who b", { hasText: /^Codex$/ }).waitFor(); + assert.doesNotMatch(await cards.nth(1).locator(".ctx-who-sub").textContent(), /,/); + // the Sessions filter names the scripts' sessions as the card does + assert.equal(await page.locator(".ctx-sess-head button.opt").filter({ hasText: name[lang] }).count(), 1); + + const over = await page.evaluate(() => { + const out = []; + const view = document.querySelector("#view-usage"); + if (view.scrollWidth > view.clientWidth + 1) out.push("page " + view.scrollWidth + ">" + view.clientWidth); + const c = document.querySelector(".ctx-agent"); + const b = c.getBoundingClientRect(); + for (const e of c.querySelectorAll(".ctx-agent-head *")) { + const r = e.getBoundingClientRect(); + if (r.width && (r.right > b.right + 1 || r.left < b.left - 1)) out.push((e.className.baseVal ?? e.className) + " " + Math.round(r.left) + "–" + Math.round(r.right) + " of " + Math.round(b.left) + "–" + Math.round(b.right)); + } + return out; + }); + assert.deepEqual(over, []); + await ctx.close(); + }); + } + assert.deepEqual(errors, []); + }); +} diff --git a/internal/usage/usage.go b/internal/usage/usage.go index 491afc57e..7adc9e7a2 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -418,6 +418,34 @@ func IsAgent(id string) bool { return slices.ContainsFunc(knownAgents(), func(k Known) bool { return k.ID == id || slices.Contains(k.Names, id) }) } +// libraries are the product names of HTTP libraries, runtimes and API +// SDKs as AgentOf names a client by its User-Agent, lower-cased. A +// request that says only one of these is from a script, or from a tool +// built on the library, and says nothing of which: it is no agent of its +// own (theforeveriris on X: Bun, curl and python-httpx each had an +// agent's scorecard on the Context tab). +var libraries = map[string]bool{ + // command lines and API tools + "curl": true, "wget": true, "httpie": true, "postmanruntime": true, "insomnia": true, + // JavaScript + "bun": true, "node": true, "deno": true, "node-fetch": true, "undici": true, "axios": true, "got": true, "ky": true, + // Python + "python": true, "python-httpx": true, "httpx": true, "python-requests": true, "requests": true, + "python-urllib": true, "urllib3": true, "aiohttp": true, + // Go, JVM, Ruby, PHP, Dart, Rust + "go-http-client": true, "go-resty": true, "resty": true, "okhttp": true, "java": true, "java-http-client": true, + "apache-httpclient": true, "reactor-netty": true, "ruby": true, "faraday": true, "rest-client": true, + "guzzlehttp": true, "dart": true, "reqwest": true, "libcurl": true, + // the vendors' SDKs, which an app or a script calls a model with + "openai": true, "asyncopenai": true, "anthropic": true, "asyncanthropic": true, "ai-sdk": true, "google-genai-sdk": true, +} + +// IsLibrary says whether a client, by the name AgentOf gives it (a +// record's Agent, old records' too), is an HTTP library, a runtime or an +// API SDK rather than an agent: curl, Bun, python-httpx, Go-http-client, +// OpenAI/Python. +func IsLibrary(id string) bool { return libraries[strings.ToLower(strings.TrimSpace(id))] } + // AgentOf names the agent behind a client User-Agent. Known agents map to // their magpie id; anything else keeps its product name. func AgentOf(ua string) string { diff --git a/internal/usage/usage_test.go b/internal/usage/usage_test.go index f694907fa..fb3121cc1 100644 --- a/internal/usage/usage_test.go +++ b/internal/usage/usage_test.go @@ -311,3 +311,21 @@ func TestSawIsLastSeen(t *testing.T) { t.Fatalf("after a request: %v", at) } } + +// A client named by an HTTP library, a runtime or an SDK is no agent +// (theforeveriris on X), as AgentOf names it from its User-Agent; an +// agent's or an app's own name is not one. +func TestIsLibrary(t *testing.T) { + for _, ua := range []string{"curl/8.7.1", "Bun/1.4.2", "python-httpx/0.28.1", "Go-http-client/1.1", "node-fetch/1.0", + "undici", "axios/1.7.2", "okhttp/4.12.0", "python-requests/2.32.3", "Python/3.12 aiohttp/3.10.5", + "OpenAI/Python 1.54.0", "AsyncOpenAI/Python 1.54.0", "Anthropic/JS 0.32.1"} { + if a := AgentOf(ua); !IsLibrary(a) { + t.Errorf("%q (%q) is not a library", ua, a) + } + } + for _, ua := range []string{"SillyTavern/1.12", "MyApp/2.0 (Linux)", "Mozilla/5.0 (Macintosh)", ""} { + if a := AgentOf(ua); IsLibrary(a) { + t.Errorf("%q (%q) is a library", ua, a) + } + } +}