diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 7ecad9687..0c3ccff0e 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`. The cookie is SameSite=Lax, which a browser sends with any request from the same site, other ports and sibling subdomains included, so `webOwnPage` answers `/api` for the page's own origin only: a write goes through net/http's `CrossOriginProtection` (Sec-Fetch-Site same-origin or none; from a browser without it, an Origin that is absent or names the Host or `MAGPIE_PUBLIC_URL`), and any request whose Sec-Fetch-Site says another origin sent it is refused, a GET too; see `TestWebAPIAnswersItsOwnPageOnly`. The desktop window's `/api` is in-process with no cookie and isn't held to it. Gateway mode shows every page but Agents on a machine that is only a gateway (`GATEWAY_HIDES`); the Library has its MCP servers and the MCP router alone, for other computers' apps to reach with a gateway key (treeman_26897 on Discord, `gateway-mode.test.cjs`, `library-mcp-agentless.test.cjs`). `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, 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) | +| 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; a session's details on the Sessions page and Usage's Sessions list draw a Context line of its requests from `/api/context/session`, which reads only the days from its first to its last (30 at most) and keeps that one session, so the tab's 80-session cap never leaves it out (`sessCtxLine` in `plugins/usage/page.js`, liang_yongxiang on Discord, `context_session_test.go`, `sessions-context-line.test.cjs`); 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`, with *Never mask* and *Masked words* drawn a value a row by `wordList` in `plugins/redact/settings.js`, saved as the same list of strings the one comma-separated box saved, `redact-words-list.test.cjs`), *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.css b/internal/gui/assets/context.css index 43db65640..448fc654f 100644 --- a/internal/gui/assets/context.css +++ b/internal/gui/assets/context.css @@ -431,3 +431,7 @@ i.dot.free { background: var(--k-free); box-shadow: inset 0 0 0 1px color-mix(in .ctx-pic.open { cursor: zoom-out; } .ctx-pic.open img { max-width: 100%; max-height: none; } @media (prefers-reduced-motion: reduce) { .ctx-pic { transition: none; } } + +/* a session's line in its details (Sessions page, Usage's Sessions list) */ +.sess-ctx .ctx-line { display: flex; align-items: center; gap: 10px; flex: 1 1 auto; min-width: 0; max-width: 320px; font-variant-numeric: tabular-nums; } +.sess-ctx .ctx-spark { flex: 1; min-width: 72px; height: 22px; } diff --git a/internal/gui/assets/context.js b/internal/gui/assets/context.js index 337fa9afd..d5b0bdf6e 100644 --- a/internal/gui/assets/context.js +++ b/internal/gui/assets/context.js @@ -143,16 +143,12 @@ return g > 0 ? Math.floor(free / g) : null; } - // count words a number with the phrase for one, or for many const count = (n, one, many) => n === 1 ? t(one) : t(many, { n }); - // spark draws a session's prompts, request by request, against its - // window; the one the card tells of is marked, and a point clicked opens - // its request + // a session's prompts against its window; a point opens its request function spark(series, at, window, onPoint) { const W = 240, H = 34, pad = 3; - // scaled to the session's peak, so a session that never came near its - // window still shows how it grew; the window's line shows once it is near + // scaled to its peak; the window's line shows once it is near const peak = Math.max(...series.map((p) => p.tokens), 1); const top = window && peak > window * 0.6 ? Math.max(window, peak) : peak * 1.2; const x = (i) => series.length < 2 ? W / 2 : pad + (i / (series.length - 1)) * (W - pad * 2); @@ -186,7 +182,9 @@ if (!onPoint) return; const hit = ns("rect", { x: x(i) - Math.max(2, W / series.length / 2), y: 0, width: Math.max(4, W / series.length), height: H, class: "hit" + (on ? " on" : "") }); const tip = document.createElementNS("http://www.w3.org/2000/svg", "title"); - tip.textContent = t("Request {n}: {tokens} tokens", { n: i + 1, tokens: fmtK(p.tokens) }); + const w = p.window || window; + tip.textContent = w ? t("Request {n}: {tokens} of {window} ({pct})", { n: i + 1, tokens: fmtK(p.tokens), window: fmtK(w), pct: pct(p.tokens / w) }) + : t("Request {n}: {tokens} tokens", { n: i + 1, tokens: fmtK(p.tokens) }); hit.append(tip); hit.onclick = (e) => { e.stopPropagation(); onPoint(p); }; }); @@ -1159,6 +1157,8 @@ return box; } + window.ctxSpark = spark; + window.ctxHealth = health; // ---------- tuned for you: the settings that would have spent the fewest tokens ---------- diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index fb1659307..d69842b3f 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -296,6 +296,7 @@ const I18N = { "Filling up": "渐满", "Near full": "将满", "Request {n}: {tokens} tokens": "第 {n} 个请求:{tokens} token", + "Request {n}: {tokens} of {window} ({pct})": "第 {n} 个请求:{tokens} / {window}({pct})", "Counted": "已计数", "Estimated": "估算", "The request is on its way: the prompt is estimated from what the agent sent": "请求进行中:提示词按 agent 发送的内容估算", @@ -5059,6 +5060,7 @@ const I18N = { "Filling up": "漸滿", "Near full": "將滿", "Request {n}: {tokens} tokens": "第 {n} 個請求:{tokens} token", + "Request {n}: {tokens} of {window} ({pct})": "第 {n} 個請求:{tokens} / {window}({pct})", "Counted": "已計數", "Estimated": "預估", "The request is on its way: the prompt is estimated from what the agent sent": "請求進行中:提示詞依 agent 送出的內容預估", @@ -9769,6 +9771,7 @@ const I18N = { "Filling up": "埋まりつつある", "Near full": "ほぼ満杯", "Request {n}: {tokens} tokens": "リクエスト {n}:{tokens} トークン", + "Request {n}: {tokens} of {window} ({pct})": "リクエスト {n}:{tokens} / {window}({pct})", "Counted": "カウント済み", "Estimated": "推定", "The request is on its way: the prompt is estimated from what the agent sent": "リクエスト送信中:プロンプトはエージェントが送った内容から推定しています", @@ -14500,6 +14503,7 @@ const I18N = { "Filling up": "Füllt sich", "Near full": "Fast voll", "Request {n}: {tokens} tokens": "Anfrage {n}: {tokens} Token", + "Request {n}: {tokens} of {window} ({pct})": "Anfrage {n}: {tokens} von {window} ({pct})", "Counted": "Gezählt", "Estimated": "Geschätzt", "The request is on its way: the prompt is estimated from what the agent sent": "Die Anfrage läuft noch: Der Prompt ist aus dem geschätzt, was der Agent gesendet hat", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index f241829b1..699cd2768 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -2798,6 +2798,44 @@ function sessModelsText(s) { return sessModelNames(s.models.slice(0, 2).map((m) => m.model)) + (s.models.length > 2 ? " +" + (s.models.length - 2) : "") + (via ? " " + via : ""); } +// A session's line in its details, on the Sessions page and in the Usage +// page's Sessions list (liang_yongxiang on Discord: Routing tells how full +// one request's window was, the Sessions page told it of no turn): its +// prompts request by request against its window, drawn as the Context tab +// draws its sessions (context.js), and the fullest one's share. A point +// opens its request in Routing, with its card. Asked of the server for a +// session the gateway sent calls of (s.via) when its details are drawn, +// kept a while so a redraw draws it at once; shown(false) when the gateway +// kept none of its prompts. +const sessCtxLines = new Map(); // agent/id -> { at, c, wait } +const SESS_CTX_AGAIN = 30000; +function sessCtxLine(s, shown) { + const box = el("span", "ctx-line"); + const k = s.agent + "/" + s.id; + const draw = (c) => { + if (!c?.points?.length) { shown(false); return; } + const fmtK = window.ctxFmt, fill = c.window ? c.peak / c.window : 0; + const [tone] = window.ctxHealth(fill); + const peak = el("span", "ctx-sess-peak " + tone, c.window ? Math.round(fill * 100) + "%" : fmtK(c.peak)); + peak.dataset.tt = t("Its largest prompt: {tokens} of {window}", { tokens: fmtK(c.peak), window: fmtK(c.window) }); + box.replaceChildren(window.ctxSpark(c.points, c.latestId, c.window, (pt) => { + if (!featuresOff.has("routing")) window.openRoute(pt.id, pt.time, { context: true }).catch(statusErr); + }), peak); + shown(true); + }; + let got = sessCtxLines.get(k); + if (got?.c !== undefined) draw(got.c); + else shown(false); + if (!got || (!got.wait && Date.now() - got.at > SESS_CTX_AGAIN)) { + got = { at: Date.now(), c: got?.c, wait: null }; + const q = new URLSearchParams({ agent: s.agent, id: s.id, from: s.start || s.last || "", to: s.last || "" }); + got.wait = api("context/session?" + q).then((d) => { got.c = d?.session || null; }, () => {}).finally(() => { got.wait = null; got.at = Date.now(); }); + sessCtxLines.set(k, got); + } + got.wait?.then(() => { if (box.isConnected) draw(got.c); }); + return box; +} + // sessUsageDetail adds to a session's details what it spent by model, and // what the gateway sent its calls to, at what reasoning; line(label, value) // adds a line of the details @@ -2812,6 +2850,12 @@ function sessUsageDetail(d, s, line) { d.append(m); } (s.via || []).forEach((v, i) => line(i ? "" : t("Routed"), viaText(v) + " · " + t("{n} tokens", { n: fmtN(v.tokens) }) + (v.credited ? " · " + ledCredits(v).textContent : ""))); + // how full its context was, request by request + if (s.via?.length && window.ctxSpark) { + const l = el("div", "sess-line sess-ctx"); + l.append(el("span", "k", t("Context")), sessCtxLine(s, (on) => { l.hidden = !on; })); + d.append(l); + } } // one place a session's calls went through magpie, in words diff --git a/internal/gui/context.go b/internal/gui/context.go index b0eb2d1ad..8655e611a 100644 --- a/internal/gui/context.go +++ b/internal/gui/context.go @@ -121,6 +121,8 @@ type ctxJSON struct { const ( ctxSessions = 80 ctxPoints = 160 + // ctxSessionPoints is how many a session's own line keeps, the latest + ctxSessionPoints = 1000 ) func median(xs []int) int { @@ -498,6 +500,13 @@ func contextOf(routes []gateway.Route, days int) ctxJSON { // contextOfRecs is contextOf of the routes as the tab reads them. func contextOfRecs(routes []ctxRec, days int) ctxJSON { + return contextOfRecsFor(routes, days, "") +} + +// contextOfRecsFor is contextOfRecs, and when only isn't "" it lists that +// one session alone (agent + "\x00" + its id), with up to ctxSessionPoints +// of its requests: a session's line on the Sessions page. +func contextOfRecsFor(routes []ctxRec, days int, only string) ctxJSON { sort.SliceStable(routes, func(i, j int) bool { return routes[i].Time.Before(routes[j].Time) }) out := ctxJSON{Days: days, Agents: []ctxAgent{}, Sessions: []ctxSession{}} type agentAcc struct { @@ -615,14 +624,21 @@ func contextOfRecs(routes []ctxRec, days int) ctxJSON { // the sessions, the latest first slices.SortFunc(order, func(a, b string) int { return sess[b].Last.Compare(sess[a].Last) }) var codexIDs, desktopIDs, piIDs []string + keep := ctxPoints + if only != "" { + keep = ctxSessionPoints + } for _, sk := range order { s := sess[sk] + if only != "" && sk != only { + continue + } if acc := agents[s.Agent]; acc != nil && s.Requests > 1 { acc.fills = append(acc.fills, float64(s.Peak)/float64(s.Window)) } if len(out.Sessions) < ctxSessions { - if len(s.Points) > ctxPoints { - s.Points = s.Points[len(s.Points)-ctxPoints:] + if len(s.Points) > keep { + s.Points = s.Points[len(s.Points)-keep:] } out.Sessions = append(out.Sessions, *s) switch s.Agent { @@ -858,13 +874,33 @@ func contextRecs(r *http.Request, days int) (out []ctxRec, stamp string) { } func contextRecsLocked(r *http.Request, days int) (out []ctxRec, stamp string) { - seen := map[int64]bool{} now := time.Now() - var key strings.Builder - asked := map[string]bool{} + list := make([]string, 0, days) for i := days - 1; i >= 0; i-- { - day := now.AddDate(0, 0, -i).Format("2006-01-02") + list = append(list, now.AddDate(0, 0, -i).Format("2006-01-02")) + } + out, stamp = daysRecsLocked(r, list) + // a day out of the range is let go; the range's days are kept for the + // next refresh + asked := map[string]bool{} + for _, day := range list { asked[day] = true + } + for day := range ctxKept.days { + if !asked[day] { + delete(ctxKept.days, day) + } + } + return out, stamp +} + +// daysRecsLocked reads the routes of the days listed, from what is kept +// of them when their files are as they were, and the live trace's not yet +// in the history. +func daysRecsLocked(r *http.Request, list []string) (out []ctxRec, stamp string) { + seen := map[int64]bool{} + var key strings.Builder + for _, day := range list { st := dayStamp(day) fmt.Fprintf(&key, "%s=%s", day, st) d, ok := ctxKept.days[day] @@ -883,13 +919,6 @@ func contextRecsLocked(r *http.Request, days int) (out []ctxRec, stamp string) { } } } - // a day out of the range is let go; the range's days are kept for the - // next refresh - for day := range ctxKept.days { - if !asked[day] { - delete(ctxKept.days, day) - } - } if gw := served.Load(); gw != nil { for _, x := range gw.Trace(r.Context(), 0, 0).Routes { if x.Done && !seen[x.ID] { @@ -907,6 +936,46 @@ func contextRecsLocked(r *http.Request, days int) (out []ctxRec, stamp string) { return out, key.String() } +// ctxSessionDays is how far back a session's line reads: the Usage page's +// Context tab's longest range +const ctxSessionDays = 30 + +// contextSession is one agent's session as the Context tab counts it, +// every request of it the gateway saw from the day of from to the day of +// to (the session's first and last, as the Sessions page has them), read +// within the last ctxSessionDays days; nil when the gateway saw none. +// The days read stay kept until the tab's next read lets go of those +// out of its range. +func contextSession(r *http.Request, agent, id string, from, to time.Time) *ctxSession { + now := time.Now() + oldest := now.AddDate(0, 0, -(ctxSessionDays - 1)) + if from.IsZero() || from.Before(oldest) { + from = oldest + } + if to.IsZero() || to.After(now) { + to = now + } + // day by day at noon, which a change of clocks never moves to another day + y, m, dd := from.Local().Date() + last := to.Local().Format("2006-01-02") + var list []string + for d := time.Date(y, m, dd, 12, 0, 0, 0, time.Local); len(list) < ctxSessionDays; d = d.AddDate(0, 0, 1) { + day := d.Format("2006-01-02") + list = append(list, day) + if day >= last { + break + } + } + ctxKept.Lock() + recs, _ := daysRecsLocked(r, list) + ctxKept.Unlock() + out := contextOfRecsFor(recs, len(list), agent+"\x00"+id) + if len(out.Sessions) == 0 { + return nil + } + return &out.Sessions[0] +} + // contextFor is the tab's answer for the days asked for: the last one // again when its routes are the same and it isn't ctxAgain old, or // ctxWhileUnmatched old when it left a route out of every session. @@ -928,6 +997,20 @@ func contextFor(r *http.Request, days int) ctxJSON { } func contextRoutesAPI(mux *http.ServeMux) { + // one session's prompts, request by request, against its window: the + // line the Sessions page draws in a session's details (liang_yongxiang + // on Discord). from and to are its first and last, RFC 3339. + mux.HandleFunc("GET /api/context/session", func(rw http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + agent, id := q.Get("agent"), q.Get("id") + if agent == "" || id == "" { + http.Error(rw, "agent and id are needed", http.StatusBadRequest) + return + } + from, _ := time.Parse(time.RFC3339, q.Get("from")) + to, _ := time.Parse(time.RFC3339, q.Get("to")) + writeJSON(rw, map[string]any{"session": contextSession(r, agent, id, from, to)}) + }) mux.HandleFunc("GET /api/context", func(rw http.ResponseWriter, r *http.Request) { days, _ := strconv.Atoi(r.URL.Query().Get("days")) if days <= 0 || days > 30 { diff --git a/internal/gui/context_session_test.go b/internal/gui/context_session_test.go new file mode 100644 index 000000000..bc9bbb3af --- /dev/null +++ b/internal/gui/context_session_test.go @@ -0,0 +1,118 @@ +package gui + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "testing" + "time" + + "github.com/yetone/magpie/internal/gateway" +) + +// A session's details on the Sessions page show how full its context was, +// request by request (liang_yongxiang on Discord: Routing told it for one +// request, the Sessions page not at all). /api/context/session answers one +// session's line: each of its requests the gateway saw, oldest first, over +// every day from its first to its last and none outside them, however many +// other sessions there were since (the Context tab lists the latest 80 and +// would leave it out), and with neither a subagent's prompt nor another +// agent's session of the same id in it. +func TestContextSessionLine(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() + reads := map[string]bool{} + readingDay = func(day string) { reads[day] = true } + t.Cleanup(func() { readingDay = nil }) + + dir := gateway.HistoryDir() + os.MkdirAll(dir, 0o700) + now := time.Now() + dayOf := func(back int) time.Time { + d := now.AddDate(0, 0, -back) + return time.Date(d.Year(), d.Month(), d.Day(), 9, 0, 0, 0, time.Local) + } + files := map[string]*bytes.Buffer{} + id := int64(0) + add := func(back int, agent, session string, chat int, edit func(*gateway.Route)) time.Time { + id++ + r := ctxRoute(id, agent, session, 20000, chat, 200000, 0) + r.Time = dayOf(back).Add(time.Duration(id) * time.Second) + if edit != nil { + edit(&r) + } + day := r.Time.Format("2006-01-02") + if files[day] == nil { + files[day] = &bytes.Buffer{} + } + j, _ := json.Marshal(r) + files[day].Write(append(j, '\n')) + return r.Time + } + // a request of another session four days ago, outside the session's days + add(4, "claude", "older", 1000, nil) + first := add(3, "claude", "s1", 10000, nil) + add(3, "claude", "s1", 30000, func(r *gateway.Route) { r.Sub = "explore" }) + add(2, "claude", "s1", 60000, nil) + add(2, "codex", "s1", 90000, nil) + last := add(1, "claude", "s1", 140000, nil) + // 100 sessions since, on its last day after it + for i := range 100 { + add(1, "claude", fmt.Sprint("later-", i), 1000, nil) + } + for day, b := range files { + os.WriteFile(filepath.Join(dir, day+".jsonl"), b.Bytes(), 0o600) + } + + ask := func(agent, sid string, from, to time.Time) *ctxSession { + t.Helper() + var got struct { + Session *ctxSession `json:"session"` + } + q := url.Values{"agent": {agent}, "id": {sid}, "from": {from.UTC().Format(time.RFC3339Nano)}, "to": {to.UTC().Format(time.RFC3339Nano)}} + getJSON(t, mux, "/api/context/session?"+q.Encode(), &got) + return got.Session + } + s := ask("claude", "s1", first, last) + if s == nil { + t.Fatal("no line for a session the gateway saw") + } + var tokens []int + for _, p := range s.Points { + tokens = append(tokens, p.Tokens) + } + if fmt.Sprint(tokens) != "[30000 80000 160000]" { + t.Fatalf("its requests' prompts: %v, want [30000 80000 160000]", tokens) + } + if s.Window != 200000 || s.Peak != 160000 || s.Requests != 3 || s.Agent != "claude" || s.Key != "s1" { + t.Fatalf("session: %+v", s) + } + if reads[dayOf(4).Format("2006-01-02")] || reads[dayOf(0).Format("2006-01-02")] { + t.Fatalf("read days outside the session's: %v", reads) + } + if !reads[dayOf(3).Format("2006-01-02")] || !reads[dayOf(1).Format("2006-01-02")] { + t.Fatalf("didn't read the session's days: %v", reads) + } + + // the same id under another agent is that agent's own + if c := ask("codex", "s1", first, last); c == nil || len(c.Points) != 1 || c.Points[0].Tokens != 110000 { + t.Fatalf("codex's s1: %+v", c) + } + // a session the gateway never saw has no line + if n := ask("claude", "nobody", first, last); n != nil { + t.Fatalf("a session never seen: %+v", n) + } + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest("GET", "/api/context/session?agent=claude", nil)) + if rec.Code != 400 { + t.Fatalf("no id: %d", rec.Code) + } +} diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 890241b1a..853b0d41a 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -849,6 +849,15 @@ Chromium and WebKit, in English, Chinese, Japanese and German, at 1100px and 420px. With the state answering after the history, the cards drawn by the agents' ids take their names once it is in, though the history is the same. +`sessions-context-line.test.cjs` opens a session's details on the Sessions +page (liang_yongxiang on Discord): one the gateway sent calls of asks +`/api/context/session` once, with its first and last, and draws a Context +line, a point a request telling its share of the window and the fullest +share beside it, toned; a point clicked opens that request in Routing with +its card; one the gateway kept no prompt of, or never saw, has no line, and +the second isn't asked; opened again it is drawn without asking — in +Chromium and WebKit, in all five languages, at 1100px and 420px. + `tray-usages.test.cjs` picks several of the Usage page's cards for the menu bar in Settings: the menu keeps open as Codex and Claude Code are ticked beside Copilot, posts nothing till it closes and then the three once, in the diff --git a/internal/gui/tests/sessions-context-line.test.cjs b/internal/gui/tests/sessions-context-line.test.cjs new file mode 100644 index 000000000..98a139ae3 --- /dev/null +++ b/internal/gui/tests/sessions-context-line.test.cjs @@ -0,0 +1,158 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A session's details on the Sessions page say how full its context was, +// request by request (liang_yongxiang on Discord: Routing told it for one +// request, the Sessions page for none). A session the gateway sent calls of +// (via) asks /api/context/session for its line once, with its first and +// last, and draws the Context tab's line of it: a point a request, each +// telling its share of the window, and the fullest one's share beside it. +// A point clicked opens that request in Routing, with its card. A session +// the gateway never saw asks nothing and has no Context line, and one it +// kept no prompt of has none either. Opened again, the line is drawn at +// once, not asked again. In five languages, Chromium and WebKit, at 1100 +// and 420 wide. +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 at = (min) => new Date(Date.now() - min * 60e3).toISOString(); +const VIA = [{ provider: "anthropic", model: "claude-sonnet-5", calls: 3, tokens: 270000 }]; +const POINTS = [ + { id: 11, time: at(30), tokens: 30000, window: 200000 }, + { id: 12, time: at(20), tokens: 80000, window: 200000 }, + { id: 13, time: at(10), tokens: 160000, window: 200000 }, +]; + +function serve(lang, asked) { + const base = { agent: "claude", cwd: "/work/c", models: [{ model: "claude-sonnet-5", input: 270000, output: 9000 }], size: 4096, messages: 6, files: 1, deletable: true }; + const sessions = [ + { ...base, id: "seen-1", title: "Seen by the gateway", start: at(40), last: at(10), via: VIA }, + { ...base, id: "kept-none", title: "Nothing kept", start: at(50), last: at(45), via: VIA }, + { ...base, id: "own-only", title: "Never through magpie", start: at(60), last: at(55) }, + ]; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/sessions/manage") { + return json({ agents: [{ agent: "claude", count: sessions.length, deletable: true, name: "Claude Code", icon: "claude" }], + agent: "claude", sessions, terminal: true, trash: [], trashDir: "~/trash" }); + } + if (url.pathname === "/api/context/session") { + const q = Object.fromEntries(url.searchParams); + asked.push(q); + if (q.id !== "seen-1") return json({ session: null }); + return json({ session: { agent: "claude", key: "seen-1", model: "claude-sonnet-5", first: POINTS[0].time, last: POINTS[2].time, + requests: 3, peak: 160000, window: 200000, latestId: 13, points: POINTS } }); + } + 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)]; + const body = await fs.readFile(file).catch(() => null); + await (body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404 })); + }; +} + +const NAV = { en: "Sessions", zh: "会话", "zh-TW": "工作階段", ja: "セッション", de: "Sitzungen" }; +const CONTEXT = { en: "Context", zh: "上下文", "zh-TW": "上下文", ja: "コンテキスト", de: "Kontext" }; +const TIP = { + en: "Request 2: 80K of 200K (40%)", + zh: "第 2 个请求:80K / 200K(40%)", + "zh-TW": "第 2 個請求:80K / 200K(40%)", + ja: "リクエスト 2:80K / 200K(40%)", + de: "Anfrage 2: 80K von 200K (40%)", +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}: a session's details show how full its context was, request by request`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-sessions-context-line.png`) }); + } + await browser.close(); + }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const asked = []; + await page.route("**/*", serve(lang, asked)); + await page.goto("http://magpie.test/?view=sessions"); + const view = page.locator("#view-sessions"); + if (!(await view.isVisible())) { + const nav = page.locator("#nav").getByRole("button", { name: NAV[lang], exact: true }); + if (await nav.count()) await nav.click(); + } + const open = async (id) => { + const row = view.locator(`.row.sm-sess[data-id="${id}"]`); + await row.waitFor(); + await row.locator(".who").click(); + const item = row.locator("xpath=.."); + await item.locator(".sess-detail").waitFor(); + return item.locator(".sess-detail"); + }; + + // the session the gateway saw + let detail = await open("seen-1"); + const line = detail.locator(".sess-line.sess-ctx"); + await line.locator(".ctx-spark svg").waitFor(); + assert.equal(await line.locator(".k").textContent(), CONTEXT[lang]); + assert.equal(asked.length, 1); + assert.equal(asked[0].agent, "claude"); + assert.equal(asked[0].id, "seen-1"); + assert.ok(asked[0].from && asked[0].to && Date.parse(asked[0].from) < Date.parse(asked[0].to), `its first and last: ${JSON.stringify(asked[0])}`); + const hits = line.locator(".ctx-spark rect.hit"); + assert.equal(await hits.count(), POINTS.length, "a point a request"); + assert.equal(await hits.nth(1).locator("title").textContent(), TIP[lang]); + const peak = line.locator(".ctx-sess-peak"); + assert.equal(await peak.textContent(), "80%"); + assert.match(await peak.getAttribute("class"), /\bwarn\b/); + + // inside the details, and the page never scrolls sideways + const box = await line.evaluate((l) => { + const r = l.getBoundingClientRect(), d = l.closest(".sess-detail").getBoundingClientRect(); + const s = l.querySelector(".ctx-spark").getBoundingClientRect(); + return { inside: r.right <= d.right + 0.5, spark: s.width, h: s.height }; + }); + assert.ok(box.inside, `the line stays inside the details at ${width}: ${JSON.stringify(box)}`); + assert.ok(box.spark >= 60 && box.h > 10, `the line can be read: ${JSON.stringify(box)}`); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "no sideways scroll"); + + // a point opens its request in Routing, with its card + await page.evaluate(() => { window.__opened = []; window.openRoute = (id, time, o) => { window.__opened.push([id, time, o]); return Promise.resolve(); }; }); + await hits.nth(1).dispatchEvent("click"); + assert.deepEqual(await page.evaluate(() => window.__opened), [[12, POINTS[1].time, { context: true }]]); + + // a session the gateway kept no prompt of: asked, no line + const answered = page.waitForResponse((r) => r.url().includes("/api/context/session") && r.url().includes("id=kept-none")); + detail = await open("kept-none"); + await answered; + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => r()))); + assert.equal(await detail.locator(".sess-line.sess-ctx:not([hidden])").count(), 0); + // one never through magpie: not asked, no line + detail = await open("own-only"); + assert.equal(await detail.locator(".sess-line.sess-ctx").count(), 0); + assert.equal(asked.filter((q) => q.id === "own-only").length, 0); + + // opened again, drawn at once from what was read + detail = await open("seen-1"); + assert.equal(await detail.locator(".sess-line.sess-ctx .ctx-spark rect.hit").count(), POINTS.length); + assert.equal(asked.filter((q) => q.id === "seen-1").length, 1, "not asked again"); + assert.deepEqual(errors, []); + }); + } + } +} +