From 3c7ec4ba2493ffcccc6969bbf2724091ebbc2c85 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 14 Oct 2026 18:21:47 +0800 Subject: [PATCH] gui: Usage is a plugin's page, its code, markup and words in plugins/usage (P2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P2 of docs/subsystems/plugin-runtime.md, the fourth page after Sessions, Library and Routing, and the largest part of app.js. - The Usage page's code (~3000 lines: the Overview's cards, the Requests ledger and heatmap, the Sessions tab, the Agents list) moves from app.js to assets/plugins/usage/page.js; its markup, index.html's
, is client.js's part html. app.js 25756 → 22675 lines (1,355,376 → 1,198,239 bytes). - page.js builds on app.js at the top level (its timers, ?view=usage's tab and filters), so it is the one plugin script that loads after app.js. index.html: kernel.js, the plugins' other scripts, app.js and the scripts beside it, each page.js, then start.js, which is app.js's old tail (magpie.start(), navHides, OPEN_VIEWS, the first page shown, load()), so the first page has its code. TestBuiltinClientsLoaded holds that order. - Hooks: open loads it, refresh(again) is load()'s read of it, reload is Refresh now, costs redraws costs on a currency change, tab says the tab for focusQuotaCard. app.js calls those through magpie.call. The allowance cards, quotasOpened, panelQuotaFocus and panelUseFocus stay in app.js: the tray panel draws them too. - plugins/usage: Essential, Requires window, no InUse. Off, its nav tab goes and so do the ways to it (data-feature="usage": the panel's Open Usage, Routing's View usage); show("usage") gives way to Agents; the panel's Allowances tab stays. builtins.test.cjs switches it off and checks each. - The 173 strings only Usage says move to plugins/usage/i18n.js; i18n.js 15032 → 14344 lines. "{n}s" and "All sessions" stay: context.js says them too since #1591. - context.js: with context.js now in before the first page is shown, the page's open and load()'s first refresh both reached loadContext, and the second drew "Reading…" again over the advice the first had just drawn, so its curves never played their entrance (context-tune, 3 of 3 red). loadContext draws the waiting pane once for the same days. Its dead last line, which loaded the tab once context.js came in late, goes. - context-window.test.cjs's "arrives after the state" becomes "loads at once though context.js is slow": start.js now waits for it. usage-stale-answer reads page.js beside app.js. quota-refresh-order (#1630) cut app.js at the period picker's comment, now in page.js; it ends at the next comment that stays (5 of 5; without keepRefreshedQuotas' call, 2 of 5 red). - docs: plugin-runtime.md, gui-shell.md. Run, at this tree on origin/main af27b70b4 (main's keepRefreshedQuotas and quotaRefresh changes, #1630, stay in app.js beside loadQuotas: the tray panel draws those cards too): - gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows. - go test -count=1 ./internal/gui ./internal/pluginrt ./plugins/...: ok (-skip TestMainWindowCorners, #1936); gateway and usage as above. - usage-card-refresh, quota-refresh-order, builtins, editor-picker-clicks, context-window, usage-stale-answer: Chromium and WebKit green. - The full GUI set: see the Routing commit; every Usage red there is the same on main or red only under load. --- docs/subsystems/gui-shell.md | 4 +- docs/subsystems/plugin-runtime.md | 25 +- internal/gui/assets/app.js | 3097 +---------------- internal/gui/assets/context.js | 10 +- internal/gui/assets/i18n.js | 696 +--- internal/gui/assets/index.html | 117 +- internal/gui/assets/plugins/routing/client.js | 1 + internal/gui/assets/plugins/usage/client.js | 139 + internal/gui/assets/plugins/usage/i18n.js | 704 ++++ internal/gui/assets/plugins/usage/page.js | 3061 ++++++++++++++++ internal/gui/assets/start.js | 25 + internal/gui/builtins_test.go | 18 +- internal/gui/tests/builtins.test.cjs | 20 +- internal/gui/tests/context-window.test.cjs | 18 +- .../gui/tests/quota-refresh-order.test.cjs | 2 +- .../gui/tests/usage-stale-answer.test.cjs | 7 +- plugins/all/all.go | 1 + plugins/usage/usage.go | 16 + 18 files changed, 4038 insertions(+), 3923 deletions(-) create mode 100644 internal/gui/assets/plugins/usage/client.js create mode 100644 internal/gui/assets/plugins/usage/i18n.js create mode 100644 internal/gui/assets/plugins/usage/page.js create mode 100644 internal/gui/assets/start.js create mode 100644 plugins/usage/usage.go diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 5635801a2..7c782a093 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -15,7 +15,7 @@ three. | Backend | `startBackend` starts the gateway this process serves, unless another magpie already serves it. In that case this process only shows the other one's status (`gw` is nil). `stopServing` drains requests in flight. | [`backend.go`](../../internal/gui/backend.go) | | API and assets | `Handler` serves `assets/` (embedded with `//go:embed assets`) and the `/api/*` routes, such as `/api/state`, `/api/set` and `/api/agents/{action}/{id}`. `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. 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); the app's own windows read the page in-process and get it uncompressed. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.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 and Routing 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; 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), and the header a breadcrumb (`renderCrumb`). 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. 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) | | 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) | | No GUI build | `-tags nogui` builds magpie without the GUI: `hasGUI` is false and `runGUI` says to use `magpie tui`. The files of `internal/gui` that need Wails build under `!nogui`. | [`gui_off.go`](../../internal/cli/gui_off.go) | @@ -59,7 +59,7 @@ refresh was requested this time; a failed read retains its failure notice. Usage rows and aggregates use `Record.Decode` and `DecodeOf` in [`internal/usage/usage.go`](../../internal/usage/usage.go). Routing uses `decodeOf` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js); Usage -rows use `ledDecode` in [`app.js`](../../internal/gui/assets/app.js). +rows use `ledDecode` in [`plugins/usage/page.js`](../../internal/gui/assets/plugins/usage/page.js). When an answer follows reasoning, only answer tokens are timed from the first answer text. Without answer text, all output tokens are timed only diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md index fe1153b6d..074717d79 100644 --- a/docs/subsystems/plugin-runtime.md +++ b/docs/subsystems/plugin-runtime.md @@ -9,7 +9,7 @@ runtime, the file and the window's switch) and P1 (the window's kernel: a plugin's page, its error boundary, the kit it draws with and its settings form, with the Gateway page as the first plugin to draw its own page), and P2 so far (a page moved out of the core whole: its code, styles and words: -Sessions, Library and Routing). OpenCode plugins (npm packages in +Sessions, Library, Routing and Usage). OpenCode plugins (npm packages in the plugin host) are a different thing; see [provider and plugin ownership](provider-plugins.md) and [gateway middleware](gateway-middleware.md). @@ -24,7 +24,7 @@ the plugin host) are a different thing; see | Ctx | What `Apply` gets: `OnDispose(f)`, `Contribute(slot, key)`, `Provide(name, v)` (withdrawn when it goes), `Service(name)`, and its composed `Config`. Disposers run in reverse, each one's panic logged and the rest still run. | [`pluginrt.go`](../../internal/pluginrt/pluginrt.go) | | plugins.yml | `appdir.Config()/plugins.yml`: `preset` (`essentials` or `all`) and `plugins`, rows of `{id, enabled, config}` holding only what the user set. | [`config.go`](../../internal/pluginrt/config.go) | | Settings schema | `SchemaOf(Settings)` makes a JSON Schema object of the struct, in its fields' order (`x-order`): each exported field with a json name is a setting, of `bool`, an int, `float64` or `string`, with tags `title` (English; the window translates it), `description`, `enum` (comma separated) and `min`/`max`. Its values are the defaults. A field a form can't draw, or a tag that doesn't parse, panics at `Register`. `Schema.Validate` takes a value only as the schema allows it (a JSON float64 or a YAML int for an integer); `SetConfig(id, config)` writes the user's row through it, and `Compose` leaves out a value edited into plugins.yml by hand that it doesn't allow, so the default stands. | [`schema.go`](../../internal/pluginrt/schema.go), [`config.go`](../../internal/pluginrt/config.go) | -| Built-in plugins | `groups`, `library`, `otel`, `sessions`, `warmups` (P0), `gateway` (P1), the Gateway page, which is Essential and in use while a gateway key is there (`access.List`), and `routing` (P2), the Routing page, Essential and in use while the user has a routing group, since the page is where groups are made and changed. The Gateway page's one setting, `callsPage` (10, 20, 50 or 100; 20), is how many recent calls the page shows at a time. The other five aren't Essential. Each one's `InUse` counts what the user made with it: routing groups not Auto and not hidden, library items given to agents, a collector sent to, gateway conversations recorded, warm-ups and check-ins on. | [`plugins/`](../../plugins) | +| Built-in plugins | `groups`, `library`, `otel`, `sessions`, `warmups` (P0), `gateway` (P1), the Gateway page, which is Essential and in use while a gateway key is there (`access.List`), and `routing` (P2), the Routing page, Essential and in use while the user has a routing group, since the page is where groups are made and changed. `usage` (P2), the Usage page, is Essential too, with no `InUse`: what it shows the gateway counts anyway, and the tray panel's Usage tab still shows the allowances with it off. The Gateway page's one setting, `callsPage` (10, 20, 50 or 100; 20), is how many recent calls the page shows at a time. The other five aren't Essential. Each one's `InUse` counts what the user made with it: routing groups not Auto and not hidden, library items given to agents, a collector sent to, gateway conversations recorded, warm-ups and check-ins on. | [`plugins/`](../../plugins) | The boundary is checked by `TestPluginsImportOnlyCore`: no package outside `plugins/` imports one (but `main.go`, through `plugins/all`), a plugin never @@ -130,6 +130,27 @@ says one of its words, which goes back to i18n.js. Providers' "Make a routing group of …" (`data-feature="routing"`), the Usage list's View routing and its time as a link, and the context card's Latest request; a panel left on its Routing tab shows Agents. +- **Usage** (`plugins/usage`, `Client: i18n.js, client.js, page.js`): + the page that was the largest part of app.js (about 3000 lines: the + Overview's cards, the Requests ledger, the Sessions tab and the Agents + list). Its part's `html` is the page's markup that was index.html's + `#view-usage`. Its code builds on app.js at the top level (its timers, + `?view=usage`'s tab and filters), so `page.js` is the one script a + plugin loads after app.js: index.html loads kernel.js, the plugins' + other scripts, app.js and the scripts beside it, then each `page.js`, + then `start.js`, which is app.js's old tail (`magpie.start()`, the + first page shown, the first `load()`), so the first page has its code. + `TestBuiltinClientsLoaded` holds that order. Its hooks: `open` loads + it, `refresh(again)` is `load()`'s read of it (coming back to the + Overview is opening the allowances, #1588), `reload` is Refresh now, + `costs` draws the costs again when Settings' currency changes, and + `tab` says which tab it is on, for `focusQuotaCard`. Still in app.js, + since the tray panel draws them too: the allowance cards, + `quotasOpened`, `panelQuotaFocus` and `panelUseFocus`. With the plugin + off, its nav tab goes, and so do the ways to the page + (`data-feature="usage"`): the tray panel's Open Usage and Routing's View + usage. A `show("usage")` left anywhere gives way to Agents. The panel's + Allowances tab stays. ## Source of truth and composing diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 389295bf4..d839eedff 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -3916,8 +3916,7 @@ async function load(again) { // the window back on the Usage page reads the tab shown as its own timer // does: drawn again only on a change, with no skeleton between; on the // Overview, where the allowances are, that is opening them (#1588) - if (view === "usage" && again && usageTab === "usage") quotasOpened(); - if (view === "usage") await (again && usageDrawn() ? refreshUsage() : loadUsage()); + if (view === "usage") await magpie.call("usage", "refresh", again); // so is an open sync form (WebDAV, export, import): its passwords are // never sent back, so a rebuild would empty it if (view === "settings" && !syncOpen) await loadSettings(); @@ -14363,36 +14362,12 @@ function rollUpSheet(sheet, then) { // ---------- usage ---------- -const PERIODS = [["today", "Today"], ["7d", "7 days"], ["30d", "30 days"], ["all", "All"]]; - // The subscriptions' quotas come from the vendors and can take a while (or // never come without a proxy), so they load on their own and the local log // never waits for them. They don't depend on the period either. let quotas = null; let quotasAt = 0; // when they came in let quotaHist = []; // each account's windows over time, for the curves (#651) -// asked: the reader opened the page, so a Claude account's usage is read -// at once, by running Claude Code's own /usage, rather than when its last -// reading is due (every 5 to 15 minutes, at random, once Claude Code was used). -// The Overview's reads share one count: only the newest draws, and only for the -// period and tab the page is on, whether a pick or the timer asked for it. -let usageRead = 0; -async function loadUsage(asked) { - renderUsageTab(); - renderUsageEvery(); // the refresh's tooltip says what it reads on this tab - if (asked) quotasOpened(); - if (usageTab === "sessions") return loadSessions(); - if (usageTab === "requests") return loadLedger(); - if (usageTab === "context") return window.loadContext?.(); - renderUsageLoading(); - if (!asked) loadQuotas(); - const p = period, read = ++usageRead; - const next = await api("usage?period=" + encodeURIComponent(p)); - if (read !== usageRead || view !== "usage" || usageTab !== "usage" || period !== p) return; - usage = next; - renderUsage(); -} - // quotasOpened: the reader opened what shows the allowances (the Usage // page's Overview, the tray panel's Allowances tab, a menu bar cell, either // brought back to the front), which is asking to see them now (#1588, @@ -14465,47 +14440,6 @@ function keepRefreshedQuotas(next, began) { return out.concat([...kept.values()]); } -// the period picker, in the page's head, for the Overview and Requests -function renderPeriod(loading) { - const seg = $("#period"); - seg.replaceChildren(); - for (const [id, name] of PERIODS) { - const b = el("button", "opt" + (id === period ? " on" : ""), t(name)); - b.disabled = !!loading; - b.onclick = () => { for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b); slide(seg, "period"); pickPeriod(id); }; - seg.append(b); - } - // days of the reader's own (#1492): the last opt names them once picked, - // and opens the range menu to pick them, or others - const range = periodDays(period); - const b = el("button", "opt range-opt" + (range ? " on" : "")); - b.type = "button"; - b.disabled = !!loading; - b.setAttribute("aria-haspopup", "dialog"); - b.setAttribute("aria-expanded", "false"); - b.setAttribute("aria-label", range ? t("Days picked: {days}", { days: rangeName(range) }) : t("Pick days")); - b.append(svg("M3 4.5h10v8.5H3zM3 7h10M5.5 3v3M10.5 3v3", 12, 1.4), el("span", "", range ? rangeName(range) : t("Custom"))); - if (range) b.title = t("Days picked: {days}", { days: rangeName(range) }); - b.onclick = () => { - if (b.classList.contains("open")) return closeProtoMenu(); - openRangeMenu(b, range, (from, to) => { - for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b); - b.lastChild.textContent = rangeName({ from, to }); - b.title = t("Days picked: {days}", { days: rangeName({ from, to }) }); - b.setAttribute("aria-label", b.title); - slide(seg, "period"); - pickPeriod(from + ".." + to); - }); - }; - seg.append(b); - slide(seg, "period"); -} - -function pickPeriod(id) { - period = id; ledDay = ""; ledOffset = 0; - loadUsage().catch((e) => status(e.message, "err")); -} - // A period of picked days is "2026-10-01..2026-10-07", both included, in // this computer's time zone, as the backend reads it (usage.RangeOf). // periodDays is its two days, or null for a preset. @@ -14513,151 +14447,7 @@ function periodDays(p) { const m = /^(\d{4}-\d{2}-\d{2})\.\.(\d{4}-\d{2}-\d{2})$/.exec(p || ""); return m ? { from: m[1], to: m[2] } : null; } -const dayKeyOf = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; const dayOfKey = (k) => new Date(k + "T12:00:00"); -// rangeName says picked days short: "Oct 1 – Oct 7", the year only when it -// isn't this one, one day alone as itself -function rangeName({ from, to }) { - const year = new Date().getFullYear(); - const name = (k) => dayOfKey(k).toLocaleDateString(intlLang(), { month: "short", day: "numeric", ...(dayOfKey(k).getFullYear() !== year ? { year: "numeric" } : {}) }); - return from === to ? name(from) : name(from) + " – " + name(to); -} -// noCallsIn is what an empty page says of the period it is on -function noCallsIn(p) { - if (periodDays(p)) return "No calls on the days picked."; - return { today: "No calls today.", "7d": "No calls in the last 7 days.", "30d": "No calls in the last 30 days.", all: "No calls yet." }[p] || "No calls yet."; -} - -// openRangeMenu is the app's own menu for picking days (#1492): a few -// spans a click away, and a month to pick the first day on, then the last. -// Days after today can't be picked. choose gets the two days, in order. -function openRangeMenu(anchor, current, choose) { - closeProtoMenu(); - const today = dayKeyOf(new Date()); - let start = null; // the first day clicked, waiting for the last - let shown = dayOfKey(current?.to || today); - shown = new Date(shown.getFullYear(), shown.getMonth(), 1, 12); - const box = el("div", "pop proto-menu range-menu"); - box.setAttribute("role", "dialog"); - box.setAttribute("aria-label", t("Pick days")); - const head = el("div", "pm-head"); - const quick = el("div", "rm-quick"); - const span = (from, to) => ({ from: dayKeyOf(from), to: dayKeyOf(to) }); - const now = new Date(); - now.setHours(12, 0, 0, 0); - const back = (n) => { const d = new Date(now); d.setDate(d.getDate() - n); return d; }; - const quicks = [ - ["Yesterday", span(back(1), back(1))], - ["This month", span(new Date(now.getFullYear(), now.getMonth(), 1, 12), now)], - ["Last month", span(new Date(now.getFullYear(), now.getMonth() - 1, 1, 12), new Date(now.getFullYear(), now.getMonth(), 0, 12))], - ["90 days", span(back(89), now)], - ]; - for (const [name, r] of quicks) { - const b = el("button", "rm-span" + (current && current.from === r.from && current.to === r.to ? " on" : ""), t(name)); - b.type = "button"; - b.title = rangeName(r); - b.onclick = (e) => { e.stopPropagation(); closeProtoMenu(); choose(r.from, r.to); }; - quick.append(b); - } - const nav = el("div", "rm-nav"); - const prev = el("button", "rm-step"), next = el("button", "rm-step"), month = el("span", "rm-month"); - prev.type = next.type = "button"; - prev.setAttribute("aria-label", t("Previous month")); - next.setAttribute("aria-label", t("Next month")); - prev.append(svg("M10 4 6 8l4 4", 12, 1.6)); - next.append(svg("m6 4 4 4-4 4", 12, 1.6)); - nav.append(prev, month, next); - const grid = el("div", "rm-grid"); - grid.setAttribute("role", "grid"); - box.append(head, quick, nav, grid); - const draw = (focusDay) => { - head.textContent = start ? t("Now the last day") : t("Pick the first day, then the last"); - month.textContent = shown.toLocaleDateString(intlLang(), { year: "numeric", month: "long" }); - next.disabled = dayKeyOf(new Date(shown.getFullYear(), shown.getMonth() + 1, 1, 12)) > today; - const cells = []; - // the weekdays, Monday first, as the app's weeks are - for (let i = 0; i < 7; i++) cells.push(el("span", "rm-wd", new Date(2024, 0, 1 + i, 12).toLocaleDateString(intlLang(), { weekday: "narrow" }))); - const first = new Date(shown); - const lead = (first.getDay() + 6) % 7; - for (let i = 0; i < lead; i++) cells.push(el("span", "rm-pad")); - const lo = start || current?.from, hi = start ? null : current?.to; - for (let d = new Date(first); d.getMonth() === shown.getMonth(); d.setDate(d.getDate() + 1)) { - const k = dayKeyOf(d); - const b = el("button", "rm-day", String(d.getDate())); - b.type = "button"; - b.dataset.day = k; - b.setAttribute("aria-label", d.toLocaleDateString(intlLang(), { year: "numeric", month: "long", day: "numeric" })); - if (k === today) b.classList.add("today"); - if (lo && (k === lo || k === hi)) b.classList.add("end"); - if (lo && hi && k > lo && k < hi) b.classList.add("in"); - b.disabled = k > today; - b.onclick = (e) => { - e.stopPropagation(); - if (!start) { start = k; draw(k); return; } - const [from, to] = start <= k ? [start, k] : [k, start]; - closeProtoMenu(); - choose(from, to); - }; - cells.push(b); - } - grid.replaceChildren(...cells); - (focusDay && grid.querySelector(`[data-day="${focusDay}"]`))?.focus({ preventScroll: true }); - }; - const turn = (by) => (e) => { e.stopPropagation(); shown = new Date(shown.getFullYear(), shown.getMonth() + by, 1, 12); draw(); }; - prev.onclick = turn(-1); - next.onclick = turn(1); - draw(); - document.body.append(box); - placeMenu(box, anchor); - anchor.classList.add("open"); - anchor.setAttribute("aria-expanded", "true"); - const outside = (e) => { if (!box.contains(e.target) && !anchor.contains(e.target)) closeProtoMenu(); }; - const scroll = (e) => { if (scrollCloses(box, e)) closeProtoMenu(); }; - // Escape closes; arrows walk the days, a week up or down - const keys = (e) => { - if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeProtoMenu(); anchor.focus({ preventScroll: true }); return; } - const at = document.activeElement?.dataset?.day; - const by = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 }[e.key]; - if (!at || !by || !box.contains(document.activeElement)) return; - e.preventDefault(); e.stopPropagation(); - const d = dayOfKey(at); - d.setDate(d.getDate() + by); - const k = dayKeyOf(d); - if (k > today) return; - if (d.getMonth() !== shown.getMonth() || d.getFullYear() !== shown.getFullYear()) shown = new Date(d.getFullYear(), d.getMonth(), 1, 12); - draw(k); - }; - document.addEventListener("mousedown", outside, true); - document.addEventListener("keydown", keys, true); - document.addEventListener("scroll", scroll, true); - addEventListener("resize", closeProtoMenu); - protoMenu = { box, anchor, outside, keys, scroll, done: null }; - (grid.querySelector(".rm-day.end") || grid.querySelector(".rm-day.today") || quick.firstChild).focus({ preventScroll: true }); -} - -function renderUsageLoading() { - const view = $("#view-usage"); - view.classList.add("loading"); - view.setAttribute("aria-busy", "true"); - renderPeriod(true); - $("#usageCost").replaceChildren(el("span", "skeleton sk-cost")); - renderQuotas(); - const stats = $("#stats"); - stats.classList.remove("empty"); - stats.replaceChildren(); - for (let i = 0; i < 4; i++) { - const tile = el("div", "kpi loading-kpi"); - tile.append(el("span", "skeleton sk-number"), el("span", "skeleton sk-label")); - stats.append(tile); - } - $("#chart").hidden = true; - for (const id of ["usageAgents", "usageAgentsHid", "usageModels", "usageKeys"]) $("#" + id).hidden = true; - // the allowances' head is renderQuotas' alone: the quotas it heads are - // still there while the period loads (#809, Hu9956: 用量界面红框这行会延迟几秒才会出现) - for (const h of $$("#view-usage .row-head:not(#quotaHead)")) h.hidden = true; - $("#usageNote").textContent = ""; -} - // a count as a short number: 133M, and 1.33 亿, 68.1 万 in Chinese with // Settings' 万/亿 units (chineseUnits), 億 and 萬 in Traditional — every // count on the Usage page and in the panel, tokens or requests, says it @@ -14690,61 +14480,8 @@ function fmtCost(t) { const s = c >= 100 ? c.toFixed(0) : c >= 1 ? c.toFixed(2) : c.toFixed(3); return sign + s + (t.unpriced ? "+" : ""); } -// costHead is the Usage head's sum: the cost at effective prices, or, when -// some of what it sums has no known price, how many beside it (#1856) — a -// total never reads as if those cost nothing — and with none priced, the -// count alone. note is that count in words ("" when everything was -// priced), title the tooltip. -function costHead(c, note, title) { - const cost = $("#usageCost"); - cost.replaceChildren(); - cost.title = ""; - if (!c && !note) return; - if (c) cost.append(el("b", "", "≈" + c)); - cost.append(el("span", note ? "unpriced" : "", note || t("effective prices"))); - cost.title = title; -} -const unpricedCalls = (n) => t(n === 1 ? "{n} call unpriced" : "{n} calls unpriced", { n: ledNum(n) }); -const unpricedCallsWhy = (n) => n ? t(n === 1 ? "{n} call had no known price and is not counted" : "{n} calls had no known price and are not counted", { n }) : t("Estimated using effective model prices, including custom prices"); -// renderCosts redraws whatever on the Usage page shows a cost, once the -// currency changes — the numbers alone, not the page around them, so a -// click on the setting never moves anything it isn't showing (#212) -function renderCosts() { - if (usage) renderUsage(); - if (ledger && usageTab === "requests") renderLedger(); - if (sessions) renderSessions(); - document.dispatchEvent(new Event("magpie-costs-changed")); -} const tokensOf = (t) => t.input + t.output; -// quotaWho is how an account's card names it (#1515): by the name the user -// gave it, the account beside it, else the account; and the key plan it -// stands in for (seat) when that isn't already its name. A team's GLM -// seats read as the user tells them apart, not as 31****36@qq.com. -function quotaWho(q) { - const out = []; - if (q.alias) { - const a = el("span", "user quota-alias", q.alias); - a.title = q.user ? q.alias + " · " + q.user : q.alias; - out.push(a); - if (q.user) { - const u = el("span", "quota-of", q.user); - u.title = q.user; - out.push(u); - } - } else if (q.user) { - const u = el("span", "user", q.user); - u.title = q.user; - out.push(u); - } - if (q.seat && q.seat !== q.alias) { - const s = el("span", "quota-seat", "≡ " + q.seat); - s.title = t("The same seat as the key plan {name}, shown once, on this account's card", { name: q.seat }); - out.push(s); - } else if (q.seat) out[0].title += "\n" + t("The same seat as the key plan {name}, shown once, on this account's card", { name: q.seat }); - return out; -} - // magpie's own requests (#1839): the ones it made by itself, not an agent — // a routing group's classifier, a web search, an image description — which // go to the same keys and accounts as the agents' and count against them, @@ -14758,9 +14495,6 @@ function ownBadge() { b.title = ownWhy(); return b; } -function ownCalls(n) { - return t("{n} by magpie itself", { n: fmtN(n) }); -} // ownLine is an account card's line saying how many of the period's // requests to it magpie made by itself, from the Overview's summary: the // account's own, or for a card of no account the provider's @@ -15656,13 +15390,6 @@ function quotaCurve(sub) { box.draw(); return box; } -// quotaReadings: a line's last eight readings, newest first, each what was -// left and when it was read (#802), a line each, ↻ where the window -// started again; for its legend key's title -function quotaReadings(l, now) { - const pts = l.points.slice(-8); - return pts.map((p, i) => (i > 0 && quotaCycleBreak(pts[i - 1], p) ? "↻ " : "") + Math.round(p.left) + "% · " + quotaTimeText(p.at, now)).reverse(); -} // curveZoom: a curve made larger on a click, or Enter, and back on the // next (TJHHHH on Discord); the page stays where it is function curveZoom(box, g) { @@ -15956,7 +15683,7 @@ function focusQuotaCard() { if (performance.now() > quotaFocusUntil) { quotaFocus = ""; return; } const box = mode === "panel" ? $("#panelQuota") : $("#subscriptionUsage"); if (mode === "panel") setPanelTab("usage"); - else if (view !== "usage" || usageTab !== "usage") return; + else if (view !== "usage" || magpie.call("usage", "tab") !== "usage") return; const id = CSS.escape(quotaFocus); // a key's balance shown on its plan's card (keyCards): that card const target = box.querySelector(`[data-card="${id}"]`) || box.querySelector(`[data-bal-card="${id}"]`) || box.querySelector(`[data-provider="${id}"]`); @@ -16131,6 +15858,7 @@ function renderPanelUse() { sessPick(comp, "All computers", panelUseComputer, copts, "Computer", (id) => { panelUseComputer = id; renderPanelUse(); loadPanelUse().catch(() => {}); }); const open = el("button", "text", t("Open Usage")); open.type = "button"; + open.dataset.feature = "usage"; // it opens on the Usage page open.onclick = (e) => { api("window/main?" + new URLSearchParams({ view: "usage", tab: "requests", ...(panelUseProvider ? { provider: panelUseProvider } : {}), ...(panelUseComputer ? { computer: panelUseComputer } : {}) }), {}); e.currentTarget.blur(); @@ -17396,274 +17124,6 @@ function quotaWindows(sub) { return windows; } -// Keep the last date and as many earlier dates as fit, without clipping their -// text. Visibility keeps each label aligned to its bar; resizing restores them. -function fitChartLabels() { - const narrow = web && matchMedia("(max-width: 760px), (pointer: coarse) and (max-width: 1024px)").matches; - for (const labels of document.querySelectorAll(".chart .labels")) { - const spans = [...labels.children]; - for (const span of spans) span.style.visibility = ""; - if (!narrow || !labels.offsetWidth) continue; - const box = labels.getBoundingClientRect(); - let right = box.right + 8; - for (const span of spans.reverse()) { - if (!span.textContent) continue; - const range = document.createRange(); - range.selectNodeContents(span); - const r = range.getBoundingClientRect(); - if (r.right + 8 > right + 1 || r.left < box.left - 1) span.style.visibility = "hidden"; - else right = r.left; - } - } -} -new ResizeObserver(fitChartLabels).observe($("#view-usage")); - -function renderUsage() { - const u = usage; - const view = $("#view-usage"); - view.classList.remove("loading"); - view.removeAttribute("aria-busy"); - renderPeriod(); - costHead(fmtCost(u), u.unpriced ? unpricedCalls(u.unpriced) : "", unpricedCallsWhy(u.unpriced)); - - const stats = $("#stats"); - stats.replaceChildren(); - const empty = !u.calls; - $("#chart").hidden = empty; - for (const id of ["usageAgents", "usageModels"]) $("#" + id).hidden = empty; - if (empty) $("#usageAgentsHid").hidden = true; - for (const h of $$("#view-usage .row-head:not(#quotaHead)")) h.hidden = empty; - $("#usageKeysHead").hidden = $("#usageKeys").hidden = empty || !u.callerKeys?.length; - // each subscription account's share, by the account that answered (#557) - $("#usageAccountsHead").hidden = $("#usageAccounts").hidden = empty || !u.accounts?.length; - if (empty) { - stats.classList.add("empty"); - const none = noCallsIn(period); - stats.append(el("div", "none", t(none) + " " + t("Point an agent at a catalog model and use it; every call through the gateway is counted here."))); - $("#usageNote").textContent = ""; - return; - } - stats.classList.remove("empty"); - const tile = (n, label, sub, title) => { - const t = el("div", "kpi"); - if (title) t.title = title; - t.append(el("b", "", n), el("span", "", label)); - if (sub) t.append(el("small", "", sub)); - stats.append(t); - }; - tile(fmtN(tokensOf(u)), t("tokens"), t("{a} in · {b} out", { a: fmtN(u.input), b: fmtN(u.output) })); - // cache reads are billed at a fraction of input, so how much of the prompt - // came from cache is the number that explains the bill; input here already - // excludes the cached tokens, read and written (the gateway subtracts - // them), so what was written counts in the prompt too: left out, a prompt - // written to the cache again at every turn showed a rate near 100%. The - // written count is secondary and only fits in the tooltip. - const promptTokens = u.input + u.cache_read + u.cache_write; - const hit = u.cache_read && promptTokens ? t("hit rate {p}", { p: Math.round(100 * u.cache_read / promptTokens) + "%" }) : ""; - tile(fmtN(u.cache_read), t("cache read"), hit, u.cache_write ? t("{n} written", { n: fmtN(u.cache_write) }) + cacheTTLs(u, fmtN) : ""); - tile(fmtN(u.reasoning), t("reasoning"), t("inside output")); - tile(String(u.calls), t(u.calls === 1 ? "call" : "calls"), [u.errors ? t("{n} failed", { n: u.errors }) : "", u.retried ? t("{n} answered on a retry", { n: u.retried }) : "", u.unpriced ? t("{n} unpriced", { n: u.unpriced }) : ""].filter(Boolean).join(" · "), u.unpriced ? unpricedCallsWhy(u.unpriced) : ""); - - // the timeline: one bar per hour, day or week; output sits on top of input - const chart = $("#chart"); - chart.replaceChildren(); - const bars = el("div", "bars"); - const peak = Math.max(1, ...u.series.map(tokensOf)); - const labels = el("div", "labels"); - const n = u.series.length; - const every = n <= 8 ? 1 : n <= 31 ? Math.ceil(n / 6) : Math.ceil(n / 5); - // the day in the reader's language (the label comes as "Sep 5" in every one) - const dayOf = (p) => u.bucket === "hour" || !p.time ? p.label : new Date(p.time).toLocaleDateString(intlLang(), { month: "short", day: "numeric" }); - u.series.forEach((p, i) => { - const b = el("div", "bar"); - const inp = el("i", "in"), out = el("i", "out"); - inp.style.height = (100 * p.input / peak).toFixed(1) + "%"; - out.style.height = (100 * p.output / peak).toFixed(1) + "%"; - b.append(out, inp); - const when = u.bucket === "hour" ? `${p.label}:00` : u.bucket === "week" ? t("week of {label}", { label: dayOf(p) }) : dayOf(p); - b.title = p.calls ? t(p.calls === 1 ? "{when} · {tokens} tokens · {n} call" : "{when} · {tokens} tokens · {n} calls", { when, tokens: fmtN(tokensOf(p)), n: p.calls }) + (fmtCost(p) ? " · ≈" + fmtCost(p) : "") : t("{when} · nothing", { when }); - bars.append(b); - const last = i === n - 1 && (n - 1) % every >= every / 2; - labels.append(el("span", "", i % every === 0 || last ? dayOf(p) : "")); - }); - chart.append(el("div", "peak", fmtN(peak)), bars, labels); - fitChartLabels(); - - const total = Math.max(1, tokensOf(u)); - const list = (id, groups, act) => { - const box = typeof id === "string" ? $("#" + id) : id; - box.replaceChildren(); - for (const g of groups) { - const r = el("div", "row stat"); - r.dataset.id = g.id || ""; - r.append(icon(g.icon || "generic")); - const who = el("div", "who"); - who.append(el("div", "name" + (g.name ? "" : " faint"), g.name || t("account not recorded"))); - const sub = []; - if (g.sub) sub.push(g.sub); - sub.push(t(g.calls === 1 ? "{n} call" : "{n} calls", { n: g.calls })); - // magpie's own calls apart from the agents' (#1839): magpie's row - // says it is, and a model's, a key's or an account's how many of - // its calls were - if (id === "usageAgents" && g.id === "magpie") who.firstChild.append(ownBadge()); - else if (g.own?.calls) sub.push(ownCalls(g.own.calls)); - if (g.errors) sub.push(t("{n} failed", { n: g.errors })); - // of those, the replies magpie ended stuck in a loop (#1858) - if (g.loops) sub.push(t("{n} looped", { n: g.loops })); - if (g.retried) sub.push(t("{n} answered on a retry", { n: g.retried })); - // how long the streamed replies took to begin, and how fast they - // wrote after (#196) - if (g.timed) { - sub.push(t("TTFT {ms}", { ms: ledTook(Math.round(g.ttft_ms / g.timed)) })); - } - const gs = ledGroupSpeed(g); - if (gs) sub.push(gs.text); - const subLine = el("div", "sub", sub.join(" · ")); - if (g.own?.calls) subLine.title = ownWhy(); - who.append(subLine); - r.append(who); - const share = el("div", "share"); - const fill = el("i"); - fill.style.width = Math.max(1.5, 100 * tokensOf(g) / total).toFixed(1) + "%"; - share.append(fill); - share.title = t("{n}% of tokens", { n: Math.round(100 * tokensOf(g) / total) }); - r.append(share); - const num = el("div", "num"); - // how much of its prompt came from the cache, counted as the cache - // read tile counts it (#925) - const prompt = g.input + g.cache_read + (g.cache_write || 0); - const hit = g.cache_read && prompt ? " · " + t("hit rate {p}", { p: Math.round(100 * g.cache_read / prompt) + "%" }) : ""; - num.append(el("b", "", fmtN(tokensOf(g))), el("small", "", t("{a} in · {b} out", { a: fmtN(g.input), b: fmtN(g.output) }) + (g.cache_read ? " · " + t("{n} cached", { n: fmtN(g.cache_read) }) : "") + hit)); - r.append(num); - r.append(el("div", "cost", fmtCost(g) ? "≈" + fmtCost(g) : "")); - if (act) act(r, g); - box.append(r); - } - }; - // a client hidden from the Agents list (ikunbots on X: curl, - // Go-http-client, python-httpx beside the agents in use) is left out of - // it, and only of it: the totals, the chart and every share above still - // count its calls. One line under the list says how many, and opens them. - const hid = new Set(state.settings?.usageAgentsHidden || []); - const hidden = u.agents.filter((g) => hid.has(g.id)); - list("usageAgents", u.agents.filter((g) => !hid.has(g.id)), (r, g) => { - r.classList.add("acts"); - const b = el("button", "icon us-more"); - b.type = "button"; - b.setAttribute("aria-haspopup", "menu"); - b.setAttribute("aria-label", t("Actions for {name}", { name: g.name || g.id })); - b.append(svg(DOTS, 14, 2.2)); - // a client magpie doesn't know can be counted as one of the agents - // it does (#1958, NorethSea): a bridge that starts Codex under a name - // of its own; the agent counting one has it put back on its own - const counted = Object.entries(state.settings?.clientAgents || {}).filter(([, as]) => as === g.id).map(([c]) => c); - const menu = () => { - const again = agentMenu?.anchor === b; - closeAgentMenu(); - if (again) return; - openRowMenu(b, [ - ...(countable(g.id) ? [{ name: "Count as an agent…", icon: COUNT_AS, run: () => pickCountAs(b, g) }] : []), - ...counted.map((c) => ({ name: t("Count {client} on its own", { client: c }), icon: OUT, run: () => countClientAs(c, "") })), - { name: "Hide from this list", icon: EYE_OFF, sep: countable(g.id) || counted.length > 0, run: () => hideUsageAgent(g.id, true) }, - ]); - }; - if (counted.length) { - const sub = r.querySelector(".who .sub"); - sub.textContent = t("with {clients}", { clients: counted.join(", ") }) + " · " + sub.textContent; - } - b.onclick = (e) => { e.stopPropagation(); menu(); }; - r.oncontextmenu = (e) => { e.preventDefault(); menu(); }; - r.querySelector(".share").after(b); - }); - const hb = $("#usageAgentsHid"); - hb.hidden = !hidden.length; - if (!hidden.length) usageHidOpen = false; - const line = hb.querySelector(".us-hidline"), hl = hb.querySelector(".list"); - line.replaceChildren(el("span", "", t("{n} hidden", { n: hidden.length })), svg(CHEV, 11, 1.6)); - line.title = t("Hidden from this list only: their calls still count in the totals and the chart. Click to see them."); - line.setAttribute("aria-expanded", String(usageHidOpen)); - line.onclick = () => { usageHidOpen = !usageHidOpen; renderUsage(); }; - hl.hidden = !usageHidOpen; - list(hl, usageHidOpen ? hidden : [], (r, g) => { - r.classList.add("hid", "acts"); - const b = el("button", "text us-unhide", t("Unhide")); - b.type = "button"; - b.onclick = (e) => { e.stopPropagation(); hideUsageAgent(g.id, false); }; - r.append(b); - }); - list("usageModels", u.models); - list("usageAccounts", u.accounts || []); - list("usageKeys", u.callerKeys || []); - $("#usageNote").textContent = t("Counted from the providers' own usage reports on every call through the gateway · {path}", { path: u.path }); - // the account cards say how many of this period's requests were - // magpie's own (ownLine), which they could only once the summary came - if (quotas && (u.accounts?.some((g) => g.own?.calls) || $("#subscriptionUsage .quota-own"))) renderQuotas(); -} - -// countable is whether the Usage page's Agents list offers to count a -// client as an agent: one magpie doesn't know, not magpie's own (#1839) -// nor the calls that named no client. -const COUNT_AS = "M3 3v3.5A3.5 3.5 0 0 0 6.5 10H13M10 7l3 3-3 3"; -function countable(id) { - return !!id && id !== "other" && !/^magpie/i.test(id) && !(state.clients || []).some((a) => a.id === id); -} -// pickCountAs opens the agents a client can be counted as, under its menu -// button. -function pickCountAs(anchor, g) { - const opts = (state.clients || []).filter((a) => a.id !== "magpie").map((a) => ({ v: a.id, name: a.name, literalName: true, note: "" })); - openProtoMenu(anchor, opts, "", (v) => countClientAs(g.id, v), "Count this client's calls as", "", "left", false, opts.length > 8 ? "Search agents…" : ""); -} -// countClientAs counts a client's calls as an agent's on the Usage and -// Sessions pages, or on its own again (as ""), and draws the page again -// from the ledger read anew: the history is counted the new way too. -async function countClientAs(client, as) { - try { - const s = await api("usage/arrange", { count: { client, as } }); - state.settings = { ...state.settings, clientAgents: s.clientAgents || {} }; - status(as ? t("{client} is counted as {agent}", { client, agent: (state.clients || []).find((a) => a.id === as)?.name || as }) : t("{client} is counted on its own", { client }), "ok"); - await loadUsage(); - } catch (e) { - status(e.message, "err"); - } -} - -// hideUsageAgent takes a client out of the Usage page's Agents list, or -// puts it back: drawn at once, put back if the save fails. Its calls stay -// in the ledger and in every total. -async function hideUsageAgent(id, hide) { - const prev = state.settings || {}; - const cur = (prev.usageAgentsHidden || []).filter((k) => k !== id); - const agentsHidden = hide ? [...cur, id] : cur; - state.settings = { ...prev, usageAgentsHidden: agentsHidden }; - const again = () => { - if (!usage) return; - renderUsage(); - // the focus stays on the list: the row put back, else the hidden line - const to = hide ? $("#usageAgentsHid .us-hidline") : $(`#usageAgents .row.stat[data-id="${CSS.escape(id)}"] .us-more`); - (to && !to.closest("[hidden]") ? to : null)?.focus({ preventScroll: true }); - }; - again(); - try { - const s = await api("usage/arrange", { agentsHidden }); - state.settings = { ...state.settings, usageAgentsHidden: s.usageAgentsHidden || [] }; - } catch (e) { - state.settings = prev; - again(); - status(e.message, "err"); - } -} - -// ---------- requests ---------- -// -// The ledger: every request of the period, one row each, newest first — -// what the agent asked for, where it went, the model sent and the one the -// reply says answered, the tokens, what they cost at effective prices, how long -// it took and how it ended — to set beside a vendor's own bill. The -// server pages it (/api/usage/requests) and saves it whole as CSV. - -let ledger = null; // the page shown: { rows, offset, total, agents, …totals } -let ledOffset = 0, ledPurpose = "", ledAgent = "", ledProvider = "", ledAccount = "", ledCallerKey = "", ledFailed = false, ledRetried = false, ledQuery = "", ledModel = "", ledRoute = 0, ledComputer = "", ledDay = "", ledVia = ""; - // computerOpts are the Computer filter's choices: this computer, the others // together, and each other one, as sync shares their usage (#542); none // while no other computer's is here. @@ -17674,309 +17134,11 @@ function computerOpts(cs) { ...(others.length > 1 ? [{ v: "others", name: t("Other computers"), note: "" }] : []), ...others.map((c) => ({ v: c.id, name: c.name || c.id, note: "" }))]; } -const LED_PAGE = 100; -// Remember the chart metric; start each app load split by model. -let ledMetric = "tokens", ledSplit = "model"; -try { - const m = localStorage.getItem("magpie.ledMetric"); - if (["tokens", "cost", "calls", "speed"].includes(m)) ledMetric = m; -} catch {} - -let ledRouteInfo = null, ledBeforeRoute = null; -window.openUsageRoute = (route) => { - if (!ledBeforeRoute) ledBeforeRoute = { period, ledOffset, ledPurpose, ledAgent, ledProvider, ledAccount, ledCallerKey, ledFailed, ledRetried, ledQuery, ledModel, ledComputer, ledDay, ledVia }; - ledRoute = route.id; - ledRouteInfo = route; - ledOffset = 0; ledPurpose = ""; ledAgent = ""; ledProvider = ""; ledAccount = ""; ledCallerKey = ""; ledFailed = false; ledRetried = false; ledQuery = ""; ledModel = ""; ledComputer = ""; ledVia = ""; - ledDay = ""; - $("#ledQ").value = ""; - period = "all"; - usageTab = "requests"; - ledger = null; - show("usage"); -}; - -function ledParams(extra) { - const q = new URLSearchParams({ period }); - if (ledDay) q.set("day", ledDay); - if (ledAgent) q.set("agent", ledAgent); - if (ledPurpose) q.set("purpose", ledPurpose); - if (ledProvider) q.set("provider", ledProvider); - if (ledAccount) q.set("account", ledAccount); - if (ledComputer) q.set("computer", ledComputer); - if (ledCallerKey) q.set("callerKey", ledCallerKey); - if (ledVia) q.set("via", ledVia); - if (ledRoute) q.set("route", ledRoute); - if (ledFailed) q.set("failed", "1"); - if (ledRetried) q.set("retried", "1"); - if (ledModel) q.set("model", ledModel); - else if (ledQuery.trim()) q.set("q", ledQuery.trim()); - if (extra) for (const k in extra) q.set(k, extra[k]); - return q.toString(); -} - -// One read of the ledger at a time (Vantiboo1ean, ~750k requests): the page -// asked again while it is read (the refresh button, the timer) waits for -// that read, and another page or filter cancels it. Each pick and press -// used to send one more, and a long history's reads, all still running, -// took the browser's few connections to magpie, so the page never came. -// flight: { want, ctl, p } -const ledFlights = { page: null, heat: null }; -function ledRead(kind, path, want) { - const was = ledFlights[kind]; - if (was?.want === want) return was.p; - was?.ctl.abort(); - const ctl = new AbortController(); - const f = { want, ctl, p: api(path + want, undefined, undefined, ctl.signal) }; - ledFlights[kind] = f; - const done = () => { if (ledFlights[kind] === f) ledFlights[kind] = null; }; - f.p.then(done, done); - return f.p; -} -const ledAborted = (e) => e?.name === "AbortError"; - -// quiet: a refresh while it's looked at, redrawn only on a change -async function loadLedger(quiet) { - if (!ledger && !quiet) renderLedgerLoading(); - loadLedHeat().catch(() => {}); - const want = ledParams({ offset: ledOffset, limit: LED_PAGE }); - let l; - try { l = await ledRead("page", "usage/requests?", want); } catch (e) { - if (ledAborted(e)) return; // another page or filter was picked, and is read instead - throw e; - } - if (want !== ledParams({ offset: ledOffset, limit: LED_PAGE })) return; // another page or filter was picked meanwhile - if (quiet && JSON.stringify(l) === JSON.stringify(ledger)) return; - ledger = l; - if (view === "usage" && usageTab === "requests") renderLedger(); -} - -function renderLedgerLoading() { - const view = $("#view-usage"); - view.classList.add("loading"); - view.setAttribute("aria-busy", "true"); - renderPeriod(true); - $("#usageCost").replaceChildren(el("span", "skeleton sk-cost")); - $("#ledSum").textContent = ""; - $("#ledPager").hidden = true; - const wrap = $("#ledWrap"); - wrap.classList.remove("none"); - wrap.replaceChildren(); - $("#ledHScroll").hidden = true; - for (let i = 0; i < 5; i++) { - const r = el("div", "led-sk"); - r.append(el("span", "skeleton sk-line")); - wrap.append(r); - } -} - const ledNum = (n) => (n || 0).toLocaleString(intlLang()); // an average first token is a fraction of a millisecond: whole ones under a // second, rounded first so 999.6 reads 1.0 s rather than 1000 ms const ledTook = (ms = 0) => (ms = Math.round(ms) || 0) < 1000 ? t("{n} ms", { n: ms }) : t("{n} s", { n: (ms / 1000).toFixed(ms < 10e3 ? 1 : 0) }); -function ledTime(when) { - const d = new Date(when), now = new Date(); - const opts = { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false }; - if (d.toDateString() !== now.toDateString()) Object.assign(opts, { month: "short", day: "numeric" }); - return d.toLocaleString(intlLang(), opts); -} -// the model the reply named: amber, as the Routing page's tag, when it is -// another than the one sent; plain when it is that one under a dated name, -// or the member a remote magpie's routing group sent it to, said in its title -function ledServed(r) { - if (!r.served) return el("span", "faint", "—"); - if (r.routed && !r.swapped) { - const k = el("span", "muted model-value routed", r.served); - k.title = window.routedWhy ? window.routedWhy({ model: r.model, served: r.served }) : ""; - return k; - } - if (!r.swapped) return el("span", "model-value", r.served); - const k = el("span", "swap", r.served); - k.title = window.swapWhy ? window.swapWhy({ model: r.model, served: r.served }) : ""; - return k; -} - -// the protocol a request was sent upstream in, told by the path it went -// out on, and the one its agent spoke when that was another: the -// endpoint reads "/v1/chat/completions → /v1/messages" for a request -// translated, the agent's own path alone for one sent as it came (蓝猫 on -// Discord). null for a request with no path kept, a session file's. Gemini's -// is generateContent, or streamGenerateContent streamed (Gemini CLI's, -// Vertex AI's). -const ledProtoOf = (path) => /\/messages\b/.test(path) ? "Anthropic" : /\/responses\b/.test(path) ? "Responses" - : /\/chat\/completions\b/.test(path) ? "Chat" : /[gG]enerateContent|\/generate\b/.test(path) ? "Gemini" : ""; -function ledProtos(r) { - if (!r.ep || r.source === "log") return null; - const [a, b] = String(r.ep).split(" → "); - const from = ledProtoOf(a), to = b ? ledProtoOf(b) : from; - if (!to) return null; - return { from: from || to, to }; -} -function ledProtoBadge(r) { - const p = ledProtos(r); - if (!p) return null; - const k = el("span", "src proto proto-" + p.to.toLowerCase(), p.from !== p.to ? p.from + " → " + p.to : p.to); - k.title = p.from !== p.to ? t("The agent spoke {from}; sent upstream as {to}", p) : t("Sent upstream as {to}, as the agent spoke it", p); - return k; -} - -// a request that failed: told by its status, or, for one read from a -// session file, which records none, by the error that ended it -const ledFailed_ = (r) => r.status >= 400 || !!r.err; -const ledKey = (r) => [r.t, r.agent, r.model, r.rid, r.session, r.computer || ""].join("|"); -const ledOpen = new Set(); // the rows opened, kept across a refresh - -// what is known of one request beyond its row: the id its vendor gave it, -// the path it went to, and, if it failed, what the vendor said -function ledDetail(r, cols) { - const dl = el("dl", "led-dl"); - const add = (name, value, cls) => { - if (value === "" || value == null) return; - dl.append(el("dt", "", t(name)), el("dd", cls || "", value)); - }; - if (ledFailed_(r)) { - add("Status", r.status ? String(r.status) : "—", "bad"); - add("Error type", r.err_type, "bad"); - add(r.source === "log" ? "Error" : "Upstream said", r.err, "said"); - } else { - // how it went, here as well as in the row's last column, which a narrow - // window leaves out of sight (#799) - add("Status", r.status ? String(r.status) : r.source === "log" ? t("Succeeded") : ""); - } - if (Number.isFinite(r.ms) && r.ms > 0) add("Duration", (r.source === "log" ? "≈" : "") + ledTook(r.ms)); - // the way it was routed: the row's time links there too, which reads as - // a time rather than a link (#799) - // (with the Routing page switched off there is nowhere to see it) - if (r.route_id && !featuresOff.has("routing")) { - const go = el("button", "text led-route-link", t("View routing")); - go.onclick = (e) => { e.stopPropagation(); window.openRoute(r.route_id, r.t).catch((err) => status(err.message, "err")); }; - const dd = el("dd"); - dd.append(go); - dl.append(el("dt", "", t("Routing")), dd); - } - if (r.computerName) add("Computer", r.computerName); - // the client's own name, for one the user counts as an agent (#1958) - add("Client", r.client); - // the columns a narrow window leaves out, shown only while it does (#860) - const opt = (name, value) => { - if (!value) return; - add(name, value); - dl.lastChild.classList.add("lc-opt"); - dl.lastChild.previousSibling.classList.add("lc-opt"); - }; - opt("Sent", r.model); - opt("Effort", r.effort); - // its tokens at every width, the cache's beside in and out: a prompt read - // from the cache is told from one that missed it, whose input is the - // whole of it, where the row's cache columns are out of sight (#1839). - // In leaves the cache out, as Anthropic counts it. - if (r.in || r.out || r.cache_read || r.cache_write || !ledFailed_(r)) { - add("Tokens", t("{i} in · {o} out · {r} cache read · {w} cache creation", { i: ledNum(r.in || 0), o: ledNum(r.out || 0), r: ledNum(r.cache_read || 0), w: ledNum(r.cache_write || 0) }) + cacheTTLs(r, ledNum), "led-tokens"); - } - if (ledRowSpeed(r)) add("Speed", t("{n} tok/s", { n: ledNum(Math.round(ledRowSpeed(r))) })); - else if (ledFloorSpeed(r)) add("Speed", "≥" + t("{n} tok/s", { n: ledNum(Math.round(ledFloorSpeed(r))) })); - add("Request ID", r.rid); - add("Endpoint", r.ep); - const protos = ledProtos(r); - if (protos) add("Protocol", protos.from !== protos.to ? protos.from + " → " + protos.to : protos.to); - // why the upstream said its reply ended, in its own words: a reply that - // ended too soon is told apart by it (蓝猫 on Discord) - add("Upstream stop reason", r.stop); - // the provider an aggregator (OpenRouter …) said answered behind it - add("Upstream provider", r.upstream); - add("Session ID", r.session); - // a call that isn't a turn of the conversation says what it was for, as - // the agent named it: a subagent's, a title, an approval check… — a - // model the conversation never picked reads as what it is (#714) - if (r.kind) add("Called for", window.kindName ? window.kindName(r.kind) : r.kind); - if (r.ttft_ms) add("First token", ledTook(r.ttft_ms)); - // of it, what came before the request went to the vendor, and the - // vendor's wait from then to its first token. Before it, magpie's own - // time is told apart from the tries that failed first, a wait for a - // slot and connecting and sending the body (#1532: a vendor that held a - // try ~100 s before its 503 read as 104 s in magpie); a record from - // before they were kept has only the whole - if (r.ttft_ms && r.sent_ms) { - const split = r.own_ms != null; - add("In magpie", ledTook(split ? r.own_ms : r.sent_ms)); - if (split) { - if (r.retried_ms > 0) add("Tries that failed first", ledTook(r.retried_ms)); - if (r.queued_ms > 0) add("Waiting for a slot", ledTook(r.queued_ms)); - const sending = r.sent_ms - r.own_ms - (r.retried_ms || 0) - (r.queued_ms || 0); - if (sending > 0) add("Connecting and sending", ledTook(sending)); - } - add("Vendor's first token", ledTook(Math.max(0, r.ttft_ms - r.sent_ms))); - } - if (r.reasoning) add("Reasoning tokens", ledNum(r.reasoning)); - if (r.session_provider) add("Recorded provider ID", r.session_provider); - if (r.session_account) add("Session account", r.session_account); - if (r.source === "log" && r.session_account && r.session_official_login) add("Login method", t("Official login")); - if (r.pricing_model) add("API price reference", r.pricing_model); - // with the archive on, a request it has no copy of says so: from before - // it was on, or not through the gateway - if (!r.archive && !r.computer && (providers?.gateway?.archive?.on ?? state.settings?.requestArchive)) add("Request archive", t("Not archived"), "muted"); - if (r.source === "log") add("Data source", t("Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred."), "muted"); - const tr = el("tr", "led-detail"); - const td = el("td"); - td.colSpan = cols; - const box = el("div", "led-box"); - box.append(dl.childElementCount ? dl : el("span", "faint", t("Nothing more was kept of this request"))); - // the call as the request archive kept it, when it was on (#447) - if (r.archive) { - const ab = el("div", "led-archive"); - const draw = () => ab.replaceChildren(archivePanel(r.archive, "led|" + ledKey(r), draw)); - draw(); - box.append(ab); - } - // what was said: read from the agent's session file, when the row is - // opened; one made on another computer has its files there, and sync - // brings none of what was said - const cx = el("div", "led-cx"); - if (r.computer) { - cx.append(el("p", "cx-none", t("What was said stays on {computer}: sync shares the usage alone.", { computer: r.computerName || r.computer }))); - } else { - cx.append(el("p", "cx-none", t("Loading…"))); - ledLoadContent(r).then((c) => { if (cx.isConnected) cx.replaceChildren(ledContentBox(c)); }); - } - box.append(cx); - td.append(box); - tr.append(td); - return tr; -} - -// What was said in a request — what its agent was given, and what came back — -// is in the agent's own session file, and read from it when a row is opened -// (the server finds the call by its session and time); magpie keeps no copy. -// What came is kept here while the list is looked at, so a row opened again, or -// drawn again as the list is read anew, doesn't ask again. -const ledContent = new Map(); const ledExpanded = new WeakSet(); -function ledLoadContent(r) { - const key = ledKey(r); - if (!ledContent.has(key)) { - if (ledContent.size > 60) ledContent.delete(ledContent.keys().next().value); - const t0 = new Date(r.t).getTime(); - // a call of a session file is at its own time; a request the gateway logged began - // a little before the file wrote it, and the call is in the span it took - const [a, b] = r.source === "log" ? [t0 - 1, t0 + 1] : [t0 - 5e3, t0 + (r.ms || 0) + 30e3]; - // the window can hold the next calls of a quick tool loop too: the one that - // ended nearest the request's own end is its call - const at = r.source === "log" ? t0 : t0 + (r.ms || 0); - const q = new URLSearchParams({ agent: r.agent, session: r.native_session || r.session || "", from: new Date(a).toISOString(), to: new Date(b).toISOString(), at: new Date(at).toISOString() }); - const pending = api("usage/requests/content?" + q).catch(() => ({ found: false, why: "read" })).then((c) => { - if (!c.found && ledContent.get(key) === pending) ledContent.delete(key); - return c; - }); - ledContent.set(key, pending); - } - return ledContent.get(key); -} -const LED_WHY = { - session: "No session was named with this request, so its session file can't be found", - agent: "magpie reads the session files of Claude Code, Claude Desktop and Codex only", - missing: "This request isn't in the agent's session files: they may be deleted, moved, or not written yet", - read: "The session file couldn't be read", -}; const LED_KINDS = { tool_use: "Tool call", tool_result: "Tool result", thinking: "Thinking", context: "Context", image: "Image" }; const LED_ROLES = { user: "You", assistant: "Assistant", tool: "Tool" }; @@ -18011,33 +17173,6 @@ function ledSaid(p) { return part; } -function ledContentBox(c) { - const box = el("div", "cx"); - if (!c.found) { - box.append(el("p", "cx-none", t(LED_WHY[c.why] || LED_WHY.read))); - return box; - } - for (const [name, parts] of [["Input", c.input || []], ["Output", c.output || []]]) { - const sec = el("section", "cx-sec"); - sec.append(el("h4", "", t(name))); - if (!parts.length) sec.append(el("p", "cx-none", t("Nothing was said here"))); - for (const p of parts) sec.append(ledSaid(p)); - box.append(sec); - } - if (c.cut) box.append(el("p", "cx-none", t("There was more than is shown here"))); - box.append(el("p", "cx-src", t("Read from the agent's session file; magpie keeps no copy"))); - return box; -} - -// ---- the totals and the trend over the requests listed -// -// A strip of four totals, then the trend of one metric — tokens, cost or -// requests — as columns by the hour, day or week, each told apart by provider, -// agent or model, beside a ranking of the same: which is the chart's legend -// and a way in (a click on a provider or agent lists only its requests). The -// server sums it all (the ledger's "series" and "by"); the tray panel's Usage -// tab draws the same from the same answer. - // a cost as an axis says it: the currency Settings picks, no more digits than it takes function ledMoney(v) { let sign = "$"; @@ -18046,20 +17181,8 @@ function ledMoney(v) { } const LED_METRICS = [["tokens", "Tokens"], ["cost", "Cost"], ["calls", "Requests"]]; -// the window's chart can also say how fast the replies came (#860) -const LED_TREND = [...LED_METRICS, ["speed", "Speed"]]; -// "modelAt" is a model at the provider it went to, so one model's speed at -// each provider is ranked side by side (inaction on Discord) -const LED_SPLITS = [["model", "Model"], ["modelAt", "Model · provider"], ["provider", "Provider"], ["agent", "Agent"]]; const LED_SHOWN = 7; // told apart in a chart; the rest are "Other" const allTokens = (x) => x.input + x.output + x.cache_read + x.cache_write; -// cacheTTLs: a call's cache writes split by how long they are kept, where -// some were for an hour (Anthropic bills those at 2× input, 5 minutes' -// at 1.25×); nothing when none were -function cacheTTLs(x, fmt) { - const h = Math.min(x.cache_write_1h || 0, x.cache_write || 0); - return h ? " · " + t("{m} for 5 minutes, {h} for an hour", { m: fmt(x.cache_write - h), h: fmt(h) }) : ""; -} // how fast the timed replies of a point, a share or a part wrote, in tokens // a second after their first (usage.Totals.Speed): 0 for none timed const ledSpeed = (x) => x?.decode_ms > 0 ? (1000 * x.decode_out) / x.decode_ms : 0; @@ -18395,1149 +17518,9 @@ function ledRankEdges(box) { rail.firstChild.style.transform = `translateY(${((h - thumb) * box.scrollTop) / end}px)`; } -// the rail's thumb drags the ranking; a click on the rail takes it there -function ledRail(rail, box) { - box.rail = rail; - rail.onpointerdown = (e) => { - if (e.button !== 0) return; - e.preventDefault(); - const end = box.scrollHeight - box.clientHeight, thumb = rail.firstChild.offsetHeight, room = rail.clientHeight - thumb; - if (end <= 0 || room <= 0) return; - if (e.target !== rail.firstChild) { - // the thumb's middle to where the rail was clicked - const y = e.clientY - rail.getBoundingClientRect().top - thumb / 2; - box.scrollTop = (Math.max(0, Math.min(room, y)) / room) * end; - } - const y0 = e.clientY, top0 = box.scrollTop; - rail.setPointerCapture(e.pointerId); - rail.classList.add("drag"); - rail.onpointermove = (m) => { box.scrollTop = top0 + ((m.clientY - y0) / room) * end; }; - rail.onpointerup = rail.onpointercancel = () => { - rail.classList.remove("drag"); - rail.onpointermove = rail.onpointerup = rail.onpointercancel = null; - }; - }; -} - -// the request list's status filter: "" for all, "failed" or "retried" -const ledStatusOf = () => ledFailed ? "failed" : ledRetried ? "retried" : ""; -function ledShowStatus(to) { - if (to === ledStatusOf()) return; - ledFailed = to === "failed"; - ledRetried = to === "retried"; - ledOffset = 0; - loadLedger().catch((e) => status(e.message, "err")); -} - -function renderLedgerDash(l) { - const dash = $("#ledDash"); - dash.hidden = !l.total && !l.day; - if (dash.hidden) return; - const total = allTokens(l); - const prompt = l.input + l.cache_write + l.cache_read; - const rate = prompt ? l.cache_read / prompt : 0; - const strip = $("#ledKpi"); - strip.replaceChildren(); - const block = (label, value, sub, cls, title) => { - const b = el("div", "blk"); - if (title) b.title = title; - // a value in parts (an array) keeps each whole, wrapping between them - const v = el("span", "v" + (cls ? " " + cls : "") + (Array.isArray(value) ? " parts" : ""), Array.isArray(value) ? undefined : value); - // (a space between two stays out of them: one leading a part is dropped) - if (Array.isArray(value)) value.forEach((x, i) => v.append(...(i && /^\s/.test(x) ? [" "] : []), el("span", "", x.trim()))); - b.append(el("span", "k", t(label)), v); - if (sub) b.append(sub); - strip.append(b); - return b; - }; - const line = (...parts) => { const s = el("span", "sub"); s.append(...parts); return s; }; - // a line holding a count's button wraps rather than cut the button off - // (German's "nach erneutem Versuch beantwortet" runs past a narrow card) - const jumps = (...parts) => { const s = line(...parts); s.classList.add("jumps"); return s; }; - block("Tokens", fmtN(total), line(t("{a} in · {b} out", { a: fmtN(l.input), b: fmtN(l.output) }), " · ", t("{a} cache", { a: fmtN(l.cache_read + l.cache_write) })), "", ledNum(total)); - // a request is counted once, by how it ended: one a later try answered - // is not a failure, and is counted beside them as answered on a retry - // (小一 on Discord). Each count is a button for its requests in the list. - const jump = (text, to, title) => { - const b = el("button", "led-jump" + (to === "failed" ? " bad" : "") + (ledStatusOf() === to ? " on" : ""), text); - b.type = "button"; - b.title = title; - b.setAttribute("aria-pressed", ledStatusOf() === to ? "true" : "false"); - b.onclick = () => ledShowStatus(ledStatusOf() === to ? "" : to); - return b; - }; - block("Requests", ledNum(l.calls), l.errors - ? jumps(jump(t("{n} failed", { n: ledNum(l.errors) }), "failed", t("Show only the failed requests")), " · " + t("{p} succeeded", { p: (100 * (1 - l.errors / l.calls)).toFixed(1) + "%" })) - : line(t("none failed"))); - if (l.retried) strip.lastChild.append(jumps(jump(t("{n} answered on a retry", { n: ledNum(l.retried) }), "retried", t("Show only the requests answered on a retry")))); - const c = fmtCost(l); - block("Cost", c ? "≈" + c : "—", line(l.unpriced ? t(l.unpriced === 1 ? "{n} call had no known price and is not counted" : "{n} calls had no known price and are not counted", { n: l.unpriced }) : t("effective prices")), c ? "cost" : ""); - const hit = block("Cache hit rate", (100 * rate).toFixed(1) + "%", null, "", t("The share of the prompt read from the cache")); - const meter = el("div", "meter"), fill = el("i"); - fill.style.width = (100 * rate).toFixed(1) + "%"; - meter.append(fill); - hit.append(meter); - // how fast the streamed replies wrote, and how long they took to begin (#860): - // the figure of more replies, its count beside it; the other under it; the - // wait for the first token on a line of its own, with how many it is of - // (Fallmonkey on Discord) - const gs = ledGroupSpeed(l); - const ttft = ledTTFT(l) ? t("first token in {ms} on average", { ms: ledTook(ledTTFT(l)) }) + " · " + t(l.timed === 1 ? "{k} timed reply" : "{k} timed replies", { k: ledNum(l.timed) }) : t("no streamed replies timed"); - const speedCard = block("Output speed", gs ? gs.mainParts : "—", gs?.other ? line(gs.other) : null, - "", [gs?.title, t("Output tokens a second after the first, over the streamed replies") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it") + ". " + t("No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed")].filter(Boolean).join("\n")); - speedCard.append(Object.assign(line(ttft), { className: "sub ttft" })); - drawLedTrend(); -} - -function drawLedTrend() { - const l = ledger; - if (!l || $("#ledDash").hidden) return; - // the two switches - const pill = (host, key, opts, cur, pick) => { - host.replaceChildren(); - for (const [id, name] of opts) { - const b = el("button", "opt" + (id === cur ? " on" : ""), t(name)); - b.onclick = () => { if (id !== cur) pick(id); }; - host.append(b); - } - slide(host, key); - }; - pill($("#ledMetric"), "ledMetric", LED_TREND, ledMetric, (id) => { ledMetric = id; try { localStorage.setItem("magpie.ledMetric", id); } catch {} drawLedTrend(); }); - pill($("#ledSplit"), "ledSplit", LED_SPLITS, ledSplit, (id) => { ledSplit = id; drawLedTrend(); }); - const chart = $("#ledChart"), rank = $("#ledRank"); - drawLedColumns(chart, l, ledSplit, ledMetric, false, (day) => { - ledDay = ledDay === day ? "" : day; - ledOffset = 0; - loadLedger().catch((e) => status(e.message, "err")); - }); - rank.chart = chart; - if (!rank.rail) ledRail($("#ledRail"), rank); - const picked = ledSplit === "provider" ? ledProvider : ledSplit === "agent" ? ledAgent - : ledSplit === "modelAt" ? (ledProvider && ledModel ? ledProvider + "/" + ledModel : "") : ledModel; - drawLedRank(rank, l, ledSplit, ledMetric, picked, (x) => { - // a click lists only that one's requests; on the one listed, all again - if (ledSplit === "modelAt") { - // provider/model: both filters, the provider's id has no "/" - const q = $("#ledQ"), cut = x.id.indexOf("/"), off = picked === x.id; - ledProvider = off ? "" : x.id.slice(0, cut); - ledModel = off ? "" : x.id.slice(cut + 1); - ledQuery = ledModel; q.value = ledQuery; - } else if (ledSplit === "provider") ledProvider = ledProvider === x.id ? "" : x.id; - else if (ledSplit === "agent") ledAgent = ledAgent === x.id ? "" : x.id; - else { const q = $("#ledQ"); ledModel = ledModel === x.id ? "" : x.id; ledQuery = ledModel; q.value = ledQuery; } - ledOffset = 0; - loadLedger().catch((e) => status(e.message, "err")); - }, false); -} -// ---------- the heatmap (#1369) ---------- -// -// The last 53 weeks a day each, Monday on top, as a calendar of -// contributions lays them out: each day as dark as it is busy among the -// others, by tokens, requests or cost. It is of the requests the filters -// above keep, whatever the period (the server's /api/usage/heatmap, read -// from the same index as the page), its days in the gateway's time zone. A -// narrow window scrolls it sideways inside its card, the newest week in -// sight; the pointer on a day says its date and what it had. -let ledHeat = null, ledHeatWant = "", ledHeatMetric = "tokens"; -try { - const m = localStorage.getItem("magpie.ledHeatMetric"); - if (["tokens", "calls", "cost"].includes(m)) ledHeatMetric = m; -} catch {} -const LED_HEAT = [["tokens", "Tokens"], ["calls", "Requests"], ["cost", "Cost"]]; -function ledHeatParams() { - const q = new URLSearchParams(ledParams()); - q.delete("period"); - q.delete("day"); - return q.toString(); -} -async function loadLedHeat() { - const want = ledHeatParams(); - ledHeatWant = want; - const h = await ledRead("heat", "usage/heatmap?", want).catch((e) => { if (ledAborted(e)) return ledAborted; throw e; }); - if (h === ledAborted) return; - if (want !== ledHeatWant) return; // another filter was picked meanwhile - if (ledHeat && ledHeat.want === want && JSON.stringify(ledHeat.data) === JSON.stringify(h)) return; - ledHeat = { want, data: h }; - if (view === "usage" && usageTab === "requests") drawLedHeat(); -} -const ledHeatDate = (s) => { const [y, m, d] = String(s).split("-").map(Number); return new Date(y, m - 1, d); }; -function ledHeatTip(x) { - const loc = intlLang(); - const tip = el("div"); - tip.append(el("b", "", x.day.toLocaleDateString(loc, { year: "numeric", month: "short", day: "numeric", weekday: "short" }))); - if (!x.calls) { - tip.append(el("span", "", t("No requests"))); - return tip; - } - const parts = [t("{n} tokens", { n: fmtN(x.tokens) }), t(x.calls === 1 ? "{n} request" : "{n} requests", { n: ledNum(x.calls) })]; - const c = fmtCost(x); - if (c) parts.push("≈" + c); - const order = { tokens: 0, calls: 1, cost: 2 }[ledHeatMetric]; - if (order && parts[order]) parts.unshift(...parts.splice(order, 1)); // the metric shown first - tip.append(el("span", "", parts.join(" · "))); - return tip; -} -function drawLedHeat() { - const box = $("#ledHeat"), h = ledHeat?.data; - const at = new Map((h?.days || []).map((d) => [d.date, d])); - box.hidden = !h?.from || !h?.to || ![...at.values()].some((d) => d.calls > 0); - if (box.hidden) return; - const first = ledHeatDate(h.from), last = ledHeatDate(h.to); - const days = []; - for (const d = new Date(first); d <= last; d.setDate(d.getDate() + 1)) { - const x = at.get(sessISO(d)) || { calls: 0, tokens: 0, cost: 0 }; - days.push({ ...x, day: new Date(d) }); - } - const value = (x) => ledHeatMetric === "cost" ? x.cost : ledHeatMetric === "calls" ? x.calls : x.tokens; - const lv = sessLevels(days.map(value)); - const seg = $("#ledHeatMetric"); - seg.replaceChildren(); - for (const [id, name] of LED_HEAT) { - const b = el("button", "opt" + (id === ledHeatMetric ? " on" : ""), t(name)); - b.type = "button"; - b.onclick = () => { - if (id === ledHeatMetric) return; - ledHeatMetric = id; - try { localStorage.setItem("magpie.ledHeatMetric", id); } catch {} - drawLedHeat(); - }; - seg.append(b); - } - slide(seg, "ledHeatMetric"); - const scroll = $("#ledHeatScroll"); - // the same days in the same language keep their cells, coloured again, so - // a refresh moves nothing and the scroll stays where the reader left it - const shape = [h.from, h.to, locale].join("|"); - let grid = scroll.querySelector(".heat-grid"); - if (!grid || grid.dataset.shape !== shape) { - grid = el("div", "heat-grid"); - grid.dataset.shape = shape; - grid.setAttribute("role", "img"); - const names = sessWeekdays(); - // every row has its place at the edge, named every other day - for (let i = 0; i < 7; i++) { - const l = el("span", "wd", i % 2 ? "" : names[i]); - l.style.gridArea = `${i + 2} / 1`; - grid.append(l); - } - const loc = intlLang(); - const weeks = Math.ceil(days.length / 7), labels = []; - let month = -1; - days.forEach((x, i) => { - const w = Math.floor(i / 7), wd = i % 7; - if (wd === 0 && x.day.getMonth() !== month) { - month = x.day.getMonth(); - // a month mostly gone in the first week is left unnamed, so as not - // to crowd out the next one's name, and so is one begun in the last - // week, with no room for its name - if ((!labels.length || w - labels.at(-1).w >= 3) && !(w === 0 && x.day.getDate() > 14) && w < weeks - 1) { - const m = el("span", "mo", x.day.toLocaleDateString(loc, { month: "short" })); - labels.push({ m, w }); - grid.append(m); - } - } - const c = el("i"); - c.dataset.date = sessISO(x.day); - c.style.gridArea = `${wd + 2} / ${w + 2}`; - grid.append(c); - }); - // a month's name spans its weeks up to the next name, cut there, so a - // long one never widens the grid past its last week - labels.forEach(({ m, w }, i) => { m.style.gridArea = `1 / ${w + 2} / 2 / ${(labels[i + 1]?.w ?? weeks) + 2}`; }); - grid.onpointerover = (e) => { if (e.target.dataset?.date) ledHeatShow(e.target); }; - grid.onpointerleave = () => { $("#ledHeatTip").hidden = true; }; - scroll.replaceChildren(grid); - if (!scroll.onscroll) { - // the newest week in sight, by the card's own scroll, never the page's: - // kept there as the card is laid out or resized, until the reader - // scrolls it back, and again once they scroll to the end - scroll.onscroll = () => { - $("#ledHeatTip").hidden = true; - // its own scroll to the end, seen after the card narrowed, is not the reader's - if (scroll.clientWidth && scroll.scrollLeft !== ledHeatSetAt) ledHeatAtEnd = scroll.scrollLeft >= scroll.scrollWidth - scroll.clientWidth - 2; - }; - } - ledHeatSized.disconnect(); - ledHeatSized.observe(scroll); - ledHeatSized.observe(grid); - ledHeatKeepEnd(); - } - grid.setAttribute("aria-label", t("Usage heatmap")); - const cells = grid.querySelectorAll("i"); - days.forEach((x, i) => { - const c = cells[i]; - c.className = "l" + lv(value(x)); - c.day = x; - }); - const legend = box.querySelector(".heat-foot"); - legend.replaceChildren(sessLegend()); - const tip = $("#ledHeatTip"); - if (!tip.hidden && tip.cell?.isConnected) ledHeatShow(tip.cell); - else tip.hidden = true; -} -let ledHeatAtEnd = true, ledHeatSetAt = -1; -const ledHeatSized = new ResizeObserver(() => ledHeatKeepEnd()); -function ledHeatKeepEnd() { - const scroll = $("#ledHeatScroll"); - if (!ledHeatAtEnd || !scroll.clientWidth || scroll.scrollWidth <= scroll.clientWidth) return; - scroll.scrollLeft = scroll.scrollWidth; - ledHeatSetAt = scroll.scrollLeft; -} -// the tip over a day, above it, kept inside the card -function ledHeatShow(cell) { - const box = $("#ledHeat"), tip = $("#ledHeatTip"); - if (!cell.day) return; - tip.replaceChildren(...ledHeatTip(cell.day).children); // the date over the figures - tip.cell = cell; - tip.hidden = false; - const b = box.getBoundingClientRect(), c = cell.getBoundingClientRect(); - const w = tip.offsetWidth, hgt = tip.offsetHeight; - const left = Math.max(6, Math.min(b.width - w - 6, c.left - b.left + c.width / 2 - w / 2)); - let top = c.top - b.top - hgt - 6; - if (top < 4) top = c.bottom - b.top + 6; - tip.style.left = left + "px"; - tip.style.top = top + "px"; -} -// the table's scrollbar, kept in view at the window's foot (#799): as wide -// as the table can go sideways, and moving it as the table moves it -function ledHScroll() { - const wrap = $("#ledWrap"), bar = $("#ledHScroll"); - const over = !!wrap.querySelector("table") && wrap.scrollWidth > wrap.clientWidth + 1; - bar.hidden = !over; - if (!over) return; - bar.firstElementChild.style.width = wrap.scrollWidth - wrap.clientWidth + bar.clientWidth + "px"; - bar.scrollLeft = wrap.scrollLeft; -} -$("#ledWrap").addEventListener("scroll", () => { const bar = $("#ledHScroll"); if (bar.scrollLeft !== $("#ledWrap").scrollLeft) bar.scrollLeft = $("#ledWrap").scrollLeft; }, { passive: true }); -$("#ledHScroll").addEventListener("scroll", () => { const wrap = $("#ledWrap"); if (wrap.scrollLeft !== $("#ledHScroll").scrollLeft) wrap.scrollLeft = $("#ledHScroll").scrollLeft; }, { passive: true }); -// a window that changes size redraws the chart at its new width -// a new width fits the table again, on the next frame, and so do the -// details' width (--ledw) and the scrollbar: each changes the table's or the -// wrap's height, which this would be told of in its own call, and WebKit -// reports that as a ResizeObserver loop (number-units' page error) -let ledFitW = 0, ledFitFrame = 0; -new ResizeObserver(() => { - if (ledFitFrame) return; - ledFitFrame = requestAnimationFrame(() => { - ledFitFrame = 0; - const wrap = $("#ledWrap"); - wrap.style.setProperty("--ledw", wrap.clientWidth + "px"); - if (wrap.clientWidth !== ledFitW) { ledFitW = wrap.clientWidth; ledFit(); } - ledHScroll(); - }); -}).observe($("#ledWrap")); -// a table that grows past the window when its width didn't change (a font -// arriving, a redraw while out of sight) leaves its columns out then too; -// and its scrollbar goes once a table left without them has come to fit, -// rather than staying under a table with nothing to scroll -let ledGrowFrame = 0; -const ledGrow = new ResizeObserver(() => { - if (ledGrowFrame) return; - ledGrowFrame = requestAnimationFrame(() => { - ledGrowFrame = 0; - const wrap = $("#ledWrap"), table = wrap.querySelector("table.led"); - if (table && !table.classList.contains("tighter") && wrap.clientWidth && wrap.scrollWidth > wrap.clientWidth + 1) ledFit(); - ledHScroll(); - }); -}); -new ResizeObserver(() => { - if (!ledger || usageTab !== "requests" || view !== "usage" || $("#ledDash").hidden) return; - drawLedColumns($("#ledChart"), ledger, ledSplit, ledMetric, false); - ledRankEdges($("#ledRank")); -}).observe($("#ledChart")); - -// the third: a column a narrow window leaves out, its value in the row's -// details (#860) -const LED_COLS = [ - ["Time"], ["Agent"], ["Requested"], ["Provider · account"], ["Sent", "", true], ["Served"], ["Effort", "", true], - ["In", "n"], ["Out", "n"], ["Cache write", "n", true], ["Cache read", "n", true], ["Cost", "n"], ["Duration", "n"], ["Speed", "n"], ["Status"], -]; - -// the tokens a reply was seen to write and the ms it took, as -// usage.DecodeOf and routing/client.js's decodeOf tell them: one that reasoned -// counts its answer from its first text, its reasoning written before -// the stream showed any (tony on Discord); null when it tells no speed. -// A reply held back and let go in a burst at its end tells none (John on -// Discord): its content came in under a quarter of its window (flow_ms), -// or its answer at over 20 times the pace its reasoning came before it -const ledDecode = (r) => { - if (ledFailed_(r) || r.reasoning_hidden && !(r.first_text_ms > 0) || !(r.ttft_ms > 0)) return null; - const think = r.reasoning > 0, visible = think && !(r.first_text_ms > 0) && r.first_reasoning_ms >= r.ttft_ms && r.flow_ms > 0 && r.reasoning <= r.out; - const n = think && !visible ? r.out - r.reasoning : r.out, from = visible ? r.first_reasoning_ms : think ? r.first_text_ms : r.ttft_ms; - const w = r.ms - from; - if (!(n > 0 && from > 0 && w >= 100 && n * 1000 <= 10000 * w)) return null; - if (r.flow_ms > 0 && r.flow_ms * 4 < w) return null; - if (think && r.first_text_ms > 0 && n * (r.first_text_ms - r.ttft_ms) > 20 * r.reasoning * w) return null; - if (ledCodexTurn(r) && (w < LED_CODEX_WINDOW_MS || n < LED_CODEX_BODY)) return null; - return { n, w }; -}; -// a Codex turn of one call read from its session file, its first token -// known: its window after the first token can be one network push, not the -// writing (Fallmonkey on Discord: a first token at 6.8 s, the rest 0.2 s -// later), so it tells a speed only over a second or more and 100 tokens or -// more (usage.CodexWindowMs, CodexBodyTokens); else ledFloor_ tells the -// least it wrote at over the whole turn -const LED_CODEX_WINDOW_MS = 1000, LED_CODEX_BODY = 100; -const ledCodexTurn = (r) => r.source === "log" && r.agent === "codex" && r.ttft_ms > 0; -// how fast a reply wrote, in tokens a second: 0 when it can't tell -const ledRowSpeed = (r) => { const d = ledDecode(r); return d ? d.n / (d.w / 1000) : 0; }; -// the least a reply read from a session file wrote at, in tokens a second: -// the file has no first token, only when the line that asked for it and its -// last line were written (Claude Code's are each block's end), so its tokens -// over that whole time, the wait for the first one in it, are a floor the -// speed after the first token can't be under. Against Claude Code's own -// stream it read 2–5% under for a reply of 1,400 tokens or more, 11–33% for -// a shorter one or one asked with a tool's result, so only a reply of 1,000 -// or more is told. 0 when it tells none, and a call magpie timed tells its -// own (ledDecode). Only the row's: the period's speed counts timed calls. -// Claude Code's, Claude Desktop's and Codex's files only (usage.FloorAgents): -// a call's time is from what asked for it, never from inside it. OpenCode's -// isn't checked against real sessions, and tells none. -// A Codex turn of one call that reasoned has its first token but not its -// first text (Fallmonkey on Discord): its answer, its output less the -// reasoning, all came after the first token, so the answer over the time -// after it is a floor of the answer's speed, when that time is a second or -// more and the answer 100 tokens or more, as a measured one is. A Codex turn -// of one call that tells neither tells its output over the whole turn, the -// wait in it, by the same 1,000-token rule as any whole-time floor (Fallmonkey -// on Discord: 11 tokens in 2.75 s read ≥4 tok/s). ledFloor_ says the tokens, -// the ms, and which it is (answer, turn). -const LED_FLOOR_AGENTS = new Set(["claude", "claude-desktop", "codex"]); -const ledFloor_ = (r) => { - if (r.source !== "log" || !LED_FLOOR_AGENTS.has(r.agent) || ledFailed_(r) || ledRowSpeed(r)) return null; - if (ledCodexTurn(r)) { - const n = r.out - (r.reasoning || 0), w = r.ms - r.ttft_ms; - if (r.reasoning > 0 && n >= LED_CODEX_BODY && w >= LED_CODEX_WINDOW_MS && n * 1000 <= 10000 * w) return { n, w, answer: true }; - return r.out >= 1000 && r.ms >= 1000 && r.out * 1000 <= 10000 * r.ms ? { n: r.out, w: r.ms, turn: true } : null; - } - return r.out >= 1000 && r.ms >= 1000 && r.out * 1000 <= 10000 * r.ms ? { n: r.out, w: r.ms } : null; -}; -const ledFloorSpeed = (r) => { const f = ledFloor_(r); return f ? f.n / (f.w / 1000) : 0; }; - -// the table as wide as the window, when leaving out what the row's details -// say anyway makes it so: else it scrolls sideways (#799) -function ledFit() { - const wrap = $("#ledWrap"), table = wrap.querySelector("table.led"); - let hint = $("#ledTight"); - if (!table) { if (hint) hint.hidden = true; return; } - table.classList.remove("tight", "tighter"); - const over = () => wrap.scrollWidth > wrap.clientWidth + 1; - const tight = over(); - table.classList.toggle("tight", tight); - // still too wide (#860: a Windows window at 175%, its wider fonts): the - // price reference line goes too, in the cost's tooltip and the details - // as well, and names are cut shorter, whole in their tooltips - if (tight && over()) table.classList.add("tighter"); - if (!hint) { - hint = el("span", "led-tight"); - hint.id = "ledTight"; - $("#ledSum").after(hint); - } - hint.textContent = hint.title = t("Sent, Effort and the cache are in each row's details"); - hint.hidden = !tight; -} - -function renderLedger() { - const l = ledger; - const callers = l.callerKeys || []; - const providers = l.providers || []; - const missingAgent = ledAgent && !l.agents.some((a) => a.id === ledAgent); - const missingProvider = ledProvider && !providers.some((p) => p.id === ledProvider); - const accounts = l.accounts || []; - const missingAccount = ledAccount && !accounts.some((a) => a.id === ledAccount); - const missingCaller = ledCallerKey && !callers.some((k) => k.id === ledCallerKey); - const computers = computerOpts(l.computers); - const missingComputer = ledComputer && !computers.some((c) => c.v === ledComputer); - if (missingAgent || missingProvider || missingAccount || missingCaller || missingComputer) { - if (missingComputer) ledComputer = ""; - if (missingAccount) ledAccount = ""; - if (missingAgent) ledAgent = ""; - if (missingProvider) ledProvider = ""; - if (missingCaller) ledCallerKey = ""; - ledOffset = 0; - // Reload the rows too: this response still belongs to the missing filters. - loadLedger().catch((e) => status(e.message, "err")); - return; - } - const view = $("#view-usage"); - view.classList.remove("loading"); - view.removeAttribute("aria-busy"); - renderPeriod(); - renderArchive(); - - costHead(fmtCost(l), l.unpriced ? unpricedCalls(l.unpriced) : "", unpricedCallsWhy(l.unpriced)); - - // the filters: choices seen in the period, and failures alone - sessPick($("#ledPurpose"), "All purposes", ledPurpose, purposeOptions(l.purposes || [], ledPurpose), "Purpose", (v) => { ledPurpose = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); }); - $("#ledPurpose").title = t("Purpose"); - sessPick($("#ledComputer"), "All computers", ledComputer, computers, "Computer", (v) => { ledComputer = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); }); - sessPick($("#ledAgent"), "All agents", ledAgent, l.agents.map((a) => ({ v: a.id, name: a.name, note: "" })), "Agent", (v) => { ledAgent = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); }); - sessPick($("#ledProvider"), "All providers", ledProvider, providers.map((p) => ({ v: p.id, name: t(p.name), note: "" })), "Provider", (v) => { ledProvider = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); }); - sessPick($("#ledAccount"), "All accounts", ledAccount, accounts.map((a) => ({ v: a.id, name: a.id, note: (a.providers || []).map((p) => t(p)).join(" · ") })), "Account", (v) => { ledAccount = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); }); - sessPick($("#ledKey"), "All gateway keys", ledCallerKey, callers.map((k) => ({ - v: k.id, name: k.name, note: "", - })), "Gateway keys", (v) => { ledCallerKey = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); }); - const seg = $("#ledStatus"); - seg.replaceChildren(); - // every request, those the agent got an error for, and those answered - // after a try that failed first - const shown = ledStatusOf(); - for (const [on, name] of [["", "All"], ["failed", "Failed"], ["retried", "Retried"]]) { - const b = el("button", "opt" + (on === shown ? " on" : ""), t(name)); - if (on === "retried") b.title = t("Show only the requests answered on a retry"); - b.onclick = () => { - if (on === ledStatusOf()) return; - for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b); - slide(seg, "ledStatus"); - ledShowStatus(on); - }; - seg.append(b); - } - slide(seg, "ledStatus"); - $("#ledExport").disabled = !l.total; - - const sum = [t(l.total === 1 ? "{n} request" : "{n} requests", { n: ledNum(l.total) })]; - if (l.total) { - sum.push(t("{n} in", { n: fmtN(l.input) }), t("{n} out", { n: fmtN(l.output) }), t("{n} cache write", { n: fmtN(l.cache_write) }), t("{n} cache read", { n: fmtN(l.cache_read) })); - if (l.errors) sum.push(t("{n} failed", { n: l.errors })); - if (l.retried) sum.push(t("{n} answered on a retry", { n: l.retried })); - } - $("#ledSum").textContent = sum.join(" · "); - // the two sources and their total, in the same block of cells as the totals - // above them: what magpie carried, what it only read about in the agents' - // own session files, and the two together. Each is a filter: picking one - // lists only its requests, and the total is the way back. Its own numbers - // are counted with the pick cleared (usage.RequestPage), so all three stay - // switchable whichever is on. - const via = $("#ledVia"); - const thru = l.through || { calls: 0 }, dir = l.direct || { calls: 0 }, rep = l.reported || { calls: 0 }; - if (thru.calls + dir.calls + rep.calls > 0) { - // the total is the two sources added up, not the page's own totals: those - // are the rows the filter keeps, so with one source picked the total cell - // would read that one's figures under the whole period's count - const all = {}; - for (const k of ["calls", "errors", "input", "output", "cache_read", "cache_write", "cost", "timed", "ttft_ms", "decode_ms", "decode_out"]) { - all[k] = (thru[k] || 0) + (dir[k] || 0) + (rep[k] || 0); - } - const tile = (b, label, calls, tot, pick) => { - const on = ledVia === pick; - b.className = "blk" + (on ? " on" : ""); - b.type = "button"; - b.setAttribute("aria-pressed", on ? "true" : "false"); - b.title = pick ? t("Show only these requests") : t("Show every request again"); - const v = el("span", "v", ledNum(calls)); - // the unit, so a bare number isn't read as the tokens below it - v.append(el("em", "", t(calls === 1 ? "request" : "requests"))); - b.replaceChildren(el("span", "k", t(label)), v, - el("span", "sub", t("{n} tokens", { n: fmtN(allTokens(tot)) }))); - b.onclick = () => { - const next = ledVia === pick ? "" : pick; - if (next === ledVia) return; - ledVia = next; - ledOffset = 0; - loadLedger().catch((e) => status(e.message, "err")); - }; - return b; - }; - // the calls apps reported themselves (#1874) are a fourth cell, once - // there are some, or while they are the ones picked - const n = rep.calls > 0 || ledVia === "reported" ? 4 : 3; - // the cells are the same elements from one redraw to the next, so - // one being pressed or focused is never swapped out from under a reader - let cells = [...via.children]; - if (cells.length !== n) { - cells = cells.slice(0, n); - while (cells.length < n) cells.push(el("button")); - via.replaceChildren(...cells); - } - via.style.setProperty("--vias", String(n)); - tile(cells[0], "all requests", thru.calls + dir.calls + rep.calls, all, ""); - tile(cells[1], "through magpie", thru.calls, thru, "through"); - tile(cells[2], "not through magpie", dir.calls, dir, "direct"); - if (n === 4) tile(cells[3], "reported by apps", rep.calls, rep, "reported"); - via.hidden = false; - } else { - via.replaceChildren(); - via.hidden = true; - } - const routeFilter = $("#ledRoute"); - routeFilter.hidden = !ledRoute; - $("#ledRouteLabel").textContent = ledRouteInfo ? t("Request: {what}", { what: new Date(ledRouteInfo.time).toLocaleString(intlLang()) + " · " + ledRouteInfo.model }) : ""; - $("#ledRouteClear").title = t("Clear filter"); - $("#ledRouteClear").setAttribute("aria-label", t("Clear filter")); - $("#ledRouteClear").onclick = () => { - ledRoute = 0; ledRouteInfo = null; - if (ledBeforeRoute) ({ period, ledOffset, ledPurpose = "", ledAgent, ledProvider, ledAccount = "", ledCallerKey, ledFailed, ledRetried = false, ledQuery, ledModel, ledComputer = "", ledDay = "", ledVia = "" } = ledBeforeRoute); - ledBeforeRoute = null; - $("#ledQ").value = ledQuery; - loadLedger().catch((e) => status(e.message, "err")); - }; - renderLedgerDash(l); - drawLedHeat(); - - const wrap = $("#ledWrap"); - const pager = $("#ledPager"); - if (!l.total) { - wrap.classList.add("none"); - const filtered = ledPurpose || ledDay || ledRoute || ledAgent || ledProvider || ledAccount || ledComputer || ledCallerKey || ledModel || ledVia || ledFailed || ledRetried || ledQuery.trim(); - const none = noCallsIn(period); - wrap.replaceChildren(el("div", "led-none", filtered ? t("No requests match these filters.") : t(none))); - ledFit(); - ledHScroll(); - pager.hidden = true; - $("#ledNote").textContent = ""; - return; - } - wrap.classList.remove("none"); - const table = el("table", "led"); - const head = el("tr"); - for (const [name, cls, opt] of LED_COLS) head.append(el("th", (cls || "") + (opt ? " lc-opt" : ""), t(name))); - table.append(el("thead"), el("tbody")); - table.tHead.append(head); - for (const r of l.rows) { - const bad = ledFailed_(r); - const key = ledKey(r); - const tr = el("tr", "led-row" + (bad ? " bad" : "") + (ledOpen.has(key) ? " open" : "")); - tr.tabIndex = 0; - tr.setAttribute("aria-expanded", ledOpen.has(key) ? "true" : "false"); - const td = (child, cls, title) => { - const c = el("td", (cls || "") + (LED_COLS[tr.childElementCount]?.[2] ? " lc-opt" : "")); - if (typeof child === "string") c.textContent = child; else c.append(child); - if (title) c.title = title; - tr.append(c); - return c; - }; - const routed = r.route_id && !featuresOff.has("routing"); // the Routing page there to open it on - const when = routed ? el("button", "text led-route-link", ledTime(r.t)) : ledTime(r.t); - if (routed) { - when.title = t("View routing"); - // the link opens the route, not the row's details as well - when.onclick = (e) => { e.stopPropagation(); window.openRoute(r.route_id, r.t).catch((err) => status(err.message, "err")); }; - } - td(when, "when", new Date(r.t).toLocaleString(intlLang())); - const who = el("span", "who"); - // an agent on another computer, whose magpie passed the request on - const name = r.agentName || r.agent; - // one made on another computer, whose usage sync brought (#542) - const at = r.computerName ? t("{agent} · on {computer}", { agent: name, computer: r.computerName }) : name; - who.append(icon(r.icon || "generic"), el("span", "", [r.via ? t("{agent} · via {host}", { agent: at, host: r.via }) : at, r.callerKeyLabel || r.callerKeyName].filter(Boolean).join(" · "))); - // a request magpie made by itself, apart from the agents' own (#1839) - if (r.agent === "magpie") who.append(ownBadge()); - td(who, "", [r.kind, r.session && t("session {id}", { id: r.session })].filter(Boolean).join(" · ")); - td(r.req || "—", "model" + (r.req ? "" : " faint"), r.req || t("Not kept for requests before this version")); - const local = r.source === "log"; - // A session file names the provider it was set up to call, which is - // where a call that went straight to a vendor went: nothing stood - // between the agent and it. It is the file's own record and not a route - // magpie saw, so the id the file carries is shown as it is — never - // resolved to a provider's name, which would promote an unknown request - // to an official provider — and the row keeps saying it is a local - // session. A row whose file names none says only that. - const where = local ? (r.session_account || r.session_provider || t("Local session")) : t(r.providerName) + (r.host ? " · " + r.host : ""); - const wc = td(el("div", "where-name", where), "where", where); - const badges = el("div", "source-badges"); - if (local && r.session_account && r.session_official_login) { - const badge = el("span", "src official", t("OFFICIAL")); - badge.title = t("Official login confirmed for this account by local login metadata. This does not establish the route or authentication used for this request."); - badges.append(badge); - } - let access = ""; - if (!local && r.access === "subscription") access = "Subscription"; - else if (!local && r.access === "api") access = "API"; - if (access) { - const badge = el("span", "src access access-" + r.access, t(access)); - badge.title = t(access); - badges.append(badge); - } - const proto = ledProtoBadge(r); - if (proto) badges.append(proto); - // the badge says where the row came from, beside a name that is not - // that: a row whose name already says it has nothing to add - if (local && (r.session_account || r.session_provider)) { - const k = el("span", "src local", t("Local session")); - k.title = r.session_provider - ? t("Read from the agent's session file, which names the provider it was set up to call. The name shown is that record, not a route magpie saw.") - : t("Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred."); - badges.append(k); - } - // a call an app reported itself (#1874): it went straight to its vendor - if (r.source === "reported") { - const k = el("span", "src reported", t("Reported")); - k.title = t("Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie."); - badges.append(k); - } - if (badges.childElementCount) wc.append(badges); - // the model sent is what the gateway sent the vendor: a session file has none - // The log names a model, but does not capture the outbound HTTP request. - td(r.model || "—", "model " + (r.model ? "model-value" : "faint"), r.source === "log" && r.model ? t("Model recorded in the local session log; the outbound HTTP request was not captured.") : r.model); - td(ledServed(r), "model"); - td(r.effort || "—", r.effort ? "" : "faint"); - td(ledNum(r.in), "n"); - td(ledNum(r.out), "n", r.reasoning ? t("{n} reasoning, inside output", { n: ledNum(r.reasoning) }) : ""); - td(ledNum(r.cache_write), "n" + (r.cache_write ? "" : " faint"), cacheTTLs(r, ledNum).replace(/^ · /, "")); - td(ledNum(r.cache_read), "n" + (r.cache_read ? "" : " faint")); - const cost = td(r.priced ? "≈" + fmtCost({ cost: r.cost, unpriced: 0 }) : "—", "n cost" + (r.priced ? "" : " faint"), r.priced ? (r.pricing_model ? t("API price reference") + ": " + r.pricing_model : "") : t("No known price for this model")); - if (r.priced && r.pricing_model) { - const reference = el("div", "price-reference", t("Price reference: {model}", { model: r.pricing_model })); - reference.title = t("Model used for the API price estimate; this is not an observed model forwarding event."); - cost.append(reference); - } - // a session file has the times of its lines: a call took about from the line that - // asked for it to its last; some have none, and are dashes, not 0 ms - const timed = r.source === "log"; - const untimed = !Number.isFinite(r.ms) || r.ms <= 0; - const durationBand = untimed ? "" : r.ms <= 10000 ? "fast" : r.ms <= 30000 ? "slow" : "long"; - td(untimed ? "—" : (timed ? "≈" : "") + ledTook(r.ms), "n duration " + (untimed ? "faint" : "duration-" + durationBand), - [!untimed ? t("{n} ms", { n: ledNum(r.ms) }) : "", !untimed ? t("Duration colors: ≤10 s green · 10–30 s amber · >30 s red") : "", timed && !untimed ? t("About: told from the session file's times, a little more or less than it took") : "", r.ttft_ms ? t("TTFT {ms}", { ms: ledTook(r.ttft_ms) }) : ""].filter(Boolean).join(" · ")); - // how fast it wrote once it began, as CC Switch's log has it (#860) - const v = ledRowSpeed(r), floor = ledFloorSpeed(r); - td(v ? t("{n} tok/s", { n: ledNum(Math.round(v)) }) : floor ? "≥" + t("{n} tok/s", { n: ledNum(Math.round(floor)) }) : "—", "n speed" + (v || floor ? "" : " faint"), - v ? (r.reasoning > 0 && r.first_text_ms > 0 ? t("{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out", { n: ledNum(ledDecode(r).n), ms: ledTook(ledDecode(r).w), r: ledNum(r.reasoning) }) - : t("{n} output tokens in {ms} after the first", { n: ledNum(ledDecode(r).n), ms: ledTook(ledDecode(r).w) })) + " · " + t("TTFT {ms}", { ms: ledTook(r.ttft_ms) }) - : floor && ledFloor_(r).answer ? t("At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too", { n: ledNum(ledFloor_(r).n), ms: ledTook(ledFloor_(r).w), r: ledNum(r.reasoning) }) + " · " + t("TTFT {ms}", { ms: ledTook(r.ttft_ms) }) - : floor && ledFloor_(r).turn ? t("At least: {n} output tokens in {ms}, the whole turn. What came after the first token ({after}) is too little to time a speed by: under a second or under 100 tokens, so the wait for it is counted too", { n: ledNum(r.out), ms: ledTook(r.ms), after: ledTook(r.ms - r.ttft_ms) }) + " · " + t("TTFT {ms}", { ms: ledTook(r.ttft_ms) }) - : floor ? t("At least: {n} output tokens in {ms}, from the line that asked for it to its last. The session file has no first token, so the wait for it is counted too", { n: ledNum(r.out), ms: ledTook(r.ms) }) - : r.ttft_ms || untimed || ledFailed_(r) ? "" : timed ? t("The session file has no first token to time a speed from") : t("Not streamed: no first token to time a speed from")); - const st = el("span", "st"); - // a status when the gateway logged the call; a session file has none, - // and says only whether it went well - let word = r.status ? String(r.status) : r.source === "log" ? (bad ? r.err_type || t("Failed") : t("Succeeded")) : "—"; - if (r.status && bad && r.err_type) word += " · " + r.err_type; - if (r.handed_on) word += " · " + t("handed on"); - else if (r.tries > 1) word += " · " + t("{n} tries", { n: r.tries }); - st.append(el("i", "dot"), document.createTextNode(word)); - td(st, "", [r.handed_on && t("This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try"), - bad ? (r.err || t("Failed: the agent was answered {status}", { status: r.status })) : ""].filter(Boolean).join("\n")); - const detail = ledOpen.has(key) ? ledDetail(r, LED_COLS.length) : null; - const toggle = () => { - if (ledOpen.delete(key)) { tr.classList.remove("open"); tr.setAttribute("aria-expanded", "false"); tr.nextElementSibling?.classList.contains("led-detail") && tr.nextElementSibling.remove(); return; } - ledOpen.add(key); - tr.classList.add("open"); - tr.setAttribute("aria-expanded", "true"); - tr.after(ledDetail(r, LED_COLS.length)); - }; - // a click that ends a text selection is the reader copying, not asking - tr.onclick = () => { if (!String(getSelection() || "")) toggle(); }; - tr.onkeydown = (e) => { if (e.target === tr && (e.key === "Enter" || e.key === " ")) { e.preventDefault(); toggle(); } }; - table.tBodies[0].append(tr); - if (detail) table.tBodies[0].append(detail); - } - wrap.replaceChildren(table); - wrap.style.setProperty("--ledw", wrap.clientWidth + "px"); - ledFit(); - ledHScroll(); - ledGrow.disconnect(); - ledGrow.observe(table); - - // a page at a time: the newest first - pager.hidden = l.total <= LED_PAGE; - pager.replaceChildren(); - if (!pager.hidden) { - const prev = el("button", "text", t("Newer")); - const next = el("button", "text", t("Older")); - prev.disabled = l.offset <= 0; - next.disabled = l.offset + l.rows.length >= l.total; - prev.onclick = () => { ledOffset = Math.max(0, l.offset - LED_PAGE); loadLedger().catch((e) => status(e.message, "err")); }; - next.onclick = () => { ledOffset = l.offset + LED_PAGE; loadLedger().catch((e) => status(e.message, "err")); }; - pager.append(prev, el("span", "", t("{a}–{b} of {n}", { a: ledNum(l.offset + 1), b: ledNum(l.offset + l.rows.length), n: ledNum(l.total) })), next); - } - $("#ledNote").textContent = t("Each request's tokens as its provider reported them; the cost estimated using effective model prices, including custom prices. Export CSV saves every page."); -} - -{ - let typing = 0; - $("#ledQ").oninput = (e) => { - ledQuery = e.target.value; - ledModel = ""; - clearTimeout(typing); - typing = setTimeout(() => { ledOffset = 0; loadLedger().catch((err) => status(err.message, "err")); }, 250); - }; - $("#ledQ").onkeydown = (e) => { - if (e.key === "Escape" && e.target.value) { e.stopPropagation(); e.target.value = ""; ledQuery = ""; ledModel = ""; ledOffset = 0; loadLedger().catch((err) => status(err.message, "err")); } - }; - $("#ledExport").onclick = async () => { - const b = $("#ledExport"); - // in a browser the file comes to it; in the app it goes to Downloads - if (web) { - const a = el("a"); - a.href = "/api/usage/requests.csv?" + ledParams(); - a.download = ""; - a.click(); - return; - } - b.classList.add("busy"); - try { - const r = await api("usage/requests/export?" + ledParams(), {}); - status(t(r.rows === 1 ? "Saved {n} request to {path}" : "Saved {n} requests to {path}", { n: ledNum(r.rows), path: r.path }), "ok"); - } catch (e) { - status(e.message, "err"); - } finally { - b.classList.remove("busy"); - } - }; -} - -// ---------- sessions ---------- -// -// The agents' own sessions, read from their session files: what each cost, -// and the command that picks it up again. A segment of the Usage page. - -const USAGE_TABS = [["usage", "Overview"], ["requests", "Requests"], ["sessions", "Sessions"], ["context", "Context"]]; -let usageTab = "usage"; let quotaFocus = ""; // pending provider/account card requested by the menu bar let quotaFocusUntil = 0; // expire before a late quota response can move the reader -try { const k = localStorage.getItem("magpie.usageTab"); if (USAGE_TABS.some(([id]) => id === k)) usageTab = k; } catch {} let sessions = null; // { sessions, terminal, dirs } -let sessAgent = "all"; -let sessQuery = ""; -// The list is drawn in pages: every session is read (so the count beside it -// and the list agree), but a filter click or a keystroke in Search draws -// SESS_PAGE rows and no more, and "Show N more" appends the next page. A -// history of thousands rebuilt whole on every keystroke took ~300ms a -// keystroke on a fast Mac (yetone, #1019). sessShown resets to one page -// whenever the filters change, so what is drawn never grows with the history. -const SESS_PAGE = 200; -let sessShown = SESS_PAGE; -// What the last draw put in the list, for the note under it to say: drawn is -// the rows drawn and total the rows the filters kept — the same list, so a -// search that matches one session says "1 session", never "1 of 2600" (the -// note is about the list, not about every session on the computer). -let sessDrawn = null, sessTotal = null; -// what the drawn list was filtered by, so a redraw from the same filters -// keeps the pages opened and a changed one starts again at the first -let sessListKey = null; -// The totals and the chart are every session's, by day, over a range; the -// list is the latest sessions within it. [id, name, days (0: all)] -const SESS_RANGES = [["today", "Today", 1], ["7d", "7 days", 7], ["30d", "30 days", 30], ["90d", "90 days", 90], ["all", "All", 0]]; -let sessRange = "30d"; -// what the activity chart counts each day -const SESS_METRICS = [["tokens", "Tokens"], ["output", "Output tokens"], ["messages", "Messages"], ["sessions", "Sessions"], ["cost", "Cost"], ["active", "Active"]]; -let sessMetric = "tokens"; -// what the top sessions are the top by -const SESS_TOPS = [["tokens", "Tokens"], ["cost", "Cost"], ["active", "Active"]]; -let sessTopBy = "tokens"; -try { - const r = localStorage.getItem("magpie.sessRange"); - if (SESS_RANGES.some(([id]) => id === r)) sessRange = r; - const m = localStorage.getItem("magpie.sessMetric"); - if (SESS_METRICS.some(([id]) => id === m)) sessMetric = m; - const b = localStorage.getItem("magpie.sessTop"); - if (SESS_TOPS.some(([id]) => id === b)) sessTopBy = b; -} catch {} -let sessStats = null; // { from, to, days: [{ date, usage, active }], agents } for sessRange -let sessModel = ""; // "" for every model -let sessFolder = ""; // "" for every folder -// the sessions of the range summed up under the filters, by the server: -// { count, median, p90, days, top: { tokens, cost, active } }, and the -// query it answers -let sessOver = null; -let sessOverAt = ""; -let sessOverLoading = ""; -let sessTopOpen = ""; // the top session opened to its details -const sessFull = new Map(); // a top session's key → the session read whole, or "…" while it is read - -function renderUsageTab() { - const seg = $("#usageTab"); - seg.replaceChildren(); - for (const [id, name] of USAGE_TABS) { - const b = el("button", "opt" + (id === usageTab ? " on" : ""), t(name)); - b.onclick = () => { - if (id === usageTab) return; - usageTab = id; - try { localStorage.setItem("magpie.usageTab", id); } catch {} - $("#usageCost").replaceChildren(); - // to the Overview is to the allowances (#1588) - loadUsage(id === "usage").catch((e) => status(e.message, "err")); - }; - seg.append(b); - } - slide(seg, "usageTab"); - const on = usageTab === "sessions"; - // the Context tab has its own range, in its pane - $("#period").hidden = on || usageTab === "context"; - $("#sessRange").hidden = !on; - $("#ctxRange").hidden = usageTab !== "context"; - $("#usagePane").hidden = usageTab !== "usage"; - $("#ledgerPane").hidden = usageTab !== "requests"; - $("#sessionsPane").hidden = !on; - $("#contextPane").hidden = usageTab !== "context"; -} - -const sessDays = () => SESS_RANGES.find(([id]) => id === sessRange)[2]; -async function loadSessions() { - const first = !sessions || !sessStats; - if (first) renderSessionsLoading(); - const range = sessRange, q = sessOverQ(); - const stop = first ? sessWatchIndex() : () => {}; - let s, st, o; - try { - [s, st, o] = await Promise.all([api("sessions"), api("sessions/stats?days=" + sessDays()), api("sessions/overview?" + q)]); - } finally { stop(); } - if (range !== sessRange) return; // another range was picked meanwhile; its load draws - const fresh = q === sessOverQ(); // no filter changed meanwhile - if (sessions && sessStats && JSON.stringify(s) === JSON.stringify(sessions) && JSON.stringify(st) === JSON.stringify(sessStats) && - (!fresh || JSON.stringify(o) === JSON.stringify(sessOver))) return; - sessions = s; - sessStats = st; - if (fresh) { sessOver = o; sessOverAt = q; } - if (view === "usage" && usageTab === "sessions") renderSessions(); -} - -// the overview's query: the range and the filters -const sessOverQ = () => new URLSearchParams({ days: sessDays(), agent: sessAgent === "all" ? "" : sessAgent, model: sessModel, cwd: sessFolder }).toString(); -// loadSessOverview reads the overview again when a filter changes, and draws -// the page once it is in; one read at a time for a query -function loadSessOverview() { - const q = sessOverQ(); - if (sessOverLoading === q) return; - sessOverLoading = q; - const done = () => { if (sessOverLoading === q) sessOverLoading = ""; }; - api("sessions/overview?" + q).then((o) => { - done(); - if (q !== sessOverQ()) return; - sessOver = o; - sessOverAt = q; - if (view === "usage" && usageTab === "sessions" && sessions && sessStats) renderSessions(); - }, (e) => { done(); status(e.message, "err"); }); -} - -function renderSessionsLoading() { - const view = $("#view-usage"); - view.classList.add("loading"); - view.setAttribute("aria-busy", "true"); - $("#usageCost").replaceChildren(el("span", "skeleton sk-cost")); - renderSessRange(true); - $("#sessAgent").replaceChildren(); - $("#sessModel").hidden = $("#sessFolder").hidden = true; - $("#sessChart").hidden = true; - $("#sessGrid").hidden = true; - $("#sessListHead").hidden = true; - const stats = $("#sessStats"); - stats.classList.remove("empty"); - stats.classList.add("six"); - stats.replaceChildren(); - for (let i = 0; i < 6; i++) { - const tile = el("div", "kpi loading-kpi"); - tile.append(el("span", "skeleton sk-number"), el("span", "skeleton sk-label")); - stats.append(tile); - } - const list = $("#sessList"); - list.hidden = false; - list.replaceChildren(); - for (let i = 0; i < 4; i++) { - const r = el("div", "row sess-sk"); - r.append(el("span", "skeleton sk-title"), el("span", "skeleton sk-line short")); - list.append(r); - } - $("#sessNote").textContent = t("Reading the agents' session files…"); -} - -const SESS_INDEX_SHOW = 700; - -// sessWatchIndex asks how far the reading of the session files has got -// while the page waits on it; a read of the kept index, over in a moment, -// shows the skeleton alone, and one that takes a while the indexing show. -// It returns the stop. -function sessWatchIndex() { - let on = true, timer = 0, shown = false, since = 0; - const tick = async () => { - if (!on) return; - let p = null; - try { p = await api("sessions/progress"); } catch {} - if (!on) return; - // only a real indexing run is shown: a read of the kept index, however - // long, keeps the skeleton, and so does the catch-up read of the few - // files the agents wrote to since (every reload has some, while an agent - // is at work), over well before SESS_INDEX_SHOW; the show would play - // again from nought for it - since = p?.indexing ? since || Date.now() : 0; - const long = since && Date.now() - since >= SESS_INDEX_SHOW; - if (p && (long || shown) && view === "usage" && usageTab === "sessions") { - const stats = $("#sessStats"); - let hero = stats.querySelector(".sess-indexing"); - if (!hero) { - hero = sessIndexHero(); - stats.replaceChildren(hero); - } - // an earlier watch's stop may have taken the class off the hero kept - stats.classList.add("indexing"); - shown = true; - hero.update(p); - } - timer = setTimeout(tick, 350); - }; - timer = setTimeout(tick, 150); - return () => { - on = false; - clearTimeout(timer); - if (shown) $("#sessStats").classList.remove("indexing"); - }; -} - -// sessIndexHero is the show put on while the session files are read: the -// words and how far it has got on the left, on the right a field of dots, the -// heatmap's cells, that light up as the files land, a wave running through -// them; a hairline along the foot. Still with reduced motion. -const SESS_TIPS = [ - "Read once, kept: after this the page opens from the index in a blink", - "Only what changed is read again, from where it was left", - "Every session is read on this computer; nothing leaves it", - "The biggest files go first, so none is left running on alone", -]; -function sessIndexHero() { - const hero = el("div", "sess-indexing"); - hero.setAttribute("role", "status"); - const field = el("div", "si-field"); - const cv = el("canvas", "si-canvas"); - cv.setAttribute("aria-hidden", "true"); - field.append(cv); - const words = el("div", "si-words"); - const head = el("div", "si-head"); - head.append(el("i", "si-spin"), el("span", "si-title", t("Indexing your sessions"))); - const pct = el("div", "si-pct"); - const num = el("b", "", ""); - pct.append(num, el("span", "", "%")); - const line = el("div", "si-line", t("Looking for session files…")); - const tip = el("div", "si-tip", t(SESS_TIPS[0])); - words.append(head, pct, line, tip); - const bar = el("div", "si-bar"); - const fill = el("i", ""); - bar.append(fill); - hero.append(words, field, bar); - - const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches; - let frac = 0, shown = 0, known = false, tipAt = Date.now(), tipI = 0, rate = 0, last = null; - let done = false; - hero.update = (p) => { - if (!(p.indexing && p.bytes > 0) && known) { - // the run is over while the page is put together: held full, never - // back to the unknown state or a second run from nought - if (!done) { - done = true; - frac = 1; - fill.style.width = "100%"; - hero.classList.add("done"); - line.textContent = t("Indexed · putting the page together…"); - } - return; - } - if (done) return; - known = !!p.indexing && p.bytes > 0; - const f = known ? Math.min(1, p.read / p.bytes) : 0; - // a steady speed, for the time left - if (known && last && p.read > last.read) { - const r = (p.read - last.read) / ((Date.now() - last.at) / 1000); - rate = rate ? rate * 0.8 + r * 0.2 : r; - } - if (known) last = { read: p.read, at: Date.now() }; - frac = Math.max(frac, f); - hero.classList.toggle("known", known); - fill.style.width = known ? (frac * 100).toFixed(1) + "%" : ""; - if (known) { - line.textContent = t("{done} of {files} files · {read} of {bytes}", { done: fmtN(p.done), files: fmtN(p.files), read: fmtBytes(p.read), bytes: fmtBytes(p.bytes) }); - const left = rate > 0 ? (p.bytes - p.read) / rate : 0; - if (left > 3) line.textContent += " · " + t("about {t} left", { t: left < 60 ? t("{n}s", { n: Math.ceil(left) }) : t("{n} min", { n: Math.ceil(left / 60) }) }); - } else line.textContent = t("Reading the kept index…"); - if (Date.now() - tipAt > 4500) { - tipAt = Date.now(); - tipI = (tipI + 1) % SESS_TIPS.length; - tip.classList.remove("in"); - void tip.offsetWidth; - tip.textContent = t(SESS_TIPS[tipI]); - tip.classList.add("in"); - } - if (reduced) paint(0); - }; - - // the drawing: each dot has its turn, mostly left to right, a little - // scattered, so the edge of what is read is ragged like rain landing - const ctx = cv.getContext("2d"); - const GAP = 14; - let W = 0, H = 0, dpr = 1, dots = [], ink = "#1c1c21", accent = "#4f46e5", frame = 0; - const colours = () => { - const c = getComputedStyle(hero); - ink = c.getPropertyValue("--fg").trim() || ink; - accent = c.getPropertyValue("--accent").trim() || accent; - }; - const size = () => { - dpr = devicePixelRatio || 1; - const r = cv.getBoundingClientRect(); - if (!r.width || !r.height) return false; - if (r.width !== W || r.height !== H) { - W = r.width; H = r.height; - cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr); - const cols = Math.max(1, Math.floor((W - 4) / GAP)), rows = Math.max(1, Math.floor((H - 4) / GAP)); - const ox = (W - (cols - 1) * GAP) / 2, oy = (H - (rows - 1) * GAP) / 2; - dots = []; - for (let j = 0; j < rows; j++) for (let i = 0; i < cols; i++) { - const seed = Math.random(); - dots.push({ x: ox + i * GAP, y: oy + j * GAP, nx: cols > 1 ? i / (cols - 1) : 0, ny: rows > 1 ? j / (rows - 1) : 0, seed, turn: (cols > 1 ? i / (cols - 1) : 0) * 0.86 + seed * 0.14 }); - } - } - return true; - }; - function paint(now) { - if (!size()) return; - if (frame++ % 30 === 0) colours(); - const T = now / 1000; - ctx.setTransform(dpr, 0, 0, dpr, 0, 0); - ctx.clearRect(0, 0, W, H); - shown += (frac - shown) * (reduced ? 1 : 0.06); - // unknown: a band of light sweeps across and on again - const scan = ((T * 0.32) % 1.4) - 0.2; - // a faint glow where the reading is - const gx = (known ? shown * 0.86 + 0.07 : scan) * W; - const glow = ctx.createRadialGradient(gx, H / 2, 0, gx, H / 2, H * 0.9); - glow.addColorStop(0, hexA(accent, reduced ? 0.06 : 0.1)); - glow.addColorStop(1, hexA(accent, 0)); - ctx.fillStyle = glow; - ctx.fillRect(0, 0, W, H); - for (const d of dots) { - const wave = reduced ? 0.5 : 0.5 + 0.5 * Math.sin(d.nx * 7 + d.ny * 2.4 - T * 1.5 + d.seed * 0.8); - let a = 0.08 + 0.05 * wave, r = 1.05 + 0.2 * wave, c = ink; - if (known) { - const since = shown - d.turn; - if (since >= 0) { - // read: resting in the accent, just landed brighter and bigger - const fresh = Math.max(0, 1 - since / 0.07); - c = accent; - a = 0.4 + 0.32 * wave * (0.3 + d.seed) + 0.5 * fresh; - r = 1.25 + 0.25 * wave + 1.1 * fresh * fresh; - } else if (since > -0.035 && !reduced) { - // about to land: a flicker - const near = 1 + since / 0.035; - if (Math.sin(T * 9 + d.seed * 40) > 0.3) { c = accent; a = 0.1 + 0.35 * near; } - } - } else if (!reduced) { - const g = Math.exp(-(((d.nx - scan) / 0.07) ** 2)); - if (g > 0.02) { c = accent; a = Math.max(a, 0.9 * g * (0.55 + 0.45 * d.seed)); r += 1 * g; } - } - ctx.globalAlpha = Math.min(1, a); - ctx.fillStyle = c; - ctx.beginPath(); - ctx.arc(d.x, d.y, r, 0, Math.PI * 2); - ctx.fill(); - } - ctx.globalAlpha = 1; - num.textContent = known ? String(Math.floor(shown * 100)) : ""; - } - // it runs until the page takes it away - const loop = (now) => { - if (!hero.isConnected) return; - paint(now); - requestAnimationFrame(loop); - }; - if (!reduced) requestAnimationFrame(loop); - else requestAnimationFrame(() => paint(0)); - return hero; -} -// hexA is a #rrggbb colour at an alpha -function hexA(hex, a) { - const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim()); - if (!m) return `rgba(79,70,229,${a})`; - const n = parseInt(m[1], 16); - return `rgba(${n >> 16},${(n >> 8) & 255},${n & 255},${a})`; -} function fmtBytes(n) { const u = ["B", "KB", "MB", "GB", "TB"]; let i = 0; @@ -19545,13 +17528,6 @@ function fmtBytes(n) { return (i && n < 10 ? n.toFixed(1) : Math.round(n)) + " " + u[i]; } -const sessKey = (s) => s.agent + ":" + s.id; -const sessTokens = (s) => s.input + s.output; -// a session's cost: "—" when none of its models has a known price -function sessCost(s) { - if (!s.models.some((m) => m.priced && (m.input || m.output || m.cache_read || m.cache_write))) return "—"; - return "≈" + fmtCost({ cost: s.cost, unpriced: s.unpriced }); -} // sessModelNames lists models for a cost note, one an agent recorded no // name for told as such: joined bare, the note read "Not counted: , with // no known price" (tony, Discord) @@ -19569,38 +17545,6 @@ function stamp(when) { } const baseName = (p) => (p || "").replace(/[\\/]+$/, "").split(/[\\/]/).pop() || p; -// the range picker, in the page's head where the Overview's period is -function renderSessRange(loading) { - const seg = $("#sessRange"); - seg.replaceChildren(); - for (const [id, name] of SESS_RANGES) { - const b = el("button", "opt" + (id === sessRange ? " on" : ""), t(name)); - b.disabled = !!loading; - b.onclick = () => { - if (id === sessRange) return; - sessRange = id; - try { localStorage.setItem("magpie.sessRange", id); } catch {} - sessStats = null; - loadSessions().catch((e) => status(e.message, "err")); - }; - seg.append(b); - } - slide(seg, "sessRange"); -} - -// a "YYYY-MM-DD" as a local date, and back -const sessDate = (d) => { const [y, m, day] = d.split("-").map(Number); return new Date(y, m - 1, day); }; -const sessISO = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; -const sessDay = (d) => d.toLocaleDateString(intlLang(), { month: "short", day: "numeric" }); -// a length of time, as hours and minutes -function fmtDur(sec) { - const m = Math.round(sec / 60); - if (!sec) return "0"; - if (m < 1) return t("<1m"); - if (m < 60) return t("{m}m", { m }); - return t("{h}h {m}m", { h: Math.floor(m / 60), m: m % 60 }); -} - // sessPick is a filter button that drops a menu of what there is to pick function sessPick(btn, all, value, opts, head, choose) { btn.hidden = opts.length < 2 && !value; @@ -19691,796 +17635,6 @@ function openSessCombo(anchor, all, opts, value, choose, head) { q.focus({ preventScroll: true }); } -function renderSessions() { - const view = $("#view-usage"); - view.classList.remove("loading"); - view.removeAttribute("aria-busy"); - renderSessRange(); - const all = sessions?.sessions || []; - const st = sessStats || { from: "", to: "", days: [], agents: {} }; - const rows = st.days.flatMap((d) => d.usage.map((u) => ({ ...u, date: d.date }))); - const acts = st.days.flatMap((d) => d.active.map((a) => ({ ...a, date: d.date }))); - - // one segment per agent that has sessions, or usage in the range - const agents = [...new Map([...all.map((s) => [s.agent, s.name]), ...Object.entries(st.agents || {})]).entries()]; - if (sessAgent !== "all" && !agents.some(([id]) => id === sessAgent)) sessAgent = "all"; - const seg = $("#sessAgent"); - seg.hidden = agents.length < 2; - const opts = [["all", t("All")], ...agents]; - // the same agents keep their buttons: drawn anew, a strip with more than - // fit (#929) would lose where it was scrolled to (WebKit) - const was = [...seg.querySelectorAll(":scope > .opt")]; - if (was.length !== opts.length || was.some((b, i) => b.dataset.agent !== opts[i][0] || b.textContent !== opts[i][1])) { - seg.replaceChildren(); - for (const [id, name] of opts) { - const b = el("button", "opt", name); - b.dataset.agent = id; - b.onclick = () => { sessAgent = id; renderSessions(); }; - seg.append(b); - } - } - for (const b of seg.querySelectorAll(":scope > .opt")) { - b.classList.toggle("on", b.dataset.agent === sessAgent); - b.setAttribute("aria-pressed", String(b.dataset.agent === sessAgent)); - } - // and the agent picked is brought into the strip, the page left where it is - const picked = seg.querySelector(":scope > .on"); - if (picked && seg.scrollWidth > seg.clientWidth) { - if (picked.offsetLeft < seg.scrollLeft) seg.scrollLeft = picked.offsetLeft; - else if (picked.offsetLeft + picked.offsetWidth > seg.scrollLeft + seg.clientWidth) seg.scrollLeft = picked.offsetLeft + picked.offsetWidth - seg.clientWidth; - } - slide(seg, "sessAgent"); - - // the model and folder filters offer what the range has, under the other filters - const byAgent = (x) => sessAgent === "all" || x.agent === sessAgent; - const byModel = (x) => !sessModel || x.model === sessModel; - const byFolder = (x) => !sessFolder || x.cwd === sessFolder; - const spent = (list, key) => { - const m = new Map(); - for (const r of list) if (r[key]) m.set(r[key], (m.get(r[key]) || 0) + r.input + r.output); - return [...m.entries()].sort((a, b) => b[1] - a[1]); - }; - const models = spent(rows.filter((r) => byAgent(r) && byFolder(r)), "model").map(([v, n]) => ({ v, name: v, note: t("{n} tokens", { n: fmtN(n) }) })); - const folders = spent(rows.filter((r) => byAgent(r) && byModel(r)), "cwd").map(([v, n]) => ({ v, name: baseName(v), note: v + " · " + t("{n} tokens", { n: fmtN(n) }) })); - sessPick($("#sessModel"), "All models", sessModel, models, "Model", (v) => { sessModel = v; renderSessions(); }); - sessPick($("#sessFolder"), "All folders", sessFolder, folders, "Folder", (v) => { sessFolder = v; renderSessions(); }); - - // the list: the sessions at work in the range, under every filter. Which - // ones were at work is the range's own answer (st.keys, the sessions - // stats counted), not a guess from s.last: a session's file goes on being - // written after its last call — a fork's seed, a setting — so one whose - // last line falls in the range spent nothing in it, and it was listed but - // not counted, the note beside the list saying more than the KPI above it. - const inRange = st.keys ? new Set(st.keys) : null; - const from = !inRange && sessDays() && st.from ? sessDate(st.from) : null; - const q = sessQuery.trim().toLowerCase(); - const list = all.filter((s) => byAgent(s) && (!sessFolder || s.cwd === sessFolder) && - (!sessModel || s.models.some((m) => m.model === sessModel)) && - (inRange ? inRange.has(s.agent + ":" + s.id) : !from || new Date(s.last) >= from) && - (!q || [s.title, s.cwd, s.id, s.name, ...s.models.map((m) => m.model)].some((x) => (x || "").toLowerCase().includes(q)))); - - // the range's totals, of every session under the filters - const used = rows.filter((r) => byAgent(r) && byModel(r) && byFolder(r)); - const tot = { input: 0, output: 0, cache_read: 0, cache_write: 0, cost: 0, unpriced: 0 }; - const unpriced = new Set(); - for (const r of used) { - for (const k of ["input", "output", "cache_read", "cache_write", "cost"]) tot[k] += r[k]; - if (!r.priced) unpriced.add(r.model); - } - tot.unpriced = unpriced.size; - // active time isn't told apart by model - const active = sessModel ? null : acts.filter((a) => byAgent(a) && byFolder(a)).reduce((n, a) => n + a.seconds, 0); - - const c = tot.cost ? fmtCost(tot) : ""; - const unpricedNote = tot.unpriced ? t("Not counted: {models}, with no known price", { models: sessModelNames([...unpriced]) }) : t("Estimated using effective model prices, including custom prices"); - // a session's models are counted, not its calls: the agents' files price by model - const unpricedModels = tot.unpriced ? t(tot.unpriced === 1 ? "{n} model unpriced" : "{n} models unpriced", { n: tot.unpriced }) : ""; - costHead(c, unpricedModels, unpricedNote); - - // the overview is read again for the filters as they are now; until it is - // in, the last one stands, dimmed - if (sessOverAt !== sessOverQ()) loadSessOverview(); - const ov = sessOver || {}; - const stale = sessOverAt !== sessOverQ(); - - const stats = $("#sessStats"); - stats.replaceChildren(); - const box = $("#sessList"); - box.replaceChildren(); - const chart = $("#sessChart"); - const grid = $("#sessGrid"); - const head = $("#sessListHead"); - if (!used.length && !list.length) { - stats.classList.remove("six"); - stats.classList.add("empty"); - const filtered = sessAgent !== "all" || sessModel || sessFolder || q; - stats.append(el("div", "none", !all.length && !rows.length ? t("No sessions yet. Claude Code's, Codex's, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.") : filtered ? t("No session matches.") : t("Nothing in this range."))); - if (from && all.some((s) => byAgent(s) && byFolder(s) && - (!sessModel || s.models.some((m) => m.model === sessModel)) && - (!q || [s.title, s.cwd, s.id, s.name, ...s.models.map((m) => m.model)].some((x) => (x || "").toLowerCase().includes(q))))) { - stats.firstChild.textContent = t("No sessions in this range"); - const history = el("button", "text sess-show-history", t("All sessions")); - history.onclick = () => { - sessRange = "all"; - try { localStorage.setItem("magpie.sessRange", sessRange); } catch {} - sessStats = null; - loadSessions().catch((e) => status(e.message, "err")); - }; - stats.append(history); - } - box.hidden = true; - chart.hidden = true; - grid.hidden = true; - sessDrawn = 0; - sessTotal = 0; - // the search stays where it was typed, to be cleared - head.hidden = !q; - } else { - stats.classList.remove("empty"); - stats.classList.add("six"); - const tile = (n, label, sub, title, cls) => { - const e = el("div", "kpi" + (cls ? " " + cls : "")); - if (title) e.title = title; - // a figure never wraps: a tile a line taller moves the page when a - // filter shortens it; a time's units step down, as the Health app's do - const b = el("b", ""); - if (cls?.includes("dur")) for (const part of n.split(/(\d+)/)) part && b.append(/^\d+$/.test(part) ? part : el("i", "u", part.trim())); - else b.textContent = n; - b.title = n; - e.append(b, el("span", "", label)); - if (sub) e.append(el("small", "", sub)); - stats.append(e); - }; - const days = new Set(used.map((r) => r.date)).size; - // how many sessions, and what the middle one and the one in ten spent - tile(ov.count == null ? "—" : fmtN(ov.count), t("sessions"), ov.count ? t("median {m} · p90 {p}", { m: fmtN(ov.median), p: fmtN(ov.p90) }) : "", - t("Tokens in and out per session: the middle session's, and what nine in ten stay under"), stale ? "stale" : ""); - tile(fmtN(tot.input + tot.output), t("tokens"), t("{a} in · {b} out", { a: fmtN(tot.input), b: fmtN(tot.output) })); - tile(c ? "≈" + c : "—", t("cost"), unpricedModels || t("at effective prices"), unpricedNote); - // input leaves out what was read from the cache and written to it - const prompt = tot.input + tot.cache_read + tot.cache_write; - tile(fmtN(tot.cache_read), t("cache read"), tot.cache_read && prompt ? t("hit rate {p}", { p: Math.round(100 * tot.cache_read / prompt) + "%" }) : "", tot.cache_write ? t("{n} written", { n: fmtN(tot.cache_write) }) : ""); - tile(active == null ? "—" : fmtDur(active), t("active"), active == null ? t("not kept by model") : t(days === 1 ? "on {n} day" : "on {n} days", { n: days }), - t("The time the sessions were at work: the pauses between one message and the next, each under five minutes"), "dur"); - // how many folders, and how much of it the first took - const byCwd = sessSums(used, "cwd"); - const lead = byCwd[0], spentAll = byCwd.reduce((n, f) => n + f.n, 0); - tile(String(byCwd.length), t("projects"), !lead ? "" : byCwd.length > 1 && spentAll ? t("{p} in {name}", { p: Math.round(100 * lead.n / spentAll) + "%", name: baseName(lead.v) }) : baseName(lead.v), lead?.v || ""); - - const actsIn = sessModel ? null : acts.filter((a) => byAgent(a) && byFolder(a)); - renderSessChart(chart, st, used, ov, actsIn); - grid.hidden = false; - // the folders and models to pick from, as the pickers offer them - sessBars($("#sessProjects"), "Projects", sessSums(rows.filter((r) => byAgent(r) && byModel(r)), "cwd"), sessFolder, (v) => { sessFolder = v; renderSessions(); }, baseName); - sessBars($("#sessModels"), "Models", sessSums(rows.filter((r) => byAgent(r) && byFolder(r)), "model"), sessModel, (v) => { sessModel = v; renderSessions(); }, (v) => v); - renderSessHours($("#sessHours"), actsIn); - renderSessTop(); - renderSessShape(); - renderSessTools(); - renderSessSkills(); - head.hidden = !list.length && !q; - box.hidden = !list.length && !q; - // a page of the list, not all of it: the same filters keep the pages - // opened, a changed one starts at the first (see sessListKey) - const key = [sessAgent, sessModel, sessFolder, sessRange, q].join("\0"); - if (key !== sessListKey) { sessListKey = key; sessShown = SESS_PAGE; } - const page = list.slice(0, sessShown); - sessDrawn = page.length; - sessTotal = list.length; - for (const s of page) box.append(sessionItem(s)); - if (list.length > page.length) { - const more = el("button", "text sess-page-more"); - more.textContent = t("Show {n} more", { n: Math.min(SESS_PAGE, list.length - page.length) }); - more.onclick = () => { sessShown += SESS_PAGE; renderSessions(); }; - box.append(more); - } - if (!list.length && q) box.append(el("div", "empty-state", t("No session matches."))); - } - const dirs = (sessions?.dirs || []).join(" · "); - // The list is every session the filters keep, drawn in pages, so the note - // counts that list and not every session on the computer: a search that - // matches one session says "1 session", not "1 of 2600", which read as if - // the rest were behind a "Show more" that isn't there (yetone, #1019). - // Nothing left to draw, the note is just the list's length, in words a - // reader uses: one session is a session, not "1 sessions". - const parts = [t("Totals count native sessions and gateway requests with a session ID")]; - if (sessDrawn !== null) { - parts.push(sessDrawn < sessTotal - ? t("showing {drawn} of {n}", { drawn: sessDrawn, n: sessTotal }) - : t(sessTotal === 1 ? "{n} session" : "{n} sessions", { n: sessTotal })); - } - if (dirs) parts.push(dirs); - $("#sessNote").textContent = parts.join(" · "); -} - -// sessSums adds up usage rows by one of their fields, the most tokens first -function sessSums(list, key) { - const m = new Map(); - for (const r of list) { - if (!r[key]) continue; - const s = m.get(r[key]) || { v: r[key], n: 0, cost: 0, unpriced: 0 }; - s.n += r.input + r.output; - s.cost += r.cost; - if (!r.priced) s.unpriced++; - m.set(r[key], s); - } - return [...m.values()].sort((a, b) => b.n - a.n); -} - -// sessLevels grades values 0 (none) to 4 by the quartiles of those above 0, -// as a calendar of contributions does. Under eight such values a quartile -// is one value or none, so two days 2% apart could be two shades apart and -// one twice another the same (#1921): a few are graded by their share of the -// busiest instead. -function sessLevels(values) { - const nz = values.filter((v) => v > 0).sort((a, b) => a - b); - if (!nz.length) return () => 0; - if (nz.length < 8) { - const most = nz[nz.length - 1]; - return (v) => v <= 0 ? 0 : Math.min(4, Math.max(1, Math.ceil(4 * v / most - 1e-9))); - } - const q = (p) => nz[Math.min(nz.length - 1, Math.floor(p * nz.length))]; - const [a, b, c, top] = [q(0.25), q(0.5), q(0.75), nz[nz.length - 1]]; - return (v) => v <= 0 ? 0 : v >= top ? 4 : v <= a ? 1 : v <= b ? 2 : v <= c ? 3 : 4; -} -function sessLegend() { - const l = el("span", "sess-legend"); - l.append(el("span", "", t("Less"))); - for (let i = 0; i <= 4; i++) l.append(el("i", "l" + i)); - l.append(el("span", "", t("More"))); - return l; -} -// the short names of the days of the week, Monday first -function sessWeekdays() { - const loc = intlLang(); - return Array.from({ length: 7 }, (_, i) => new Date(2024, 0, 1 + i).toLocaleDateString(loc, { weekday: "short" })); -} -function sessCardHead(title) { - const h = el("div", "sess-card-head"); - h.append(el("span", "label", t(title))); - return h; -} -function sessSegs(opts, cur, choose) { - const seg = el("div", "segs"); - for (const [id, name, off] of opts) { - const b = el("button", "opt" + (id === cur ? " on" : ""), t(name)); - if (off) { b.disabled = true; b.title = off; } - b.onclick = () => { if (id !== cur) choose(id); }; - seg.append(b); - } - return seg; -} - -// renderSessChart draws the range's activity: day by day as bars up to a -// hundred days, as a calendar up to a year, week by week past that. It counts -// tokens (output on top of input, as on the Overview), output tokens alone, -// messages, sessions at work, cost or active time. -function renderSessChart(chart, st, used, ov, acts) { - const perDay = ov.days, msgs = ov.messages; - const first = sessDate(st.from), last = sessDate(st.to); - const n = Math.round((last - first) / 864e5) + 1; - chart.hidden = !(n >= 2); - if (chart.hidden) { chart.dataset.drawn = ""; return; } - const days = [], at = new Map(); - for (let i = 0, d = new Date(first); i < n; i++, d.setDate(d.getDate() + 1)) { - const x = { day: new Date(d), input: 0, output: 0, cost: 0, unpriced: 0, sessions: perDay?.length === n ? perDay[i] : 0, - messages: msgs?.length === n ? msgs[i] : 0, active: 0 }; - days.push(x); - at.set(sessISO(d), x); - } - for (const r of used) { - const x = at.get(r.date); - if (!x) continue; - x.input += r.input; x.output += r.output; x.cost += r.cost; - if (!r.priced) x.unpriced++; - } - for (const a of acts || []) { const x = at.get(a.date); if (x) x.active += a.seconds; } - const off = { sessions: perDay?.length === n ? "" : t("Still counting"), messages: msgs?.length === n ? "" : t("Still counting"), active: acts ? "" : t("not kept by model") }; - const metric = off[sessMetric] ? "tokens" : sessMetric; - const value = (x) => metric === "cost" ? x.cost : metric === "sessions" ? x.sessions : metric === "messages" ? x.messages : - metric === "active" ? x.active : metric === "output" ? x.output : x.input + x.output; - const show = (v) => metric === "cost" ? "≈" + fmtCost({ cost: v }) : metric === "active" ? fmtDur(v) : fmtN(v); - const tip = (x, when) => { - const parts = [x.input + x.output ? t("{n} tokens", { n: fmtN(x.input + x.output) }) : "", x.cost && fmtCost(x) ? "≈" + fmtCost(x) : "", - x.messages ? t(x.messages === 1 ? "{n} message" : "{n} messages", { n: fmtN(x.messages) }) : "", - x.sessions ? t(x.sessions === 1 ? "{n} session" : "{n} sessions", { n: x.sessions }) : "", x.active ? t("{d} active", { d: fmtDur(x.active) }) : ""].filter(Boolean); - return parts.length ? when + " · " + parts.join(" · ") : t("{when} · nothing", { when }); - }; - const shape = n <= 100 ? "day" : n <= 371 ? "calendar" : "week"; - // the page reads the sessions again every few seconds, and while an agent - // is at work today's numbers change each time: the same days by the same - // metric keep their bars, filled in again where they are, so the one under - // the pointer — today's, as often as not — keeps its tooltip (#309) - const drawn = [shape, metric, st.from, n, locale, ...Object.values(off).map(Boolean)].join("|"); - const same = chart.dataset.drawn === drawn; - chart.dataset.drawn = drawn; - chart.redraw = () => renderSessChart(chart, st, used, ov, acts); // the metrics kept draw what is in now - - if (same && shape === "calendar") { - const lv = sessLevels(days.map(value)); - chart.querySelectorAll(".sess-cal > i").forEach((c, i) => { - c.className = "l" + lv(value(days[i])); - c.title = tip(days[i], sessDay(days[i].day)); - }); - chart.querySelector(".sess-cal-side").replaceWith(sessCalSide(days, value, show)); - chart.fitCal = () => sessCalFit(chart, days, value, tip); - return; - } - chart.fitCal = null; - if (shape === "calendar") { - chart.replaceChildren(); - chart.classList.add("cal"); - drawHead(); - const wrap = el("div", "sess-cal-wrap"); - wrap.append(sessCalendar(days, value, tip), sessCalSide(days, value, show)); - chart.append(wrap); - chart.querySelector(".sess-chart-head").append(sessLegend()); - chart.fitCal = () => sessCalFit(chart, days, value, tip); - chart.fitCal(); - sessCalWidth.observe(chart); - return; - } - - // bars: a day each, or a week - const step = shape === "week" ? 7 : 1; - const buckets = []; - for (let i = 0; i < n; i += step) { - const b = { day: days[i].day, input: 0, output: 0, cost: 0, unpriced: 0, sessions: 0, messages: 0, active: 0 }; - for (const x of days.slice(i, i + step)) for (const k of ["input", "output", "cost", "unpriced", "sessions", "messages", "active"]) b[k] += x[k]; - buckets.push(b); - } - const peak = Math.max(metric === "cost" ? 0.001 : 1, ...buckets.map(value)); - const fill = (bar, b) => { - const [top, low] = bar.children; - if (metric === "tokens") { - top.style.height = (100 * b.output / peak).toFixed(1) + "%"; - low.style.height = (100 * b.input / peak).toFixed(1) + "%"; - } else top.style.height = (100 * value(b) / peak).toFixed(1) + "%"; - const label = sessDay(b.day); - bar.title = tip(b, step === 7 ? t("week of {label}", { label }) : label); - }; - if (same) { - chart.querySelector(".sess-chart-head .peak").textContent = show(peak); - const bars = chart.querySelectorAll(".bars > .bar"); - buckets.forEach((b, i) => fill(bars[i], b)); - return; - } - chart.replaceChildren(); - chart.classList.remove("cal"); - drawHead().append(el("span", "peak", show(peak))); - const bars = el("div", "bars"); - const labels = el("div", "labels"); - const k = buckets.length; - const every = k <= 8 ? 1 : k <= 31 ? Math.ceil(k / 6) : Math.ceil(k / 5); - buckets.forEach((b, i) => { - const bar = el("div", "bar"); - if (metric === "tokens") bar.append(el("i", "out"), el("i", "in")); - else bar.append(el("i", "out")); - fill(bar, b); - bars.append(bar); - const label = sessDay(b.day); - const end = i === k - 1 && (k - 1) % every >= every / 2; - labels.append(el("span", "", i % every === 0 || end ? label : "")); - }); - chart.append(bars, labels); - fitChartLabels(); - - function drawHead() { - const head = el("div", "sess-chart-head"); - const seg = sessSegs(SESS_METRICS.map(([id, name]) => [id, name, off[id]]), metric, (id) => { - sessMetric = id; - try { localStorage.setItem("magpie.sessMetric", id); } catch {} - chart.redraw(); - }); - head.append(el("span", "label", t(shape === "week" ? "By week" : shape === "day" ? "By day" : "Activity")), seg, el("span", "grow")); - chart.append(head); - slide(seg, "sessMetric"); - return head; - } -} - -// a week's column in the calendar, cell and gap: as wide as weeks are counted -// by, and as wide as one may grow to take what is left over -const SESS_WEEK = 20, SESS_WEEK_MAX = 24; - -// sessCalFit lays the calendar across its card (John on Discord: 这个活跃度怎么 -// 没有铺满全部宽度呢?): a range of a few months took a few hundred pixels of a -// wide card and left the rest empty. The weeks before the range come in as -// empty cells, GitHub's way, up to a year in all, and the cells grow a little -// to take what is left; a narrow card gets none and its cells shrink. -// It fits on the next frame: a calendar put again changes the card's height, -// which this would be told of in the same call, a ResizeObserver loop. -const sessCalWidth = new ResizeObserver((es) => { - for (const { target: chart } of es) { - if (!chart.fitFrame) chart.fitFrame = requestAnimationFrame(() => { chart.fitFrame = 0; chart.fitCal?.(); }); - } -}); -function sessCalFit(chart, days, value, tip) { - const wrap = chart.querySelector(".sess-cal-wrap"), cal = wrap?.querySelector(".sess-cal"); - if (!cal || !wrap.clientWidth) return; - const ws = getComputedStyle(wrap), side = wrap.querySelector(".sess-cal-side"); - const wd = Math.max(0, ...[...cal.querySelectorAll(".wd")].map((l) => l.getBoundingClientRect().width)); - const room = wrap.clientWidth - wd - (ws.flexDirection === "row" ? side.getBoundingClientRect().width + (parseFloat(ws.columnGap) || 0) : 0); - const weeks = Math.ceil(((days[0].day.getDay() + 6) % 7 + days.length) / 7); - const pad = Math.max(0, Math.min(53, Math.floor(room / SESS_WEEK)) - weeks); - if (String(pad) !== cal.dataset.pad) cal.replaceWith(sessCalendar(days, value, tip, pad)); -} - -// sessCalendar is the range as weeks of days, Monday on top, each day as -// dark as it is busy among the others, after pad empty weeks before it -function sessCalendar(days, value, tip, pad = 0) { - const lv = sessLevels(days.map(value)); - const lead = (days[0].day.getDay() + 6) % 7 + 7 * pad; - const weeks = Math.ceil((lead + days.length) / 7); - const cal = el("div", "sess-cal"); - cal.dataset.pad = pad; - cal.style.gridTemplateColumns = `auto repeat(${weeks}, minmax(0, 1fr))`; - cal.style.maxWidth = `calc(2.6em + ${weeks * (pad ? SESS_WEEK_MAX : SESS_WEEK)}px)`; - const names = sessWeekdays(); - for (const i of [0, 2, 4]) { - const l = el("span", "wd", names[i]); - l.style.gridArea = `${i + 2} / 1`; - cal.append(l); - } - const loc = intlLang(); - let month = -1, labelAt = -9; - // the days before the range, from the Monday it is laid out from: their - // months named as the range's are, the days themselves left blank - const before = Array.from({ length: pad ? lead : 0 }, (_, i) => { - const d = new Date(days[0].day); - d.setDate(d.getDate() - lead + i); - return { day: d, before: true }; - }); - [...before, ...days].forEach((x, i) => { - const k = (pad ? 0 : lead) + i, w = Math.floor(k / 7), wd = k % 7; - if ((wd === 0 || i === 0) && x.day.getMonth() !== month) { - month = x.day.getMonth(); - // a month mostly gone when the weeks before begin is left unnamed, so - // as not to crowd out the next one's name - if (w - labelAt >= 3 && !(x.before && x.day.getDate() > 14)) { - const m = el("span", "mo", x.day.toLocaleDateString(loc, month === 0 && weeks > 20 ? { month: "short", year: "numeric" } : { month: "short" })); - m.style.gridArea = `1 / ${w + 2}`; - cal.append(m); - labelAt = w; - } - } - const c = x.before ? el("s") : el("i", "l" + lv(value(x))); - c.style.gridArea = `${wd + 2} / ${w + 2}`; - if (!x.before) c.title = tip(x, sessDay(x.day)); - cal.append(c); - }); - return cal; -} - -// beside the calendar: the days at work, the longest run of them, the busiest -function sessCalSide(days, value, show) { - const side = el("div", "sess-cal-side"); - const fact = (label, v, sub) => { - const f = el("div", "fact"); - f.append(el("b", "", v), el("span", "", label)); - if (sub) f.append(el("small", "", sub)); - side.append(f); - }; - const busy = (x) => x.input + x.output || x.active || x.sessions; - let run = 0, streak = 0, best = null; - for (const x of days) { - run = busy(x) ? run + 1 : 0; - streak = Math.max(streak, run); - if (value(x) > 0 && (!best || value(x) > value(best))) best = x; - } - fact(t("days at work"), `${days.filter(busy).length} / ${days.length}`); - fact(t("longest streak"), t(streak === 1 ? "{n} day" : "{n} days", { n: streak })); - if (best) fact(t("busiest day"), sessDay(best.day), show(value(best))); - return side; -} - -// renderSessHours lays the range's active time out by day of the week and -// hour of the day, in this computer's time zone -function renderSessHours(box, acts) { - box.replaceChildren(); - const head = sessCardHead("By hour"); - const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || ""; - head.append(el("span", "grow"), el("span", "tz", tz)); - box.append(head); - if (!acts) return box.append(el("div", "sess-none", t("Active time isn't kept by model."))); - const grid = Array.from({ length: 7 }, () => new Array(24).fill(0)); - let total = 0; - for (const a of acts) { - if (!a.hours) continue; - const wd = (sessDate(a.date).getDay() + 6) % 7; - a.hours.forEach((s, h) => { grid[wd][h] += s; total += s; }); - } - if (!total) return box.append(el("div", "sess-none", t("No active time in this range."))); - const lv = sessLevels(grid.flat()); - const names = sessWeekdays(); - const hh = (h) => String(h).padStart(2, "0") + ":00"; - const map = el("div", "sess-hours"); - let best = [0, 0]; - grid.forEach((row, wd) => { - map.append(el("span", "wd", names[wd])); - row.forEach((s, h) => { - const c = el("i", "l" + lv(s)); - c.title = `${names[wd]} ${hh(h)} · ` + (s ? fmtDur(s) : t("nothing")); - if (s > grid[best[0]][best[1]]) best = [wd, h]; - map.append(c); - }); - }); - map.append(el("span", "")); - for (let h = 0; h < 24; h++) map.append(el("span", "hr", h % 6 === 0 ? String(h) : "")); - box.append(map); - const foot = el("div", "sess-card-foot"); - foot.append(el("span", "", t("Busiest at {when}", { when: `${names[best[0]]} ${hh(best[1])}` })), el("span", "grow"), sessLegend()); - box.append(foot); -} - -// renderSessTop lists the sessions that spent the most in the range, under -// the filters; a click opens one to its details, read whole from its files -function renderSessTop() { - const box = $("#sessTop"); - const ov = sessOver || {}; - box.replaceChildren(); - box.classList.toggle("stale", sessOverAt !== sessOverQ()); - const head = sessCardHead("Top sessions"); - const seg = sessSegs(SESS_TOPS, sessTopBy, (id) => { - sessTopBy = id; - try { localStorage.setItem("magpie.sessTop", id); } catch {} - renderSessTop(); - }); - head.append(el("span", "grow"), seg); - box.append(head); - slide(seg, "sessTop"); - const list = ov.top?.[sessTopBy] || []; - const body = el("div", "sess-tops"); - if (!list.length) body.append(el("div", "sess-none", ov.top ? t("Nothing in this range.") : "…")); - const icons = new Map((sessions?.sessions || []).map((s) => [s.agent, s.icon])); - const names = sessStats?.agents || {}; - for (const s of list) { - const open = sessTopOpen === s.key; - const item = el("div", "sess-item" + (open ? " open" : "")); - const r = el("div", "row sess sess-top"); - r.append(icon(icons.get(s.agent) || "generic")); - const who = el("div", "who"); - who.append(el("div", "name", s.title || t("(no prompt)"))); - const sub = el("div", "sub", [s.cwd ? baseName(s.cwd) : "", names[s.agent] || s.agent, s.models?.[0], ago(s.last)].filter(Boolean).join(" · ")); - sub.title = s.cwd || ""; - who.append(sub); - r.append(who); - const fc = fmtCost({ cost: s.cost, unpriced: !s.priced }); - const v = sessTopBy === "cost" ? (fc ? "≈" + fc : "—") : sessTopBy === "active" ? fmtDur(s.active) : fmtN(s.input + s.output); - r.append(el("div", "v", v)); - r.onclick = () => { - if (window.getSelection()?.toString()) return; - sessTopOpen = open ? "" : s.key; - const had = sessFull.get(s.key); - if (!open && (!had || had.error)) { - sessFull.set(s.key, "…"); - api("sessions/one?key=" + encodeURIComponent(s.key)).then((full) => sessFull.set(s.key, full), (e) => sessFull.set(s.key, { error: e.message })) - .then(() => { if (sessTopOpen === s.key && view === "usage" && usageTab === "sessions") renderSessTop(); }); - } - renderSessTop(); - }; - item.append(r); - if (open) { - const full = sessFull.get(s.key); - item.append(!full || full === "…" ? el("div", "sess-detail sess-wait", t("Reading the session…")) : full.error ? el("div", "sess-detail sess-wait", full.error) : sessionDetail(full)); - } - body.append(item); - } - box.append(body); -} - -// the ways a session's shape is told, and the one shown -const SESS_SHAPES = [["messages", "Messages"], ["minutes", "Length"], ["autonomy", "Tool calls"]]; -let sessShapeBy = "messages"; -try { const v = localStorage.getItem("magpie.sessShape"); if (SESS_SHAPES.some(([id]) => id === v)) sessShapeBy = v; } catch {} - -// renderSessShape counts the range's sessions by how long they ran: by -// messages, by minutes at work, or by tool calls a prompt -function renderSessShape() { - const box = $("#sessShape"); - const ov = sessOver || {}; - box.replaceChildren(); - box.classList.toggle("stale", sessOverAt !== sessOverQ()); - const sh = ov.shape?.[sessShapeBy]; - const head = sessCardHead("Session shape"); - const seg = sessSegs(SESS_SHAPES, sessShapeBy, (id) => { - sessShapeBy = id; - try { localStorage.setItem("magpie.sessShape", id); } catch {} - renderSessShape(); - }); - head.append(seg, el("span", "grow"), el("span", "tz", sh ? t(sh.total === 1 ? "{n} session" : "{n} sessions", { n: fmtN(sh.total) }) : "")); - box.append(head); - slide(seg, "sessShape"); - if (!sh?.total) return box.append(el("div", "sess-none", ov.shape ? t("Nothing in this range.") : "…")); - const label = (i) => { - const lo = sh.edges[i], hi = sh.edges[i + 1]; - if (sessShapeBy === "autonomy" && lo === 0) return "<1"; - const r = hi == null ? lo + "+" : hi - 1 === lo ? String(lo) : `${lo}–${hi - 1}`; - return sessShapeBy === "minutes" ? t("{r}m", { r }) : r; - }; - const what = { messages: "{r} messages", minutes: "{r} minutes at work", autonomy: "{r} tool calls a prompt" }[sessShapeBy]; - const peak = Math.max(1, ...sh.counts); - const bars = el("div", "sess-shape"); - sh.counts.forEach((c, i) => { - const col = el("div", "col"); - const pct = Math.round(100 * c / sh.total); - col.title = t(what, { r: label(i) }) + " · " + t(c === 1 ? "{n} session" : "{n} sessions", { n: fmtN(c) }) + ` (${pct}%)`; - // a bar as tall as its share of the busiest bin, on a baseline; an - // empty bin a stub, so no grey column reads as a bar of its own - const plot = el("div", "plot"); - const fill = el("i", c ? "" : "none"); - fill.style.height = c ? `max(4px, calc((100% - 20px) * ${(c / peak).toFixed(3)}))` : ""; - plot.append(el("b", c ? "" : "zero", fmtN(c)), fill); - // the busiest bin in full, when one is busiest - col.classList.toggle("peak", c === peak && c > 0 && sh.counts.filter((n) => n === peak).length === 1); - col.append(plot, el("span", "", label(i))); - bars.append(col); - }); - box.append(bars); - // what the two axes are, said plainly - const axis = { messages: "messages in a session, prompts and replies", minutes: "minutes a session was at work", autonomy: "tool calls the agent made on its own for each prompt" }[sessShapeBy]; - const foot = el("div", "sess-card-foot"); - foot.append(el("span", "", t("Across: {axis} · Height: sessions", { axis: t(axis) }))); - box.append(foot); -} - -// the colours of the kinds of tool, as the calls are told apart -const TOOL_CATS = { Bash: "#e0823d", Edit: "#4f8cf0", Read: "#2fb087", Write: "#9b6cf0", Grep: "#e0608f", Glob: "#d4a72c", Task: "#35a9c7", Tool: "#7c83f2", Other: "#9aa0a8" }; -const toolColor = (c) => TOOL_CATS[c] || TOOL_CATS.Other; -// a kind's name, as its tools are named, "Other" aside -const toolKind = (c) => c === "Other" ? t("Other") : c; -function toolDot(c) { - const d = el("i", "dot"); - d.style.background = toolColor(c); - return d; -} - -// renderSessTools is what the sessions called their tools for: the most -// called, by kind, and week by week -function renderSessTools() { - const box = $("#sessTools"); - const tu = sessOver?.tools; - box.replaceChildren(); - box.classList.toggle("stale", sessOverAt !== sessOverQ()); - const head = sessCardHead("Tool use"); - head.append(el("span", "grow")); - if (tu?.calls) head.append(el("span", "tz", t("{n} calls", { n: fmtN(tu.calls) }) + " · " + t(tu.sessions === 1 ? "{n} session" : "{n} sessions", { n: fmtN(tu.sessions) }))); - box.append(head); - if (!tu?.calls) return box.append(el("div", "sess-none", tu ? t("No tool calls in this range.") : "…")); - const cols = el("div", "sess-tools-cols"); - - // the most called, each with its kind's dot, calls, sessions and share - const top = el("div", "sess-bars tools"); - const peak = Math.max(1, ...tu.top.map((x) => x.calls)); - for (const x of tu.top) { - const r = el("div", "sess-bar tool"); - r.title = `${x.name} · ${toolKind(x.category)}`; - const n = el("span", "n"); - n.append(toolDot(x.category), el("span", "", x.name)); - const track = el("span", "track"); - const fill = el("i"); - fill.style.width = Math.max(1.5, 100 * x.calls / peak).toFixed(1) + "%"; - fill.style.background = toolColor(x.category); - track.append(fill); - r.append(n, track, el("span", "v", fmtN(x.calls)), el("span", "s", t(x.sessions === 1 ? "{n} session" : "{n} sessions", { n: fmtN(x.sessions) })), - el("span", "p", Math.round(100 * x.calls / tu.calls) + "%")); - top.append(r); - } - cols.append(top); - - const side = el("div", "sess-tools-side"); - // by kind: one bar of every call, and each kind's count - const mix = el("div", "sess-mix"); - const kinds = el("div", "sess-kinds"); - for (const c of tu.categories) { - const seg = el("i"); - seg.style.flexGrow = c.calls; - seg.style.background = toolColor(c.name); - seg.title = `${toolKind(c.name)} · ${t("{n} calls", { n: fmtN(c.calls) })} (${Math.round(100 * c.calls / tu.calls)}%)`; - mix.append(seg); - const k = el("span", "kind"); - k.title = seg.title; - k.append(toolDot(c.name), el("span", "", toolKind(c.name)), el("b", "", fmtN(c.calls))); - kinds.append(k); - } - side.append(mix, kinds); - - // week by week, the last sixteen, each kind stacked - const weeks = tu.weeks.slice(-16); - if (weeks.length > 1) { - side.append(el("div", "sess-sub", t("By week"))); - const order = tu.categories.map((c) => c.name); - const total = (w) => Object.values(w.calls).reduce((a, b) => a + b, 0); - const wpeak = Math.max(1, ...weeks.map(total)); - const bars = el("div", "sess-weeks"); - for (const w of weeks) { - const bar = el("div", "bar"); - const n = total(w); - bar.title = t("week of {label}", { label: sessDay(sessDate(w.start)) }) + " · " + t("{n} calls", { n: fmtN(n) }); - const stack = el("div", "stack"); - stack.style.height = (n ? Math.max(2, 100 * n / wpeak) : 0).toFixed(1) + "%"; - for (const c of order) { - if (!w.calls[c]) continue; - const part = el("i"); - part.style.flexGrow = w.calls[c]; - part.style.background = toolColor(c); - stack.append(part); - } - bar.append(stack); - bars.append(bar); - } - const labels = el("div", "sess-weeks-labels"); - labels.append(el("span", "", sessDay(sessDate(weeks[0].start))), el("span", "", sessDay(sessDate(weeks[weeks.length - 1].start)))); - side.append(bars, labels); - } - cols.append(side); - box.append(cols); -} - -// renderSessSkills lists the skills the sessions called up, the most first -function renderSessSkills() { - const box = $("#sessSkills"); - const su = sessOver?.skills; - box.replaceChildren(); - box.classList.toggle("stale", sessOverAt !== sessOverQ()); - const head = sessCardHead("Top skills"); - head.append(el("span", "grow")); - if (su?.calls) head.append(el("span", "tz", t("{n} calls", { n: fmtN(su.calls) }) + " · " + t(su.count === 1 ? "{n} skill" : "{n} skills", { n: fmtN(su.count) }))); - box.append(head); - if (!su?.calls) return box.append(el("div", "sess-none", su ? t("No skill was called up in this range.") : "…")); - const names = sessStats?.agents || {}; - const peak = Math.max(1, ...su.top.map((x) => x.calls)); - const body = el("div", "sess-skills"); - for (const x of su.top) { - const r = el("div", "sess-skill"); - const line = el("div", "line"); - const track = el("span", "track"); - const fill = el("i"); - fill.style.width = Math.max(1.5, 100 * x.calls / peak).toFixed(1) + "%"; - track.append(fill); - line.append(el("span", "n", x.name), track, el("span", "v", fmtN(x.calls))); - const agents = Object.entries(x.agents || {}).sort((a, b) => b[1] - a[1]); - const share = agents.map(([a, c]) => `${names[a] || a} ${Math.round(100 * c / x.calls)}%`).join(" · "); - const where = (x.projects || []).map((p) => baseName(p.name)).join(", "); - const sub = el("div", "sub", [t(x.sessions === 1 ? "{n} session" : "{n} sessions", { n: fmtN(x.sessions) }), - x.last ? t("last {when}", { when: sessDay(sessDate(x.last)) }) : "", share, where].filter(Boolean).join(" · ")); - sub.title = (x.projects || []).map((p) => `${p.name} · ${t("{n} calls", { n: fmtN(p.calls) })}`).join("\n"); - r.append(line, sub); - body.append(r); - } - if (su.count > su.top.length) body.append(el("div", "sess-more", t("+{n} more", { n: su.count - su.top.length }))); - box.append(body); -} - -// sessBars is a card of folders or models as bars of the tokens each took; -// a click shows that one alone, and a click on it again every one -const SESS_BARS = 6; -function sessBars(box, title, items, cur, choose, name) { - box.replaceChildren(); - box.append(sessCardHead(title)); - const body = el("div", "sess-bars"); - let shown = items.slice(0, SESS_BARS); - const picked = cur && items.find((x) => x.v === cur); - if (picked && !shown.includes(picked)) shown = [...shown.slice(0, SESS_BARS - 1), picked]; - const peak = Math.max(1, ...items.map((x) => x.n)); - for (const x of shown) { - const r = el("button", "sess-bar" + (x.v === cur ? " on" : "")); - r.type = "button"; - r.title = [name(x.v) !== x.v ? x.v : "", x.v === cur ? t("Click again to show every one") : t("Click to show only this")].filter(Boolean).join("\n"); - const track = el("span", "track"); - const fill = el("i"); - fill.style.width = Math.max(1.5, 100 * x.n / peak).toFixed(1) + "%"; - track.append(fill); - const fc = x.cost ? fmtCost(x) : ""; - r.append(el("span", "n", name(x.v)), track, el("span", "v", fmtN(x.n)), el("span", "c", fc ? "≈" + fc : "")); - r.onclick = () => choose(x.v === cur ? "" : x.v); - body.append(r); - } - if (!items.length) body.append(el("div", "sess-none", t("Nothing in this range."))); - if (items.length > shown.length) body.append(el("div", "sess-more", t("+{n} more", { n: items.length - shown.length }))); - box.append(body); -} - // wslBadge marks a session an agent ran in a WSL distro, read through // \\wsl.localhost; its resume command runs it there through wsl.exe function wslBadge(s) { @@ -20489,20 +17643,6 @@ function wslBadge(s) { return b; } -// sessSpent is a session's tokens and cost, as the two right-hand columns -// of its row: the Usage page's list and the Sessions page's (#752) -function sessSpent(s) { - const tokens = sessTokens(s); - const num = el("div", "num" + (tokens ? "" : " none")); - num.append(el("b", "", tokens ? fmtN(tokens) : "—")); - if (tokens) num.append(el("small", "", t("{a} in · {b} out", { a: fmtN(s.input), b: fmtN(s.output) }) + (s.cache_read ? " · " + t("{n} cached", { n: fmtN(s.cache_read) }) : ""))); - const sc = sessCost(s); - const cost = el("div", "cost" + (sc === "—" ? " none" : ""), sc); - if (sc === "—") cost.title = t("No known price for {models}", { models: sessModelNames(s.models.map((m) => m.model)) || "—" }); - else if (s.unpriced) cost.title = t("Not counted: {models}, with no known price", { models: sessModelNames(s.models.filter((m) => !m.priced).map((m) => m.model)) }); - return [num, cost]; -} - // sessModelsText: a session's models, the first two and how many more, and // where magpie's gateway sent its calls, the most first: a routing group's // member and the reasoning it was asked for @@ -20511,62 +17651,6 @@ 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 row of the Usage page's list: what the session spent. It opens on the -// Sessions page, where it is resumed, read in full and deleted (#752: the -// two lists were one done twice, each lacking half). -function sessionItem(s) { - const item = el("div", "sess-item"); - const r = el("div", "row sess sess-link"); - r.tabIndex = 0; - r.setAttribute("role", "link"); - r.title = t("Open in Sessions"); - r.append(icon(s.icon || "generic")); - const who = el("div", "who"); - who.append(el("div", "name", s.title || t("(no prompt)"))); - const sub = el("div", "sub", [s.cwd ? baseName(s.cwd) : "", sessModelsText(s), ago(s.last)].filter(Boolean).join(" · ")); - sub.title = [s.cwd, ...(s.via || []).map(viaText)].filter(Boolean).join("\n"); - if (s.wsl) sub.prepend(wslBadge(s), " "); - who.append(sub); - r.append(who, ...sessSpent(s)); - const go = el("span", "sess-go"); - go.append(svg(CHEV_R, 12, 1.6)); - r.append(go); - const open = (e) => { - if (window.getSelection()?.toString()) return; - if (featuresOff.has("sessions")) return; // Sessions is switched off: there is no page to open it on - magpie.call("sessions", "reveal", s, e); - }; - r.onclick = open; - r.onkeydown = (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); open(e); } }; - item.append(r); - return item; -} - -function sessionDetail(s) { - const d = el("div", "sess-detail"); - const line = (label, value, extra) => { - const l = el("div", "sess-line"); - l.append(el("span", "k", label)); - const v = el("span", "v", value); - l.append(v); - if (extra) l.append(extra); - d.append(l); - }; - line(t("Time"), stamp(s.start) + " – " + stamp(s.last)); - if (s.wsl) line("WSL", s.wsl); - if (s.cwd) line(t("Folder"), s.cwd); - line(t("Session ID"), s.id, copyBtn(s.id, t("Session id"))); - if (s.resume) { - const code = el("code", "", s.resume); - const l = el("div", "sess-line"); - l.append(el("span", "k", t("Resume")), code, copyBtn(s.resume, t("Resume command"))); - d.append(l); - } - sessUsageDetail(d, s, line); - if (s.path) line(t("File"), s.path); - return d; -} - // 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 @@ -20588,17 +17672,6 @@ function viaText(v) { return `${v.provider}/${v.model}` + (v.effort ? " · " + v.effort : "") + " · " + t("{n} calls", { n: v.calls }); } -// All sessions: the Sessions page, on the agent picked here if one is -$("#sessAll").onclick = (e) => magpie.call("sessions", "reveal", sessAgent === "all" ? {} : { agent: sessAgent }, e); -$("#sessQ").oninput = (e) => { sessQuery = e.target.value; if (sessions) renderSessions(); }; -$("#sessQ").onkeydown = (e) => { if (e.key === "Escape" && e.target.value) { e.stopPropagation(); e.target.value = ""; sessQuery = ""; if (sessions) renderSessions(); } }; - -// ---------- settings ---------- -// -// Three choices (palette, language, what the tray icon opens) and the facts -// people come looking for: -// the version, where magpie keeps its files, the gateway's address. - const THEMES = [["system", "System"], ["light", "Light"], ["dark", "Dark"]]; const LOCALES = [["system", "System"], ["en", "English"], ["zh", "简体中文"], ["zh-TW", "繁體中文"], ["ja", "日本語"], ["de", "Deutsch"]]; const TRAYS = [["panel", "Open the quick panel"], ["window", "Open the main window"]]; @@ -20809,11 +17882,11 @@ function applyPrefs(s, rate) { if (got) fx = got; if (currency !== (s.currency || "usd") || (moved && currency === "cny")) { currency = s.currency || "usd"; - if (applyPrefs.painted) renderCosts(); + if (applyPrefs.painted) magpie.call("usage", "costs"); } if (chineseUnits !== !!s.chineseUnits) { chineseUnits = !!s.chineseUnits; - if (applyPrefs.painted) { renderCosts(); if (mode === "panel" && panelTab === "stats") renderPanelUse(); } + if (applyPrefs.painted) { magpie.call("usage", "costs"); if (mode === "panel" && panelTab === "stats") renderPanelUse(); } } applyPrefs.painted = true; if (!prefsBusy && (s.textSize || 100) !== textSize) { textSize = s.textSize || 100; newTextSize(); applyZoom(textSize); } @@ -24568,7 +21641,7 @@ async function show(v) { view = v; // the page the reader leaves is the one the window opens on next (keptView) if (mode === "window") { try { localStorage.setItem("magpie.lastView", v); } catch { /* not kept */ } } - const title = magpie.page(v)?.title ?? ({ agents: "Agents", providers: "Providers", usage: "Usage", plugins: "Plugins", settings: "Settings" })[v]; + const title = magpie.page(v)?.title ?? ({ agents: "Agents", providers: "Providers", plugins: "Plugins", settings: "Settings" })[v]; $("#pageTitle").dataset.en = title; $("#pageTitle").textContent = t(title); if (mode === "window") { @@ -24582,7 +21655,7 @@ async function show(v) { $("#prefs").classList.toggle("on", v === "settings"); if (v === "settings") $("#prefs").setAttribute("aria-current", "page"); else $("#prefs").removeAttribute("aria-current"); navSubs(); - for (const id of ["agents", "providers", "usage", "plugins", "settings", ...magpie.pages()]) $("#view-" + id).hidden = v !== id; + for (const id of ["agents", "providers", "plugins", "settings", ...magpie.pages()]) $("#view-" + id).hidden = v !== id; // back to where the reader was in it, and again once it has what it loads const back = () => backToReader($("#view-" + v)); requestAnimationFrame(back); @@ -24595,7 +21668,6 @@ async function show(v) { // Routing's accounts show their windows as the Usage page read them // (#1833): what is kept, read in an ordinary way, never an asked read if (v === "routing" && (!quotas || Date.now() - quotasAt > 60e3)) loadQuotas(); - if (v === "usage") loadUsage(true).then(back, (e) => status(e.message, "err")); if (v === "settings") loadSettings().then(back, (e) => status(e.message, "err")); if (v === "plugins") window.loadPlugins?.()?.then(back); syncTitle(); @@ -24755,7 +21827,7 @@ async function refreshPage(kind) { await Promise.all([loadInstalls(), loadCLIs()]); return t("Agents looked for again"); case "usage": - await refreshUsage(true); + await magpie.call("usage", "reload"); return t("Usage refreshed"); case "allowances": await loadQuotas(true); @@ -25364,117 +22436,6 @@ setInterval(async () => { ro.observe($("#usageCost")); new MutationObserver(later).observe(head, { childList: true, subtree: true, characterData: true }); } -// The Usage page reads its numbers again while it is looked at, as often as -// the reader says — off, or every 5 s to a minute (a request through the gateway -// shows within that; the subscriptions' windows each minute at most, the vendors' -// answers being cached behind them, and the sessions each 15 s) — redrawn only -// on a change. The button beside it reads them now. -const USAGE_EVERY = [[0, "Off"], [5, "5 s"], [10, "10 s"], [30, "30 s"], [60, "1 min"]]; -let usageEvery = 5; // seconds; 0 is off -try { - const v = localStorage.getItem("magpie.usageEvery"); - if (USAGE_EVERY.some(([n]) => String(n) === v)) usageEvery = Number(v); -} catch {} -let usageLast = 0, usageReadAt = 0, sessionsAt = 0, quotasAsked = 0; - -function renderUsageEvery() { - const cur = USAGE_EVERY.find(([n]) => n === usageEvery); - const b = $("#usageEvery"); - b.replaceChildren(el("span", "", t(cur[1])), svg(CHEV, 11, 1.6)); - b.title = t("Refresh every"); - b.onclick = (e) => { - e.stopPropagation(); - if (b.classList.contains("open")) return closeProtoMenu(); - openProtoMenu(b, USAGE_EVERY.map(([n, name]) => ({ v: String(n), name: t(name), note: "" })), String(usageEvery), (v) => { - usageEvery = Number(v); - try { localStorage.setItem("magpie.usageEvery", v); } catch {} - usageLast = performance.now(); - renderUsageEvery(); - }, "Refresh every", "sess-menu"); - }; - const r = $("#usageReload"); - // on the Overview it reads the allowances again too (#486: they had a - // Refresh of their own beside it) - const what = usageTab === "usage" ? t("Refresh now, the allowances too; a Claude account's is read by running Claude Code's own /usage") : t("Refresh now"); - r.title = usageReadAt ? what + " · " + t("Updated {time}", { time: new Date(usageReadAt).toLocaleTimeString(intlLang(), { hour12: false }) }) : what; - r.setAttribute("aria-label", t("Refresh now")); - r.onclick = async () => { - r.classList.add("busy"); - try { await refreshUsage(true); } finally { r.classList.remove("busy"); r.blur(); } - }; -} - -// refreshUsage reads what the tab shown draws; now is the reader asking, which -// reads the page it is on too, and the sessions and the allowances. -// A read that outlives its interval must not have another started behind it: -// one is in flight at a time, and a read asked for while one is (the timer, or -// the reader's button, which may not be swallowed) is served when it is done, -// the reader's own if either asked for it. The promise covers that second read -// too, so the button turns while the reader's own is still to come. -let usageFlight = null, usageQueued = false, usageQueuedNow = false; -// usageDrawn: the tab shown has its figures on the page already, which a -// quiet read (refreshUsage) only replaces when they changed -function usageDrawn() { - if (usageTab === "sessions") return !!(sessions && sessStats); - if (usageTab === "requests") return !!ledger; - if (usageTab === "context") return true; // loadContext keeps what it drew when nothing changed - return !!usage && !$("#view-usage").classList.contains("loading"); -} -function refreshUsage(now = false) { - usageLast = performance.now(); - if (usageFlight) { - usageQueued = true; - usageQueuedNow = usageQueuedNow || now; - return usageFlight; // this promise includes the queued read - } - const run = async (want) => { - try { - if (usageTab === "sessions") { - if (sessions && (want || performance.now() - sessionsAt > 15e3)) { sessionsAt = performance.now(); await loadSessions(); } - } else if (usageTab === "requests") { - // the newest page takes the requests as they come; an older one stays put - if (ledger && (want || !ledOffset)) await loadLedger(true); - } else if (usageTab === "context") { - await window.loadContext?.(); - } else { - // the reader asking reads the allowances afresh, a Claude account's by - // running Claude Code's own /usage (the backend runs it at most once in 30s) - let q = null; - if (want) { quotasAsked = performance.now(); q = loadQuotas(true); } - else if (usage && performance.now() - quotasAsked > 60e3) { quotasAsked = performance.now(); loadQuotas(); } - if (usage) { - const p = period, read = ++usageRead; - const u = await api("usage?period=" + encodeURIComponent(p)); - if (read === usageRead && view === "usage" && usageTab === "usage" && p === period) { - if (JSON.stringify(u) !== JSON.stringify(usage)) { usage = u; renderUsage(); } - // this read claimed the newest one: a pick it superseded had put the - // skeleton up, and the figures on hand are what ends it - else if ($("#view-usage").classList.contains("loading")) renderUsage(); - } - } - await q; - } - usageReadAt = Date.now(); - renderUsageEvery(); - } catch {} - }; - const flight = Promise.resolve().then(() => run(now)).then(() => { - if (usageFlight !== flight) return; - usageFlight = null; - if (!usageQueued) return; - const want = usageQueuedNow; - usageQueued = usageQueuedNow = false; - // one more read, the reader's own if either asked for it - return refreshUsage(want); - }); - usageFlight = flight; - return flight; -} -renderUsageEvery(); -setInterval(() => { - if (!usageEvery || view !== "usage" || document.hidden || document.querySelector(".pop:not([hidden])")) return; - if (performance.now() - usageLast >= usageEvery * 1000) refreshUsage(); -}, 1000); window.addEventListener("focus", () => load(true)); setInterval(renderUpdateBadge, 15 * 60 * 1000); // a window left open still hears of a new version // renderPluginDot puts a dot on Plugins while a plugin's update waits for @@ -25712,45 +22673,3 @@ if (mode === "window" && params.get("import")) { }).catch(() => {}); } if (mode === "window" && params.get("view") === "providers" && params.get("edit")) editing = params.get("edit"); -// opened from the tray panel's Usage tab: on the Requests of one provider or agent -if (mode === "window" && params.get("view") === "usage") { - // An explicit destination takes precedence over the remembered tab. - const tab = params.get("tab"); - if (tab === "requests" || tab === "usage") usageTab = tab; - // a total in the menu bar opens the Overview at its period - const per = params.get("period"); - if (PERIODS.some(([id]) => id === per)) period = per; - quotaFocus = usageTab === "usage" ? (params.get("card") || params.get("provider") || "") : ""; - quotaFocusUntil = performance.now() + 5000; - ledProvider = params.get("provider") || ""; - ledAgent = params.get("agent") || ""; - ledPurpose = params.get("purpose") || ""; - ledComputer = params.get("computer") || ""; - const v = params.get("via") || ""; - ledVia = v === "through" || v === "direct" || v === "reported" ? v : ""; - const u = new URL(location.href); - for (const k of ["tab", "provider", "agent", "computer", "card", "purpose", "via", "period"]) u.searchParams.delete(k); - history.replaceState(null, "", u); -} -// the plugins' pages wired up (kernel.js), before the first is shown -magpie.start(); -navHides(); // the pages built-in plugins switched off have, from boot.js -// The window opens on the page the reader last left, as a Mac app comes back -// as it was (molvqingtai, lc on Discord): a page asked for (?view=, a link -// from the tray or a reload) first, then the one kept; a page gateway mode -// leaves out, or one there is no longer, gives way to the first page. -// the pages the window can open on besides the first (Agents) -const OPEN_VIEWS = ["providers", "usage", "plugins", "settings", ...magpie.pages()]; -function keptView() { - const asked = params.get("view"); - if (asked === "agents" || OPEN_VIEWS.includes(asked)) return asked; - let v = ""; - try { v = localStorage.getItem("magpie.lastView") || ""; } catch { /* none kept */ } - return OPEN_VIEWS.includes(v) ? v : ""; // one gateway mode leaves out, show() makes Providers -} -const firstView = mode === "window" ? keptView() : ""; -if (OPEN_VIEWS.includes(firstView)) show(firstView); -else if (mode === "window" && !gatewayMode && !sideNav()) slide($("#nav"), "nav"); -// in gateway mode the first page is Providers, Agents' tab gone -if (gatewayMode) setGatewayMode(true); -load(); diff --git a/internal/gui/assets/context.js b/internal/gui/assets/context.js index f17dec00a..0dae6dc9d 100644 --- a/internal/gui/assets/context.js +++ b/internal/gui/assets/context.js @@ -735,6 +735,10 @@ let ctxDays = "7"; try { const d = localStorage.getItem("magpie.ctxDays"); if (CTX_RANGES.some(([id]) => id === d)) ctxDays = d; } catch {} let ctxData = null, ctxJSON = "", ctxRead = 0, ctxOpen = "", ctxAgent = "all"; + // the days the pane shows "Reading…" for: a second read before the history + // answers (the page opened, then the first state's refresh) leaves it be, + // so the advice drawn meanwhile keeps its entrance + let ctxWaiting = ""; const SCORE_NAMES = { cache: "Cache", lean: "Lean start", pace: "Pace", reliable: "Reliability" }; const SCORE_NOTES = { @@ -1258,7 +1262,8 @@ async function loadContext() { const read = ++ctxRead, days = ctxDays; if (tuneData && tuneData.days !== +days) tuneData = null; - if (!ctxData || ctxData.days !== +days) { ctxData = null; renderContext(); } + if (ctxData && ctxData.days !== +days) ctxData = null; + if (!ctxData && (ctxWaiting !== days || !$("#contextPane")?.childElementCount)) { ctxWaiting = days; renderContext(); } loadTune().catch((e) => status(e.message, "err")); const data = await api("context?days=" + days); if (read !== ctxRead) return; @@ -1274,7 +1279,4 @@ } window.loadContext = loadContext; window.renderContext = renderContext; - // opened on the Context tab (?view=usage): app.js showed it, and may have - // read the state, before this file was here to load it - if (view === "usage" && usageTab === "context") loadContext().catch((e) => status(e.message, "err")); })(); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 08e4e079b..3e0fbeaf0 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -51,16 +51,6 @@ const I18N = { "This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.": "这个请求的原文已不再保留:magpie 只在运行期间、仅在内存中保留最近 {n} 个请求的原文。", "As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.": "即 magpie 发出的内容,开启脱敏时为脱敏后的内容。仅在内存中保留最近 {n} 个请求。", "All of {part} · {n}": "全部{part} · {n}", - "Yesterday": "昨天", - "This month": "本月", - "Last month": "上个月", - "Pick days": "选择日期", - "Previous month": "上个月", - "Next month": "下个月", - "Days picked: {days}": "所选日期:{days}", - "Now the last day": "再选最后一天", - "Pick the first day, then the last": "先选第一天,再选最后一天", - "No calls on the days picked.": "所选日期内没有调用。", "{n} on {date}": "{date} {n}", "roles": "角色", "plan": "规划", @@ -379,8 +369,6 @@ const I18N = { "The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.": "{name} 已用的 Token 和费用一起清零,并从现在开始新的 {n} 天周期。", "The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets {when}.": "{name} 已用的 Token 和费用一起清零,本周期内此前的调用不再计入;周期仍在 {when} 重置。", "Usage reset for {name}": "已重置 {name} 的额度", - "All gateway keys": "全部网关密钥", - "All accounts": "全部账号", "account not recorded": "未记录账号", "Use a gateway key to track usage": "使用网关密钥统计用量", "Choose a gateway key to use as {env}; usage is tracked by key.": "选择填入 {env} 的网关密钥,用量按密钥统计。", @@ -745,6 +733,7 @@ const I18N = { "Parts of magpie not everyone needs. Switched off, a part leaves the sidebar, its pages and Settings; magpie works the same either way.": "不是人人都需要的部分。关掉后,它会从侧边栏、各页面和设置中隐去;magpie 的工作方式不变。", "Your agents' past conversations: read, search, resume and export them": "Agent 的历史对话:查看、搜索、继续和导出", "Each request as the gateway routes it, the accounts it weighed and what each answered, and your routing groups": "每个请求经网关路由的过程、它比较过的账号和各自的回应,以及你的路由组", + "Your allowances, what was spent and on what, each request, and what filled the context window": "你的额度、花费及其去向、每个请求,以及上下文窗口里装了什么", "Recording gateway conversations": "正在记录网关对话", "Instructions, MCP servers, skills and hooks, kept once and given to every agent": "指令、MCP 服务器、技能和 Hooks,统一管理,分发给每个 Agent", "1 item given to agents": "1 项已分发给 Agent", @@ -2281,8 +2270,6 @@ const I18N = { "usage": "用量", "Couldn't share usage: {error}": "用量未能共享:{error}", "All computers": "全部电脑", "Other computers": "其他电脑", "Computer": "电脑", - "{agent} · on {computer}": "{agent} · 在 {computer}", - "What was said stays on {computer}: sync shares the usage alone.": "对话内容留在 {computer} 上:同步只共享用量。", "Address": "地址", "User": "用户", "Password": "密码", "Passphrase": "口令", "Also sync": "同时同步", "A folder named magpie is made in it.": "会在其中建一个名为 magpie 的文件夹。", "The file is sealed with it on this computer; the server only ever sees it sealed. Keep it: without it the file can't be opened.": "文件在本机用它加密,服务器只能看到加密后的内容。请记住它:没有口令无法打开文件。", @@ -2348,7 +2335,6 @@ const I18N = { "Key": "密钥", "{env}=magpie. The gateway trusts everything on loopback, so any value works.": "{env}=magpie。网关信任本机回环请求,可填任意值。", "Model": "模型", - "Model · provider": "模型 · 供应商", "Model id": "模型 ID", "Model ids": "模型 ID", "provider/model, as listed below. Click a model there to put it in the snippets.": "格式为 provider/model,见下方列表。点击某个模型即可放入示例。", @@ -2402,7 +2388,6 @@ const I18N = { "This archive is {size}, too large to show here. Download it to read it.": "存档 {size},过大无法在此显示,请下载后查看。", "very large": "非常大", "first {n} of {size}": "前 {n},共 {size}", - "Not archived": "无存档", "Reply": "回复", "Events": "事件", "Raw": "原文", @@ -2443,13 +2428,9 @@ const I18N = { "A heavier model fills a window sooner: this holds for the models used so far": "越重的模型越快用满窗口:这个数只对目前用过的模型成立", "{n} call had no known price and is not counted": "{n} 次调用没有已知价格,未计入", "{n} calls had no known price and are not counted": "{n} 次调用没有已知价格,未计入", - "Estimated using effective model prices, including custom prices": "按模型生效价格估算,包含自定义价格", // requests: the Usage page's ledger - "Search models, providers, sessions": "搜索模型、供应商、会话", "Export CSV": "导出 CSV", - "Save every request listed, all pages, as a CSV file in Downloads": "将列出的全部请求(所有页)存为 CSV,保存到“下载”文件夹", - "All agents": "全部 Agent", "All purposes": "全部用途", "Purpose": "调用用途", "Filter the request list by purpose": "按调用用途筛选请求列表", @@ -2458,24 +2439,13 @@ const I18N = { "{n} request": "{n} 个请求", "{n} requests": "{n} 个请求", "{n} in": "输入 {n}", - "{n} out": "输出 {n}", - "{n} cache write": "缓存写入 {n}", - "{n} cache read": "缓存读取 {n}", "through magpie": "经过 magpie", "not through magpie": "不经过 magpie", - "reported by apps": "由应用上报", "Reported": "上报", - "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "由发起请求的应用通过 POST /v1/magpie/usage/requests 上报:这次请求直接发给了服务商,没有经过 magpie。", - "all requests": "全部请求", - "Show only these requests": "只看这些请求", - "Show every request again": "重新显示全部请求", - "View routing": "查看路由", "Clear filter": "清除筛选", - "Request: {what}": "请求:{what}", "No requests match these filters.": "没有符合这些筛选条件的请求。", "Time": "时间", "Requested": "请求模型", - "Provider · account": "供应商 · 账号", "Sent": "发送模型", "Served": "实际模型", "In": "输入", @@ -2488,27 +2458,16 @@ const I18N = { "Long-context price, over": "长上下文价格,超过", "Long-context price": "长上下文价格", "A long-context price starts over a number of input tokens, like 272K": "长上下文价格要写从多少输入 token 起算,比如 272K", - "{m} for 5 minutes, {h} for an hour": "{m} 保留 5 分钟,{h} 保留 1 小时", "Cache read": "缓存读取", "Duration": "耗时", "Status": "状态", - "session {id}": "会话 {id}", - "{agent} · via {host}": "{agent} · 来自 {host}", - "Not kept for requests before this version": "此版本之前的请求没有记下", - "{n} reasoning, inside output": "其中推理 {n}(已计入输出)", - "No known price for this model": "此模型没有已知价格", - "Failed: the agent was answered {status}": "失败:Agent 收到的是 {status}", "Succeeded": "成功", "Request ID": "请求 ID", "Error": "错误", - "Error type": "错误类型", - "Upstream said": "上游返回", "First token": "首响", "Reasoning tokens": "推理 token", "Called for": "用途", - "Data source": "数据来源", "Session ID": "会话 ID", - "Nothing more was kept of this request": "这个请求没有更多记录", "Input": "输入", "Output": "输出", "You": "你", @@ -2524,15 +2483,10 @@ const I18N = { "Image": "图片", "Show full content": "展开全部", "Collapse content": "收起", - "OFFICIAL": "官方", "Nothing was said here": "这里没有内容", "There was more than is shown here": "内容太多,这里只显示了一部分", "… {n} more characters not shown": "……还有 {n} 个字符未显示", "Read from the agent's session file; magpie keeps no copy": "读自 Agent 的会话文件,magpie 不保存副本", - "No session was named with this request, so its session file can't be found": "此请求未带会话 ID,找不到其会话文件", - "magpie reads the session files of Claude Code, Claude Desktop and Codex only": "magpie 只读 Claude Code、Claude Desktop 和 Codex 的会话文件", - "This request isn't in the agent's session files: they may be deleted, moved, or not written yet": "Agent 会话文件中没有此请求:文件可能已删除、移走或尚未写入", - "The session file couldn't be read": "会话文件读取失败", "Cache hit rate": "缓存命中率", "Metrics": "指标", "Usage trend": "使用趋势", @@ -2541,23 +2495,15 @@ const I18N = { "10 s": "10 秒", "30 s": "30 秒", "1 min": "1 分钟", - "Refresh every": "刷新周期", "Refresh now": "立即刷新", "Refresh this card": "刷新这张卡片", "Read this card again": "只刷新这张卡片的用量,其他卡片不动", "Read this card again, by running Claude Code's own /usage": "只刷新这张卡片的用量(运行 Claude Code 自己的 /usage),其他卡片不动", - "Updated {time}": "更新于 {time}", - "Model recorded in the local session log; the outbound HTTP request was not captured.": "本地会话日志记录的模型;未采集实际发出的 HTTP 请求。", - "About: told from the session file's times, a little more or less than it took": "估算值:按会话文件中的时间计算,与实际耗时略有出入", "Open Usage": "打开用量", "No requests today": "今天还没有请求", "No requests here": "这里没有请求", "Every request an agent sends to magpie, and every call the agents' own session files record, is counted here.": "统计 Agent 发给 magpie 的每个请求,以及 Agent 会话文件记录的每次调用。", "{n} unpriced": "{n} 个没有价格", - "{n} call unpriced": "{n} 次调用未计价", - "{n} calls unpriced": "{n} 次调用未计价", - "{n} model unpriced": "{n} 个模型未计价", - "{n} models unpriced": "{n} 个模型未计价", "of the prompt": "占提示词", "Provider": "供应商", "All providers": "全部供应商", @@ -2567,36 +2513,16 @@ const I18N = { "none failed": "没有失败", "{n} answered on a retry": "{n} 次重试后成功", "Retried": "重试后成功", - "Show only the requests answered on a retry": "只看重试后成功的请求", - "Show only the failed requests": "只看失败的请求", "handed on": "已转交", - "This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "这次尝试失败,请求已转交给下一个:请求按最终结果计数,不算这次尝试", - "{p} succeeded": "成功 {p}", - "{a} cache": "缓存 {a}", "The share of the prompt read from the cache": "提示词中从缓存读取的比例", "Newer": "较新", "Older": "较早", - "{a}–{b} of {n}": "第 {a}–{b} 条,共 {n} 条", - "Each request's tokens as its provider reported them; the cost estimated using effective model prices, including custom prices. Export CSV saves every page.": "每个请求的 token 数取自供应商报告,费用按模型生效价格(含自定义价格)估算。导出 CSV 包含所有页。", - "Saved {n} request to {path}": "已将 {n} 个请求保存到 {path}", - "Saved {n} requests to {path}": "已将 {n} 个请求保存到 {path}", // sessions "Overview": "概览", "Local session": "本地会话", - "Login method": "登录方式", - "Official login": "官方登录", - "Duration colors: ≤10 s green · 10–30 s amber · >30 s red": "耗时颜色:≤10 秒绿色 · 10–30 秒黄色 · >30 秒红色", - "Official login confirmed for this account by local login metadata. This does not establish the route or authentication used for this request.": "本地登录资料确认此账号采用官方登录;不代表已确认这次请求的渠道或认证方式。", "Subscription": "订阅账号", - "API price reference": "API 估价参考模型", - "Price reference: {model}": "估价参考:{model}", - "Model used for the API price estimate; this is not an observed model forwarding event.": "用于 API 费用估算的参考模型;并非实际观测到的模型转发记录。", - "Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred.": "读自 Agent 的会话文件;仅在本地元数据能够明确识别时显示账号,不推断供应商。", - "Read from the agent's session file, which names the provider it was set up to call. The name shown is that record, not a route magpie saw.": "读自 Agent 的会话文件,其中记录了它被配置去调用的供应商。此处显示的就是那条记录,不是 magpie 看到的路由。", "Recorded provider ID": "日志中的供应商标识", - "Session account": "会话账号", - "Gateway calls only; session-log calls are in Requests. Local rejections are excluded from totals.": "仅统计网关调用;会话日志调用请查看「请求」。本地拒绝的请求不计入汇总。", "Gateway and session-log calls; local rejections excluded from totals.": "统计网关调用与会话日志调用;本地拒绝的请求不计入汇总。", "Sessions": "会话", "Search sessions": "搜索会话", @@ -2630,31 +2556,15 @@ const I18N = { "{n} folder": "{n} 个文件夹", "{n} folders": "{n} 个文件夹", "cost": "费用", - "at effective prices": "按生效价格", "just now": "刚刚", "No session matches.": "没有匹配的会话。", "No sessions yet. Claude Code's, Codex's, Hermes, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.": "还没有会话。本机 Claude Code、Codex、Hermes、OpenCode 和 Pi 的会话会显示在这里,附费用和继续会话的命令。", - "Reading the agents' session files…": "正在读取 Agent 的会话文件…", "Totals count every session in the agents' own files; the list is the latest {n} by activity · {dirs}": "合计含 Agent 文件中的全部会话;列表为最近活动的 {n} 个 · {dirs}", - "Totals count native sessions and gateway requests with a session ID": "合计含本机会话和带有会话 ID 的网关请求", - "showing {drawn} of {n}": "显示 {n} 个中的 {drawn} 个", "90 days": "90 天", - "All folders": "全部文件夹", "Search {n}…": "搜索 {n} 项…", "No match": "没有匹配项", - "Indexing your sessions": "正在为你的会话建立索引", - "Looking for session files…": "正在查找会话文件…", - "Reading the kept index…": "正在读取已建好的索引…", - "Indexed · putting the page together…": "索引完成 · 正在生成页面…", - "{done} of {files} files · {read} of {bytes}": "{done} / {files} 个文件 · {read} / {bytes}", - "about {t} left": "约剩 {t}", "{n}s": "{n} 秒", - "Read once, kept: after this the page opens from the index in a blink": "只需索引一次:之后打开这一页几乎是瞬间的", - "Only what changed is read again, from where it was left": "之后只读新增的部分,从上次读到的地方接着读", - "Every session is read on this computer; nothing leaves it": "所有会话都在本机读取,不会上传到任何地方", - "The biggest files go first, so none is left running on alone": "最大的文件先读,所有核心一起跑满", "{n} more — type to narrow": "还有 {n} 项 — 输入以筛选", - "Nothing in this range.": "这段时间没有用量。", "active": "活跃时长", "not kept by model": "不按模型统计", "Active": "活跃", @@ -2663,68 +2573,25 @@ const I18N = { "Activity": "活跃度", "nothing": "无", "Less": "少", - "Usage heatmap": "用量热力图", - "Daily usage over the last 53 weeks": "最近 53 周的每日用量", "No requests": "无请求", "More": "多", "{n} session": "{n} 个会话", "{n} sessions": "{n} 个会话", "{n} day": "{n} 天", "{n} days": "{n} 天", - "{d} active": "活跃 {d}", - "Latest sessions": "最近的会话", "All sessions": "全部会话", - "Open in Sessions": "在会话页打开", - "Top sessions": "最耗会话", "Output tokens": "输出 Token", "Messages": "消息", "{n} message": "{n} 条消息", "{n} messages": "{n} 条消息", - "Session shape": "会话形态", "Length": "时长", "Tool calls": "工具调用", - "{r}m": "{r} 分钟", - "{r} messages": "{r} 条消息", - "{r} minutes at work": "工作 {r} 分钟", - "{r} tool calls a prompt": "每条提示 {r} 次工具调用", - "Across: {axis} · Height: sessions": "横轴:{axis} · 柱高:会话数", - "messages in a session, prompts and replies": "一个会话里的消息数(提示加回复)", - "minutes a session was at work": "一个会话实际工作的分钟数", - "tool calls the agent made on its own for each prompt": "你每发一条提示,Agent 自己调用工具的次数", "Tool use": "Tool 使用", - "No tool calls in this range.": "这段时间没有工具调用。", "Other": "其他", - "Top skills": "常用 Skills", - "No skill was called up in this range.": "这段时间没有调用 skill。", - "last {when}": "最近 {when}", - "By hour": "按时段", - "Still counting": "还在统计", - "days at work": "活跃天数", - "longest streak": "最长连续", - "busiest day": "最忙的一天", "+{n} more": "还有 {n} 个", - "Reading the session…": "正在读取会话…", - "Click to show only this": "点击只看这一项", - "Click again to show every one": "再点一次显示全部", - "median {m} · p90 {p}": "中位 {m} · p90 {p}", - "{p} in {name}": "{name} 占 {p}", - "Busiest at {when}": "最忙:{when}", - "Active time isn't kept by model.": "活跃时长不按模型统计。", - "No active time in this range.": "这段时间没有活跃时长。", - "Tokens in and out per session: the middle session's, and what nine in ten stay under": "每个会话的输入加输出 token:中位数,以及九成会话不超过的量", - "on {n} day": "共 {n} 天", - "on {n} days": "共 {n} 天", - "The time the sessions were at work: the pauses between one message and the next, each under five minutes": "会话实际工作的时间:相邻两条消息之间的间隔,只计不到五分钟的", "<1m": "<1 分钟", - "{m}m": "{m} 分钟", - "{h}h {m}m": "{h} 小时 {m} 分", - "By day": "每日趋势", - "By week": "每周趋势", "Tokens": "Token", "Cost": "费用", - "{when} · {tokens} tokens": "{when} · {tokens} token", - "No known price for {models}": "{models} 没有已知价格", - "Not counted: {models}, with no known price": "未计入:{models},没有已知价格", "a model with no name": "未注明名称的模型", "{n} session used a model with no known price; its share is not counted": "{n} 个会话用了没有已知价格的模型,这部分未计入", "{n} sessions used a model with no known price; their share is not counted": "{n} 个会话用了没有已知价格的模型,这部分未计入", @@ -2840,11 +2707,6 @@ const I18N = { "Chat requests": "聊天请求", "Completions": "代码补全", "Premium requests": "高级请求", - "No calls today.": "今天没有调用。", - "No calls in the last 7 days.": "最近 7 天没有调用。", - "No calls in the last 30 days.": "最近 30 天没有调用。", - "No calls yet.": "还没有调用。", - "Point an agent at a catalog model and use it; every call through the gateway is counted here.": "让某个 Agent 使用目录中的模型;每次经过网关的调用都会计入这里。", "tokens": "token", "{a} in · {b} out": "输入 {a} · 输出 {b}", "cache read": "缓存读取", @@ -2853,21 +2715,16 @@ const I18N = { "reasoning": "推理", "agent": "Agent", "member": "成员", - "inside output": "计入输出", "call": "次调用", "calls": "次调用", "{n} failed": "{n} 次失败", "{n} looped": "{n} 次陷入循环", "Replies magpie ended because the model kept repeating itself": "magpie 因模型一直重复自己而中止的回复", "week of {label}": "{label} 起的一周", - "{when} · {tokens} tokens · {n} call": "{when} · {tokens} token · {n} 次调用", - "{when} · {tokens} tokens · {n} calls": "{when} · {tokens} token · {n} 次调用", "{when} · nothing": "{when} · 无", "{n} call": "{n} 次调用", "{n} calls": "{n} 次调用", - "{n}% of tokens": "占 token 的 {n}%", "{n} cached": "缓存 {n}", - "Counted from the providers' own usage reports on every call through the gateway · {path}": "根据供应商在每次网关调用中返回的用量统计 · {path}", // sync "Model lists refreshed": "模型列表已刷新", @@ -3050,17 +2907,8 @@ const I18N = { "This key is set to {api} only, but {name} has no {api} URL, so no request reaches {api} with it. Fill in the {api} URL, or set the key to Any protocol.": "这个 key 只用于 {api},但 {name} 没有填 {api} 地址,所以用这个 key 的请求到不了 {api}。请填上 {api} 地址,或者把 key 改回「任意协议」。", "any API": "任意 API", "models agents pick as one": "Agent 当作一个模型来选", - "Hide from this list": "从列表中隐藏", - "Count as an agent…": "计入某个 Agent…", - "Count {client} on its own": "将 {client} 单独计算", - "with {clients}": "含 {clients}", - "Count this client's calls as": "将此客户端的调用计入", - "{client} is counted as {agent}": "{client} 已计入 {agent}", - "{client} is counted on its own": "{client} 已单独计算", "Client": "客户端", - "Actions for {name}": "{name} 的操作", "Unhide": "取消隐藏", - "Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "只是不在此列表中显示,它们的调用仍计入总数和图表。点击查看。", "found by magpie": "magpie 自动发现", "no member ready": "没有可用成员", // a manual group (#317) @@ -3086,10 +2934,6 @@ const I18N = { "min": "分钟", "slow to start": "迟迟未开始", "In magpie": "magpie 内耗时", - "Vendor's first token": "厂商首字等待", - "Tries that failed first": "之前失败的尝试", - "Waiting for a slot": "排队等空位", - "Connecting and sending": "连接并发送请求", "One rate limited while it still has quota rests as long as the vendor asks, then takes its place in the order again.": "仍有额度却被限流的账号按厂商要求休息,之后回到原位继续使用。", "One rate limited (429) while it still has quota goes to the back of the order, behind every one not rate limited since, and comes round again once those ahead of it are rate limited in turn — so the load goes round rather than back to the first each time. Out of quota, it rests as usual. Kept until magpie restarts.": "仍有额度却被限流(429)的账号排到最后,位于此后所有未被限流的账号之后;前面的账号依次被限流后才再轮到它,负载因此轮转,而非每次回到第一个。额度用完的照常休息。此顺序保留到 magpie 重启。", "Rules": "规则", @@ -3169,7 +3013,6 @@ const I18N = { "A conversation stays put within a turn, while the agent sends tool results back; when you speak again, routing decides afresh.": "一轮之内(Agent 回传工具结果时)不换;你再次发言时,路由重新决定。", "Every request is routed afresh, whoever answered its conversation before.": "每个请求都重新路由,不论之前由谁回答。", "Mask the accounts on this page — email addresses and account names — for a screenshot to share": "给本页的账号(邮箱地址和账号名)打码,方便截图分享", - "Refresh now, the allowances too; a Claude account's is read by running Claude Code's own /usage": "立即刷新,含额度;Claude 账号的额度通过运行 Claude Code 自带的 /usage 读取", "Least used": "最少使用", "requests": "请求", "request": "请求", @@ -3233,7 +3076,6 @@ const I18N = { "Image description": "图片描述", "Routing classifier": "路由分类器", "magpie's own": "magpie 自身", - "{n} by magpie itself": "其中 {n} 次由 magpie 自身发出", "{n} request in this period was magpie's own": "此期间有 {n} 个请求是 magpie 自身发出的", "{n} requests in this period were magpie's own": "此期间有 {n} 个请求是 magpie 自身发出的", "Requests magpie made by itself, not an agent: a routing group's classifier, a web search or an image description. They count against the key or account like any other request.": "magpie 自身发出的请求,而非智能体发出的:路由组的分类器、网页搜索或图片描述。它们与其他请求一样计入密钥或账号的用量。", @@ -3303,22 +3145,11 @@ const I18N = { "TTFT {ms}": "首字 {ms}", "Speed": "速度", "Output speed": "输出速度", - "first token in {ms} on average": "首字平均 {ms}", - "no streamed replies timed": "没有可计时的流式回复", "Output tokens a second after the first, over the streamed replies": "流式回复从首响起每秒输出的 token 数", "No streamed replies timed in this period": "这段时间没有可计时的流式回复", - "Sent, Effort and the cache are in each row's details": "窗口较窄:发送模型、推理强度和缓存在每行的详情里", - "{n} output tokens in {ms} after the first": "首字后 {ms} 输出 {n} 个 token", - "At least: {n} output tokens in {ms}, from the line that asked for it to its last. The session file has no first token, so the wait for it is counted too": "下限:从发出请求的那一行到最后一行,{ms} 输出 {n} 个 token。会话文件没有首字时间,等首字的时间也算在里面", - "At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too": "下限:首字后 {ms} 输出 {n} 个正文 token,{r} 个推理 token 不计。会话文件没有首个正文的时间,首字后的推理时间也算在里面", - "At least: {n} output tokens in {ms}, the whole turn. What came after the first token ({after}) is too little to time a speed by: under a second or under 100 tokens, so the wait for it is counted too": "下限:整轮 {ms} 输出 {n} 个 token。首字后只有 {after},不足 1 秒或不足 100 个 token,测不出速度,等首字的时间也算在里面", - "The session file has no first token to time a speed from": "会话文件没有首字时间,算不出速度", "A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "有推理的回复只算正文部分,从首个正文起计:推理在流里出现前就已写完", "No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "没有正文时,仅在可见推理持续流式输出时将其计入速度;隐藏推理不显示速度", - "{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "首个正文后 {ms} 输出 {n} 个正文 token,之前的 {r} 个推理 token 不计", - "Not streamed: no first token to time a speed from": "非流式:没有首字时间,算不出速度", "Cache": "缓存", - "{i} in · {o} out · {r} cache read · {w} cache creation": "输入 {i} · 输出 {o} · 缓存读取 {r} · 缓存创建 {w}", "first token in {ms}": "{ms} 后首响", "{n} tok/s": "{n} token/秒", "{k} timed reply": "{k} 次计时", @@ -3332,11 +3163,8 @@ const I18N = { "Measured on {k} replies, from their first token to their end": "实测 {k} 次回复:从首字到结束", "At least: {k} reply read from a session file, which doesn't say when its answer began, so time before that is counted too": "下限:{k} 次读自会话文件的回复。会话文件不记录正文何时开始,之前的时间也算在里面", "At least: {k} replies read from session files, which don't say when their answers began, so time before that is counted too": "下限:{k} 次读自会话文件的回复。会话文件不记录正文何时开始,之前的时间也算在里面", - "Upstream provider": "上游", "Protocol": "协议", "Upstream stop reason": "上游结束原因", - "The agent spoke {from}; sent upstream as {to}": "agent 用 {from} 协议请求;以 {to} 协议发往上游", - "Sent upstream as {to}, as the agent spoke it": "以 {to} 协议发往上游,与 agent 所用协议相同", "Open Routing": "打开路由", "{n} min": "{n} 分钟", "{n} h": "{n} 小时", @@ -3772,16 +3600,6 @@ const I18N = { "This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.": "這個請求的原文已不再保留:magpie 只在執行期間、僅在記憶體中保留最近 {n} 個請求的原文。", "As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.": "即 magpie 送出的內容,開啟遮罩時為遮罩後的內容。僅在記憶體中保留最近 {n} 個請求。", "All of {part} · {n}": "全部{part} · {n}", - "Yesterday": "昨天", - "This month": "本月", - "Last month": "上個月", - "Pick days": "選擇日期", - "Previous month": "上個月", - "Next month": "下個月", - "Days picked: {days}": "所選日期:{days}", - "Now the last day": "再選最後一天", - "Pick the first day, then the last": "先選第一天,再選最後一天", - "No calls on the days picked.": "所選日期內沒有呼叫。", "{n} on {date}": "{date} {n}", "roles": "角色", "plan": "規劃", @@ -4103,8 +3921,6 @@ const I18N = { "The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.": "{name} 已用的 Token 和費用一起歸零,並從現在開始新的 {n} 天週期。", "The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets {when}.": "{name} 已用的 Token 和費用一起歸零,本週期內此前的呼叫不再計入;週期仍在 {when} 重置。", "Usage reset for {name}": "已重置 {name} 的額度", - "All gateway keys": "全部閘道金鑰", - "All accounts": "全部帳號", "account not recorded": "未記錄帳號", "Use a gateway key to track usage": "使用閘道金鑰統計用量", "Choose a gateway key to use as {env}; usage is tracked by key.": "選擇填入 {env} 的閘道金鑰,用量按金鑰統計。", @@ -4462,6 +4278,7 @@ const I18N = { "Parts of magpie not everyone needs. Switched off, a part leaves the sidebar, its pages and Settings; magpie works the same either way.": "不是人人都需要的部分。關掉後,它會從側邊欄、各頁面和設定中隱去;magpie 的運作方式不變。", "Your agents' past conversations: read, search, resume and export them": "Agent 的歷史對話:檢視、搜尋、繼續和匯出", "Each request as the gateway routes it, the accounts it weighed and what each answered, and your routing groups": "每個請求經閘道路由的過程、它比較過的帳號和各自的回應,以及你的路由組", + "Your allowances, what was spent and on what, each request, and what filled the context window": "你的額度、花費及其去向、每個請求,以及上下文視窗裡裝了什麼", "Recording gateway conversations": "正在記錄閘道對話", "Instructions, MCP servers, skills and hooks, kept once and given to every agent": "指令、MCP 伺服器、技能和 Hooks,統一管理,分發給每個 Agent", "1 item given to agents": "1 項已分發給 Agent", @@ -5976,8 +5793,6 @@ const I18N = { "All computers": "全部電腦", "Other computers": "其他電腦", "Computer": "電腦", - "{agent} · on {computer}": "{agent} · 在 {computer}", - "What was said stays on {computer}: sync shares the usage alone.": "對話內容留在 {computer} 上:同步只共享用量。", "Address": "位址", "User": "使用者", "Password": "密碼", @@ -6053,7 +5868,6 @@ const I18N = { "Key": "金鑰", "{env}=magpie. The gateway trusts everything on loopback, so any value works.": "{env}=magpie。閘道信任本機迴環請求,可填任意值。", "Model": "模型", - "Model · provider": "模型 · 供應商", "Model id": "模型 ID", "Model ids": "模型 ID", "provider/model, as listed below. Click a model there to put it in the snippets.": "格式為 provider/model,見下方列表。點選某個模型即可放入範例。", @@ -6107,7 +5921,6 @@ const I18N = { "This archive is {size}, too large to show here. Download it to read it.": "存檔 {size},過大無法在此顯示,請下載後檢視。", "very large": "非常大", "first {n} of {size}": "前 {n},共 {size}", - "Not archived": "無存檔", "Reply": "回覆", "Events": "事件", "Raw": "原文", @@ -6146,11 +5959,7 @@ const I18N = { "A heavier model fills a window sooner: this holds for the models used so far": "越重的模型越快用滿視窗:這個數只對目前用過的模型成立", "{n} call had no known price and is not counted": "{n} 次呼叫沒有已知價格,未計入", "{n} calls had no known price and are not counted": "{n} 次呼叫沒有已知價格,未計入", - "Estimated using effective model prices, including custom prices": "按模型生效價格估算,包含自定義價格", - "Search models, providers, sessions": "搜尋模型、供應商、會話", "Export CSV": "匯出 CSV", - "Save every request listed, all pages, as a CSV file in Downloads": "將列出的全部請求(所有頁)存為 CSV,儲存到「下載」資料夾", - "All agents": "全部 Agent", "All purposes": "全部用途", "Purpose": "呼叫用途", "Filter the request list by purpose": "按呼叫用途篩選請求列表", @@ -6159,24 +5968,13 @@ const I18N = { "{n} request": "{n} 個請求", "{n} requests": "{n} 個請求", "{n} in": "輸入 {n}", - "{n} out": "輸出 {n}", - "{n} cache write": "快取寫入 {n}", - "{n} cache read": "快取讀取 {n}", "through magpie": "經過 magpie", "not through magpie": "不經過 magpie", - "reported by apps": "由應用程式回報", "Reported": "回報", - "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "由發出請求的應用程式透過 POST /v1/magpie/usage/requests 回報:這次請求直接送往服務商,沒有經過 magpie。", - "all requests": "全部請求", - "Show only these requests": "只看這些請求", - "Show every request again": "重新顯示全部請求", - "View routing": "檢視路由", "Clear filter": "清除篩選", - "Request: {what}": "請求:{what}", "No requests match these filters.": "沒有符合這些篩選條件的請求。", "Time": "時間", "Requested": "請求模型", - "Provider · account": "供應商 · 帳號", "Sent": "傳送模型", "Served": "實際模型", "In": "輸入", @@ -6189,27 +5987,16 @@ const I18N = { "Long-context price, over": "長上下文價格,超過", "Long-context price": "長上下文價格", "A long-context price starts over a number of input tokens, like 272K": "長上下文價格要寫從多少輸入 token 起算,比如 272K", - "{m} for 5 minutes, {h} for an hour": "{m} 保留 5 分鐘,{h} 保留 1 小時", "Cache read": "快取讀取", "Duration": "耗時", "Status": "狀態", - "session {id}": "會話 {id}", - "{agent} · via {host}": "{agent} · 來自 {host}", - "Not kept for requests before this version": "此版本之前的請求沒有記下", - "{n} reasoning, inside output": "其中推理 {n}(已計入輸出)", - "No known price for this model": "此模型沒有已知價格", - "Failed: the agent was answered {status}": "失敗:Agent 收到的是 {status}", "Succeeded": "成功", "Request ID": "請求 ID", "Error": "錯誤", - "Error type": "錯誤型別", - "Upstream said": "上游返回", "First token": "首響", "Reasoning tokens": "推理 token", "Called for": "用途", - "Data source": "資料來源", "Session ID": "會話 ID", - "Nothing more was kept of this request": "這個請求沒有更多記錄", "Input": "輸入", "Output": "輸出", "You": "你", @@ -6225,15 +6012,10 @@ const I18N = { "Image": "圖片", "Show full content": "展開全部", "Collapse content": "收起", - "OFFICIAL": "官方", "Nothing was said here": "這裡沒有內容", "There was more than is shown here": "內容太多,這裡只顯示了一部分", "… {n} more characters not shown": "……還有 {n} 個字元未顯示", "Read from the agent's session file; magpie keeps no copy": "讀自 Agent 的會話檔案,magpie 不儲存副本", - "No session was named with this request, so its session file can't be found": "此請求未帶會話 ID,找不到其會話檔案", - "magpie reads the session files of Claude Code, Claude Desktop and Codex only": "magpie 只讀 Claude Code、Claude Desktop 和 Codex 的會話檔案", - "This request isn't in the agent's session files: they may be deleted, moved, or not written yet": "Agent 會話檔案中沒有此請求:檔案可能已刪除、移走或尚未寫入", - "The session file couldn't be read": "會話檔案讀取失敗", "Cache hit rate": "快取命中率", "Metrics": "指標", "Usage trend": "使用趨勢", @@ -6242,23 +6024,15 @@ const I18N = { "10 s": "10 秒", "30 s": "30 秒", "1 min": "1 分鐘", - "Refresh every": "重新整理週期", "Refresh now": "立即重新整理", "Refresh this card": "重新整理這張卡片", "Read this card again": "只重新整理這張卡片的用量,其他卡片不動", "Read this card again, by running Claude Code's own /usage": "只重新整理這張卡片的用量(執行 Claude Code 自己的 /usage),其他卡片不動", - "Updated {time}": "更新於 {time}", - "Model recorded in the local session log; the outbound HTTP request was not captured.": "本地會話日誌記錄的模型;未採集實際發出的 HTTP 請求。", - "About: told from the session file's times, a little more or less than it took": "估算值:按會話檔案中的時間計算,與實際耗時略有出入", "Open Usage": "開啟用量", "No requests today": "今天還沒有請求", "No requests here": "這裡沒有請求", "Every request an agent sends to magpie, and every call the agents' own session files record, is counted here.": "統計 Agent 發給 magpie 的每個請求,以及 Agent 會話檔案記錄的每次呼叫。", "{n} unpriced": "{n} 個沒有價格", - "{n} call unpriced": "{n} 次呼叫未計價", - "{n} calls unpriced": "{n} 次呼叫未計價", - "{n} model unpriced": "{n} 個模型未計價", - "{n} models unpriced": "{n} 個模型未計價", "of the prompt": "佔提示詞", "Provider": "供應商", "All providers": "全部供應商", @@ -6268,34 +6042,14 @@ const I18N = { "none failed": "沒有失敗", "{n} answered on a retry": "{n} 次重試後成功", "Retried": "重試後成功", - "Show only the requests answered on a retry": "只看重試後成功的請求", - "Show only the failed requests": "只看失敗的請求", "handed on": "已轉交", - "This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "這次嘗試失敗,請求已轉交給下一個:請求依最終結果計數,不算這次嘗試", - "{p} succeeded": "成功 {p}", - "{a} cache": "快取 {a}", "The share of the prompt read from the cache": "提示詞中從快取讀取的比例", "Newer": "較新", "Older": "較早", - "{a}–{b} of {n}": "第 {a}–{b} 條,共 {n} 條", - "Each request's tokens as its provider reported them; the cost estimated using effective model prices, including custom prices. Export CSV saves every page.": "每個請求的 token 數取自供應商報告,費用按模型生效價格(含自定義價格)估算。匯出 CSV 包含所有頁。", - "Saved {n} request to {path}": "已將 {n} 個請求儲存到 {path}", - "Saved {n} requests to {path}": "已將 {n} 個請求儲存到 {path}", "Overview": "概覽", "Local session": "本地會話", - "Login method": "登入方式", - "Official login": "官方登入", - "Duration colors: ≤10 s green · 10–30 s amber · >30 s red": "耗時顏色:≤10 秒綠色 · 10–30 秒黃色 · >30 秒紅色", - "Official login confirmed for this account by local login metadata. This does not establish the route or authentication used for this request.": "本地登入資料確認此帳號採用官方登入;不代表已確認這次請求的渠道或認證方式。", "Subscription": "訂閱帳號", - "API price reference": "API 估價參考模型", - "Price reference: {model}": "估價參考:{model}", - "Model used for the API price estimate; this is not an observed model forwarding event.": "用於 API 費用估算的參考模型;並非實際觀測到的模型轉發記錄。", - "Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred.": "讀自 Agent 的會話檔案;僅在本地後設資料能夠明確識別時顯示帳號,不推斷供應商。", - "Read from the agent's session file, which names the provider it was set up to call. The name shown is that record, not a route magpie saw.": "讀自 Agent 的會話檔案,其中記錄了它被設定去呼叫的供應商。此處顯示的就是那條記錄,不是 magpie 看到的路由。", "Recorded provider ID": "日誌中的供應商標識", - "Session account": "會話帳號", - "Gateway calls only; session-log calls are in Requests. Local rejections are excluded from totals.": "僅統計閘道呼叫;會話日誌呼叫請檢視「請求」。本地拒絕的請求不計入彙總。", "Gateway and session-log calls; local rejections excluded from totals.": "統計閘道呼叫與會話日誌呼叫;本地拒絕的請求不計入彙總。", "Sessions": "會話", "Search sessions": "搜尋會話", @@ -6328,31 +6082,15 @@ const I18N = { "{n} folder": "{n} 個資料夾", "{n} folders": "{n} 個資料夾", "cost": "費用", - "at effective prices": "按生效價格", "just now": "剛剛", "No session matches.": "沒有匹配的會話。", "No sessions yet. Claude Code's, Codex's, Hermes, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.": "還沒有會話。本機 Claude Code、Codex、Hermes、OpenCode 和 Pi 的會話會顯示在這裡,附費用和繼續會話的命令。", - "Reading the agents' session files…": "正在讀取 Agent 的會話檔案…", "Totals count every session in the agents' own files; the list is the latest {n} by activity · {dirs}": "合計含 Agent 檔案中的全部會話;列表為最近活動的 {n} 個 · {dirs}", - "Totals count native sessions and gateway requests with a session ID": "合計含本機會話和帶有會話 ID 的閘道請求", - "showing {drawn} of {n}": "顯示 {n} 箇中的 {drawn} 個", "90 days": "90 天", - "All folders": "全部資料夾", "Search {n}…": "搜尋 {n} 項…", "No match": "沒有匹配項", - "Indexing your sessions": "正在為你的會話建立索引", - "Looking for session files…": "正在查詢會話檔案…", - "Reading the kept index…": "正在讀取已建好的索引…", - "Indexed · putting the page together…": "索引完成 · 正在生成頁面…", - "{done} of {files} files · {read} of {bytes}": "{done} / {files} 個檔案 · {read} / {bytes}", - "about {t} left": "約剩 {t}", "{n}s": "{n} 秒", - "Read once, kept: after this the page opens from the index in a blink": "只需索引一次:之後開啟這一頁幾乎是瞬間的", - "Only what changed is read again, from where it was left": "之後只讀新增的部分,從上次讀到的地方接著讀", - "Every session is read on this computer; nothing leaves it": "所有會話都在本機讀取,不會上傳到任何地方", - "The biggest files go first, so none is left running on alone": "最大的檔案先讀,所有核心一起跑滿", "{n} more — type to narrow": "還有 {n} 項 — 輸入以篩選", - "Nothing in this range.": "這段時間沒有用量。", "active": "活躍時長", "not kept by model": "不按模型統計", "Active": "活躍", @@ -6361,68 +6099,25 @@ const I18N = { "Activity": "活躍度", "nothing": "無", "Less": "少", - "Usage heatmap": "用量熱力圖", - "Daily usage over the last 53 weeks": "最近 53 週的每日用量", "No requests": "無請求", "More": "多", "{n} session": "{n} 個會話", "{n} sessions": "{n} 個會話", "{n} day": "{n} 天", "{n} days": "{n} 天", - "{d} active": "活躍 {d}", - "Latest sessions": "最近的會話", "All sessions": "全部會話", - "Open in Sessions": "在會話頁開啟", - "Top sessions": "最耗會話", "Output tokens": "輸出 Token", "Messages": "訊息", "{n} message": "{n} 條訊息", "{n} messages": "{n} 條訊息", - "Session shape": "會話形態", "Length": "時長", "Tool calls": "工具呼叫", - "{r}m": "{r} 分鐘", - "{r} messages": "{r} 條訊息", - "{r} minutes at work": "工作 {r} 分鐘", - "{r} tool calls a prompt": "每條提示 {r} 次工具呼叫", - "Across: {axis} · Height: sessions": "橫軸:{axis} · 柱高:會話數", - "messages in a session, prompts and replies": "一個會話裡的訊息數(提示加回覆)", - "minutes a session was at work": "一個會話實際工作的分鐘數", - "tool calls the agent made on its own for each prompt": "你每發一條提示,Agent 自己呼叫工具的次數", "Tool use": "Tool 使用", - "No tool calls in this range.": "這段時間沒有工具呼叫。", "Other": "其他", - "Top skills": "常用 Skills", - "No skill was called up in this range.": "這段時間沒有呼叫 skill。", - "last {when}": "最近 {when}", - "By hour": "按時段", - "Still counting": "還在統計", - "days at work": "活躍天數", - "longest streak": "最長連續", - "busiest day": "最忙的一天", "+{n} more": "還有 {n} 個", - "Reading the session…": "正在讀取會話…", - "Click to show only this": "點選只看這一項", - "Click again to show every one": "再點一次顯示全部", - "median {m} · p90 {p}": "中位 {m} · p90 {p}", - "{p} in {name}": "{name} 佔 {p}", - "Busiest at {when}": "最忙:{when}", - "Active time isn't kept by model.": "活躍時長不按模型統計。", - "No active time in this range.": "這段時間沒有活躍時長。", - "Tokens in and out per session: the middle session's, and what nine in ten stay under": "每個會話的輸入加輸出 token:中位數,以及九成會話不超過的量", - "on {n} day": "共 {n} 天", - "on {n} days": "共 {n} 天", - "The time the sessions were at work: the pauses between one message and the next, each under five minutes": "會話實際工作的時間:相鄰兩條訊息之間的間隔,只計不到五分鐘的", "<1m": "<1 分鐘", - "{m}m": "{m} 分鐘", - "{h}h {m}m": "{h} 小時 {m} 分", - "By day": "每日趨勢", - "By week": "每週趨勢", "Tokens": "Token", "Cost": "費用", - "{when} · {tokens} tokens": "{when} · {tokens} token", - "No known price for {models}": "{models} 沒有已知價格", - "Not counted: {models}, with no known price": "未計入:{models},沒有已知價格", "a model with no name": "未註明名稱的模型", "{n} session used a model with no known price; its share is not counted": "{n} 個會話用了沒有已知價格的模型,這部分未計入", "{n} sessions used a model with no known price; their share is not counted": "{n} 個會話用了沒有已知價格的模型,這部分未計入", @@ -6536,11 +6231,6 @@ const I18N = { "Chat requests": "聊天請求", "Completions": "程式碼補全", "Premium requests": "高階請求", - "No calls today.": "今天沒有呼叫。", - "No calls in the last 7 days.": "最近 7 天沒有呼叫。", - "No calls in the last 30 days.": "最近 30 天沒有呼叫。", - "No calls yet.": "還沒有呼叫。", - "Point an agent at a catalog model and use it; every call through the gateway is counted here.": "讓某個 Agent 使用目錄中的模型;每次經過閘道的呼叫都會計入這裡。", "tokens": "token", "{a} in · {b} out": "輸入 {a} · 輸出 {b}", "cache read": "快取讀取", @@ -6549,21 +6239,16 @@ const I18N = { "reasoning": "推理", "agent": "Agent", "member": "成員", - "inside output": "計入輸出", "call": "次呼叫", "calls": "次呼叫", "{n} failed": "{n} 次失敗", "{n} looped": "{n} 次陷入迴圈", "Replies magpie ended because the model kept repeating itself": "magpie 因模型一直重複自己而中止的回覆", "week of {label}": "{label} 起的一週", - "{when} · {tokens} tokens · {n} call": "{when} · {tokens} token · {n} 次呼叫", - "{when} · {tokens} tokens · {n} calls": "{when} · {tokens} token · {n} 次呼叫", "{when} · nothing": "{when} · 無", "{n} call": "{n} 次呼叫", "{n} calls": "{n} 次呼叫", - "{n}% of tokens": "佔 token 的 {n}%", "{n} cached": "快取 {n}", - "Counted from the providers' own usage reports on every call through the gateway · {path}": "根據供應商在每次閘道呼叫中返回的用量統計 · {path}", "Model lists refreshed": "模型列表已重新整理", "Sync failed: {e}": "同步失敗:{e}", "Preferences": "偏好", @@ -6740,17 +6425,8 @@ const I18N = { "This key is set to {api} only, but {name} has no {api} URL, so no request reaches {api} with it. Fill in the {api} URL, or set the key to Any protocol.": "這個 key 只用於 {api},但 {name} 沒有填 {api} 位址,所以用這個 key 的請求到不了 {api}。請填上 {api} 位址,或把 key 改回「任意協議」。", "any API": "任意 API", "models agents pick as one": "Agent 當作一個模型來選", - "Hide from this list": "從列表中隱藏", - "Count as an agent…": "計入某個 Agent…", - "Count {client} on its own": "將 {client} 單獨計算", - "with {clients}": "含 {clients}", - "Count this client's calls as": "將此用戶端的呼叫計入", - "{client} is counted as {agent}": "{client} 已計入 {agent}", - "{client} is counted on its own": "{client} 已單獨計算", "Client": "用戶端", - "Actions for {name}": "{name} 的操作", "Unhide": "取消隱藏", - "Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "只是不在此列表中顯示,它們的呼叫仍計入總數和圖表。點按查看。", "found by magpie": "magpie 自動發現", "no member ready": "沒有可用成員", "Manual": "手動", @@ -6775,10 +6451,6 @@ const I18N = { "min": "分鐘", "slow to start": "遲遲未開始", "In magpie": "magpie 內耗時", - "Vendor's first token": "廠商首字等待", - "Tries that failed first": "之前失敗的嘗試", - "Waiting for a slot": "排隊等空位", - "Connecting and sending": "連線並傳送請求", "One rate limited while it still has quota rests as long as the vendor asks, then takes its place in the order again.": "仍有額度卻被限流的帳號按廠商要求休息,之後回到原位繼續使用。", "One rate limited (429) while it still has quota goes to the back of the order, behind every one not rate limited since, and comes round again once those ahead of it are rate limited in turn — so the load goes round rather than back to the first each time. Out of quota, it rests as usual. Kept until magpie restarts.": "仍有額度卻被限流(429)的帳號排到最後,位於此後所有未被限流的帳號之後;前面的帳號依次被限流後才再輪到它,負載因此輪轉,而非每次回到第一個。額度用完的照常休息。此順序保留到 magpie 重啟。", "Rules": "規則", @@ -6857,7 +6529,6 @@ const I18N = { "A conversation stays put within a turn, while the agent sends tool results back; when you speak again, routing decides afresh.": "一輪之內(Agent 回傳工具結果時)不換;你再次發言時,路由重新決定。", "Every request is routed afresh, whoever answered its conversation before.": "每個請求都重新路由,不論之前由誰回答。", "Mask the accounts on this page — email addresses and account names — for a screenshot to share": "給本頁的帳號(郵箱位址和帳號名)打碼,方便截圖分享", - "Refresh now, the allowances too; a Claude account's is read by running Claude Code's own /usage": "立即重新整理,含額度;Claude 帳號的額度透過執行 Claude Code 自帶的 /usage 讀取", "Least used": "最少使用", "requests": "請求", "request": "請求", @@ -6920,7 +6591,6 @@ const I18N = { "Image description": "圖片描述", "Routing classifier": "路由分類器", "magpie's own": "magpie 自身", - "{n} by magpie itself": "其中 {n} 次由 magpie 自身發出", "{n} request in this period was magpie's own": "此期間有 {n} 個請求是 magpie 自身發出的", "{n} requests in this period were magpie's own": "此期間有 {n} 個請求是 magpie 自身發出的", "Requests magpie made by itself, not an agent: a routing group's classifier, a web search or an image description. They count against the key or account like any other request.": "magpie 自身發出的請求,而非代理發出的:路由群組的分類器、網頁搜尋或圖片描述。它們與其他請求一樣計入金鑰或帳號的用量。", @@ -6990,22 +6660,11 @@ const I18N = { "TTFT {ms}": "首字 {ms}", "Speed": "速度", "Output speed": "輸出速度", - "first token in {ms} on average": "首字平均 {ms}", - "no streamed replies timed": "沒有可計時的流式回覆", "Output tokens a second after the first, over the streamed replies": "流式回覆從首響起每秒輸出的 token 數", "No streamed replies timed in this period": "這段時間沒有可計時的流式回覆", - "Sent, Effort and the cache are in each row's details": "視窗較窄:傳送模型、推理強度和快取在每行的詳情裡", - "{n} output tokens in {ms} after the first": "首字後 {ms} 輸出 {n} 個 token", - "At least: {n} output tokens in {ms}, from the line that asked for it to its last. The session file has no first token, so the wait for it is counted too": "下限:從發出請求的那一行到最後一行,{ms} 輸出 {n} 個 token。會話檔案沒有首字時間,等首字的時間也算在裡面", - "At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too": "下限:首字後 {ms} 輸出 {n} 個正文 token,{r} 個推理 token 不計。會話檔案沒有首個正文的時間,首字後的推理時間也算在裡面", - "At least: {n} output tokens in {ms}, the whole turn. What came after the first token ({after}) is too little to time a speed by: under a second or under 100 tokens, so the wait for it is counted too": "下限:整輪 {ms} 輸出 {n} 個 token。首字後只有 {after},不足 1 秒或不足 100 個 token,測不出速度,等首字的時間也算在裡面", - "The session file has no first token to time a speed from": "會話檔案沒有首字時間,算不出速度", "A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "有推理的回覆只算正文部分,從首個正文起計:推理在流裡出現前就已寫完", "No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "沒有正文時,僅在可見推理持續串流輸出時將其計入速度;隱藏推理不顯示速度", - "{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "首個正文後 {ms} 輸出 {n} 個正文 token,之前的 {r} 個推理 token 不計", - "Not streamed: no first token to time a speed from": "非流式:沒有首字時間,算不出速度", "Cache": "快取", - "{i} in · {o} out · {r} cache read · {w} cache creation": "輸入 {i} · 輸出 {o} · 快取讀取 {r} · 快取建立 {w}", "first token in {ms}": "{ms} 後首響", "{n} tok/s": "{n} token/秒", "{k} timed reply": "{k} 次計時", @@ -7019,11 +6678,8 @@ const I18N = { "Measured on {k} replies, from their first token to their end": "實測 {k} 次回覆:從首字到結束", "At least: {k} reply read from a session file, which doesn't say when its answer began, so time before that is counted too": "下限:{k} 次讀自會話檔案的回覆。會話檔案不記錄正文何時開始,之前的時間也算在裡面", "At least: {k} replies read from session files, which don't say when their answers began, so time before that is counted too": "下限:{k} 次讀自會話檔案的回覆。會話檔案不記錄正文何時開始,之前的時間也算在裡面", - "Upstream provider": "上游", "Protocol": "協議", "Upstream stop reason": "上游結束原因", - "The agent spoke {from}; sent upstream as {to}": "agent 用 {from} 協議請求;以 {to} 協議發往上游", - "Sent upstream as {to}, as the agent spoke it": "以 {to} 協議發往上游,與 agent 所用協議相同", "Open Routing": "開啟路由", "{n} min": "{n} 分鐘", "{n} h": "{n} 小時", @@ -7468,16 +7124,6 @@ const I18N = { "This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.": "このリクエストの本文はもう保持されていません。magpie は直近 {n} 件のリクエストの本文を、実行中にメモリ内だけで保持します。", "As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.": "magpie が送信したとおりの内容です(マスキングが有効ならマスク済み)。直近 {n} 件のリクエストだけをメモリ内に保持します。", "All of {part} · {n}": "{part}をすべて · {n}", - "Yesterday": "昨日", - "This month": "今月", - "Last month": "先月", - "Pick days": "日付を選ぶ", - "Previous month": "前の月", - "Next month": "次の月", - "Days picked: {days}": "選んだ日付:{days}", - "Now the last day": "次に最終日を選択", - "Pick the first day, then the last": "最初の日、次に最終日を選択", - "No calls on the days picked.": "選んだ日付の呼び出しはありません。", "{n} on {date}": "{date} {n}", "roles": "ロール", "plan": "プラン", @@ -7789,8 +7435,6 @@ const I18N = { "The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.": "{name} が使ったトークンと費用を一緒に 0 に戻し、今から新しい {n} 日の周期を始めます。", "The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets {when}.": "{name} が使ったトークンと費用を一緒に 0 に戻します。この期間のこれまでの呼び出しは数えなくなり、リセットは引き続き {when} です。", "Usage reset for {name}": "{name} の使用量をリセットしました", - "All gateway keys": "すべてのゲートウェイキー", - "All accounts": "すべてのアカウント", "account not recorded": "アカウント未記録", "Use a gateway key to track usage": "ゲートウェイキーで使用量を記録", "Choose a gateway key to use as {env}; usage is tracked by key.": "{env} に使うゲートウェイキーを選んでください。使用量はキーごとに記録されます。", @@ -8151,6 +7795,7 @@ const I18N = { "Parts of magpie not everyone needs. Switched off, a part leaves the sidebar, its pages and Settings; magpie works the same either way.": "誰もが使うわけではない部分です。オフにすると、サイドバー、各ページ、設定から消えます。magpie の動作は変わりません。", "Your agents' past conversations: read, search, resume and export them": "エージェントの過去の会話:閲覧、検索、再開、書き出し", "Each request as the gateway routes it, the accounts it weighed and what each answered, and your routing groups": "ゲートウェイが各リクエストをどうルーティングしたか、比べたアカウントとそれぞれの応答、そしてルーティンググループ", + "Your allowances, what was spent and on what, each request, and what filled the context window": "利用枠、使った額とその内訳、各リクエスト、そしてコンテキストウィンドウの中身", "Recording gateway conversations": "ゲートウェイの会話を記録中", "Instructions, MCP servers, skills and hooks, kept once and given to every agent": "指示、MCP サーバー、スキル、フックを一か所で管理し、すべてのエージェントに渡します", "1 item given to agents": "1 件をエージェントに渡しています", @@ -9681,8 +9326,6 @@ const I18N = { "All computers": "すべてのコンピューター", "Other computers": "他のコンピューター", "Computer": "コンピューター", - "{agent} · on {computer}": "{agent} · {computer} 上", - "What was said stays on {computer}: sync shares the usage alone.": "会話内容は {computer} に残ります。同期で共有されるのは使用量だけです。", "Address": "アドレス", "User": "ユーザー", "Password": "パスワード", @@ -9758,7 +9401,6 @@ const I18N = { "Key": "キー", "{env}=magpie. The gateway trusts everything on loopback, so any value works.": "{env}=magpie。ゲートウェイはループバック上のすべてを信頼するため、どんな値でも動作します。", "Model": "モデル", - "Model · provider": "モデル · プロバイダ", "Model id": "モデル ID", "Model ids": "モデル ID", "provider/model, as listed below. Click a model there to put it in the snippets.": "下の一覧にある provider/model の形式です。モデルをクリックするとスニペットに入ります。", @@ -9812,7 +9454,6 @@ const I18N = { "This archive is {size}, too large to show here. Download it to read it.": "このアーカイブは {size} あり、大きすぎてここには表示できません。ダウンロードして読んでください。", "very large": "非常に大きい", "first {n} of {size}": "{size} 中の最初の {n}", - "Not archived": "アーカイブなし", "Reply": "返信", "Events": "イベント", "Raw": "Raw", @@ -9851,11 +9492,7 @@ const I18N = { "A heavier model fills a window sooner: this holds for the models used so far": "重いモデルほど枠を早く使い切ります。この値はこれまで使ったモデルでの目安です", "{n} call had no known price and is not counted": "{n} 件の呼び出しは価格が不明のため計上されていません", "{n} calls had no known price and are not counted": "{n} 件の呼び出しは価格が不明のため計上されていません", - "Estimated using effective model prices, including custom prices": "カスタム価格を含む、モデルの適用価格で見積もり", - "Search models, providers, sessions": "モデル、プロバイダ、セッションを検索", "Export CSV": "CSV をエクスポート", - "Save every request listed, all pages, as a CSV file in Downloads": "一覧のリクエストを全ページ分、CSV ファイルとして「ダウンロード」フォルダに保存", - "All agents": "すべてのエージェント", "All purposes": "すべての用途", "Purpose": "用途", "Filter the request list by purpose": "リクエスト一覧を用途で絞り込む", @@ -9864,24 +9501,13 @@ const I18N = { "{n} request": "{n} 件のリクエスト", "{n} requests": "{n} 件のリクエスト", "{n} in": "入力 {n}", - "{n} out": "出力 {n}", - "{n} cache write": "キャッシュ書き込み {n}", - "{n} cache read": "キャッシュ読み取り {n}", "through magpie": "magpie 経由", "not through magpie": "magpie を経由しない", - "reported by apps": "アプリからの報告", "Reported": "報告", - "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "リクエストを送ったアプリが POST /v1/magpie/usage/requests で報告したものです。このリクエストは magpie を経由せず、直接ベンダーに送られました。", - "all requests": "すべてのリクエスト", - "Show only these requests": "これらのリクエストだけを表示", - "Show every request again": "すべてのリクエストを再表示", - "View routing": "ルーティングを表示", "Clear filter": "フィルタをクリア", - "Request: {what}": "リクエスト:{what}", "No requests match these filters.": "これらのフィルタに一致するリクエストはありません。", "Time": "時刻", "Requested": "リクエストしたモデル", - "Provider · account": "プロバイダ · アカウント", "Sent": "送信したモデル", "Served": "応答したモデル", "In": "入力", @@ -9894,27 +9520,16 @@ const I18N = { "Long-context price, over": "長コンテキスト価格、超過", "Long-context price": "長コンテキスト価格", "A long-context price starts over a number of input tokens, like 272K": "長コンテキスト価格には、何トークンを超えたら適用するかを書いてください(例:272K)", - "{m} for 5 minutes, {h} for an hour": "{m} は 5 分間、{h} は 1 時間保持", "Cache read": "キャッシュ読み取り", "Duration": "所要時間", "Status": "ステータス", - "session {id}": "セッション {id}", - "{agent} · via {host}": "{agent} · {host} 経由", - "Not kept for requests before this version": "このバージョンより前のリクエストでは記録されていません", - "{n} reasoning, inside output": "推論 {n}(出力に含む)", - "No known price for this model": "このモデルの価格は不明です", - "Failed: the agent was answered {status}": "失敗:エージェントには {status} が返されました", "Succeeded": "成功", "Request ID": "リクエスト ID", "Error": "エラー", - "Error type": "エラーの種類", - "Upstream said": "上流の応答", "First token": "最初のトークン", "Reasoning tokens": "推論トークン", "Called for": "用途", - "Data source": "データソース", "Session ID": "セッション ID", - "Nothing more was kept of this request": "このリクエストについてこれ以上の記録はありません", "Input": "入力", "Output": "出力", "You": "あなた", @@ -9930,15 +9545,10 @@ const I18N = { "Image": "画像", "Show full content": "すべて表示", "Collapse content": "折りたたむ", - "OFFICIAL": "公式", "Nothing was said here": "ここには何もありません", "There was more than is shown here": "ここに表示しきれない内容があります", "… {n} more characters not shown": "… ほか {n} 文字は表示されていません", "Read from the agent's session file; magpie keeps no copy": "エージェントのセッションファイルから読み取り。magpie はコピーを保存しません", - "No session was named with this request, so its session file can't be found": "このリクエストにはセッションが指定されていないため、セッションファイルが見つかりません", - "magpie reads the session files of Claude Code, Claude Desktop and Codex only": "magpie が読み取れるのは Claude Code、Claude Desktop、Codex のセッションファイルのみです", - "This request isn't in the agent's session files: they may be deleted, moved, or not written yet": "このリクエストはエージェントのセッションファイルにありません。削除・移動されたか、まだ書き込まれていない可能性があります", - "The session file couldn't be read": "セッションファイルを読み取れませんでした", "Cache hit rate": "キャッシュヒット率", "Metrics": "指標", "Usage trend": "使用量の推移", @@ -9947,23 +9557,15 @@ const I18N = { "10 s": "10 秒", "30 s": "30 秒", "1 min": "1 分", - "Refresh every": "更新間隔", "Refresh now": "今すぐ更新", "Refresh this card": "このカードを更新", "Read this card again": "このカードの使用量だけを読み直します(ほかのカードはそのまま)", "Read this card again, by running Claude Code's own /usage": "このカードの使用量だけを読み直します(Claude Code 自身の /usage を実行。ほかのカードはそのまま)", - "Updated {time}": "{time} に更新", - "Model recorded in the local session log; the outbound HTTP request was not captured.": "ローカルのセッションログに記録されたモデルです。実際に送信された HTTP リクエストは取得していません。", - "About: told from the session file's times, a little more or less than it took": "概算:セッションファイルの時刻から算出しており、実際の所要時間とは多少ずれます", "Open Usage": "使用量を開く", "No requests today": "今日のリクエストはまだありません", "No requests here": "ここにはリクエストがありません", "Every request an agent sends to magpie, and every call the agents' own session files record, is counted here.": "エージェントが magpie に送ったすべてのリクエストと、エージェント自身のセッションファイルに記録されたすべての呼び出しがここに集計されます。", "{n} unpriced": "{n} 件は価格不明", - "{n} call unpriced": "{n} 件の呼び出しは価格不明", - "{n} calls unpriced": "{n} 件の呼び出しは価格不明", - "{n} model unpriced": "{n} 個のモデルは価格不明", - "{n} models unpriced": "{n} 個のモデルは価格不明", "of the prompt": "プロンプトのうち", "Provider": "プロバイダ", "All providers": "すべてのプロバイダ", @@ -9973,34 +9575,14 @@ const I18N = { "none failed": "失敗なし", "{n} answered on a retry": "{n} 件が再試行で成功", "Retried": "再試行で成功", - "Show only the requests answered on a retry": "再試行で成功したリクエストだけを表示", - "Show only the failed requests": "失敗したリクエストだけを表示", "handed on": "引き継ぎ", - "This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "この試行は失敗し、リクエストは次へ引き継がれました。リクエストはこの試行ではなく最終結果で数えます", - "{p} succeeded": "成功 {p}", - "{a} cache": "キャッシュ {a}", "The share of the prompt read from the cache": "プロンプトのうちキャッシュから読み取られた割合", "Newer": "新しい", "Older": "古い", - "{a}–{b} of {n}": "{n} 件中 {a}–{b}", - "Each request's tokens as its provider reported them; the cost estimated using effective model prices, including custom prices. Export CSV saves every page.": "各リクエストのトークン数はプロバイダの報告によるもので、費用はカスタム価格を含む有効なモデル価格で見積もっています。CSV エクスポートは全ページを保存します。", - "Saved {n} request to {path}": "{n} 件のリクエストを {path} に保存しました", - "Saved {n} requests to {path}": "{n} 件のリクエストを {path} に保存しました", "Overview": "概要", "Local session": "ローカルセッション", - "Login method": "ログイン方法", - "Official login": "公式ログイン", - "Duration colors: ≤10 s green · 10–30 s amber · >30 s red": "所要時間の色:≤10 秒 緑 · 10–30 秒 黄 · >30 秒 赤", - "Official login confirmed for this account by local login metadata. This does not establish the route or authentication used for this request.": "ローカルのログイン情報により、このアカウントは公式ログインであることが確認されています。このリクエストの経路や認証方式を確認するものではありません。", "Subscription": "サブスクリプション", - "API price reference": "API 価格の参考モデル", - "Price reference: {model}": "価格の参考:{model}", - "Model used for the API price estimate; this is not an observed model forwarding event.": "API 費用の見積もりに使った参考モデルです。実際に観測されたモデル転送ではありません。", - "Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred.": "エージェントのセッションファイルから読み取り。アカウントはローカルのメタデータで特定できる場合のみ表示し、プロバイダは推測しません。", - "Read from the agent's session file, which names the provider it was set up to call. The name shown is that record, not a route magpie saw.": "エージェントのセッションファイルから読み取り。呼び出すよう設定されたプロバイダが記録されています。ここに表示されるのはその記録であり、magpie が確認したルートではありません。", "Recorded provider ID": "記録されたプロバイダ ID", - "Session account": "セッションのアカウント", - "Gateway calls only; session-log calls are in Requests. Local rejections are excluded from totals.": "ゲートウェイ経由の呼び出しのみ。セッションログの呼び出しは「リクエスト」にあります。ローカルで拒否されたものは合計に含みません。", "Gateway and session-log calls; local rejections excluded from totals.": "ゲートウェイとセッションログの呼び出し。ローカルで拒否されたものは合計に含みません。", "Sessions": "セッション", "Search sessions": "セッションを検索", @@ -10033,31 +9615,15 @@ const I18N = { "{n} folder": "{n} 個のフォルダ", "{n} folders": "{n} 個のフォルダ", "cost": "費用", - "at effective prices": "有効な価格で", "just now": "たった今", "No session matches.": "一致するセッションはありません。", "No sessions yet. Claude Code's, Codex's, Hermes, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.": "セッションはまだありません。このコンピュータ上の Claude Code、Codex、Hermes、OpenCode、Pi のセッションが、それぞれの費用と再開コマンドとともにここに表示されます。", - "Reading the agents' session files…": "エージェントのセッションファイルを読み取り中…", "Totals count every session in the agents' own files; the list is the latest {n} by activity · {dirs}": "合計はエージェント自身のファイルにあるすべてのセッションを集計しています。一覧は最近のアクティビティ順で {n} 件 · {dirs}", - "Totals count native sessions and gateway requests with a session ID": "合計にはローカルのセッションとセッション ID のあるゲートウェイ要求が含まれます", - "showing {drawn} of {n}": "{n} 件中 {drawn} 件を表示", "90 days": "90 日", - "All folders": "すべてのフォルダ", "Search {n}…": "{n} 件を検索…", "No match": "一致なし", - "Indexing your sessions": "セッションのインデックスを作成中", - "Looking for session files…": "セッションファイルを探しています…", - "Reading the kept index…": "保存済みのインデックスを読み取り中…", - "Indexed · putting the page together…": "インデックス作成完了 · ページを準備しています…", - "{done} of {files} files · {read} of {bytes}": "{done} / {files} ファイル · {read} / {bytes}", - "about {t} left": "残り約 {t}", "{n}s": "{n} 秒", - "Read once, kept: after this the page opens from the index in a blink": "一度読み取れば保存されます。次回からはインデックスから一瞬で開きます", - "Only what changed is read again, from where it was left": "次回からは変更された部分だけを、前回の続きから読み取ります", - "Every session is read on this computer; nothing leaves it": "すべてのセッションはこのコンピュータ上で読み取られ、外部には送信されません", - "The biggest files go first, so none is left running on alone": "大きいファイルから先に読むので、最後に 1 つだけ残って時間がかかることはありません", "{n} more — type to narrow": "ほか {n} 件 — 入力して絞り込み", - "Nothing in this range.": "この期間のデータはありません。", "active": "アクティブ時間", "not kept by model": "モデル別には記録されません", "Active": "アクティブ", @@ -10066,68 +9632,25 @@ const I18N = { "Activity": "アクティビティ", "nothing": "なし", "Less": "少", - "Usage heatmap": "使用量ヒートマップ", - "Daily usage over the last 53 weeks": "直近 53 週間の日ごとの使用量", "No requests": "リクエストなし", "More": "多", "{n} session": "{n} 件のセッション", "{n} sessions": "{n} 件のセッション", "{n} day": "{n} 日", "{n} days": "{n} 日", - "{d} active": "アクティブ {d}", - "Latest sessions": "最近のセッション", "All sessions": "すべてのセッション", - "Open in Sessions": "セッションで開く", - "Top sessions": "上位のセッション", "Output tokens": "出力トークン", "Messages": "メッセージ", "{n} message": "{n} 件のメッセージ", "{n} messages": "{n} 件のメッセージ", - "Session shape": "セッションの傾向", "Length": "長さ", "Tool calls": "ツール呼び出し", - "{r}m": "{r} 分", - "{r} messages": "{r} 件のメッセージ", - "{r} minutes at work": "作業時間 {r} 分", - "{r} tool calls a prompt": "プロンプトあたり {r} 回のツール呼び出し", - "Across: {axis} · Height: sessions": "横軸:{axis} · 高さ:セッション数", - "messages in a session, prompts and replies": "セッション内のメッセージ数(プロンプトと応答)", - "minutes a session was at work": "セッションが作業していた分数", - "tool calls the agent made on its own for each prompt": "プロンプト 1 つにつきエージェントが自ら行ったツール呼び出しの回数", "Tool use": "ツールの使用", - "No tool calls in this range.": "この期間のツール呼び出しはありません。", "Other": "その他", - "Top skills": "よく使うスキル", - "No skill was called up in this range.": "この期間に呼び出されたスキルはありません。", - "last {when}": "最終 {when}", - "By hour": "時間帯別", - "Still counting": "集計中", - "days at work": "作業日数", - "longest streak": "最長連続日数", - "busiest day": "最も忙しかった日", "+{n} more": "ほか {n} 件", - "Reading the session…": "セッションを読み取り中…", - "Click to show only this": "クリックでこれだけを表示", - "Click again to show every one": "もう一度クリックですべて表示", - "median {m} · p90 {p}": "中央値 {m} · p90 {p}", - "{p} in {name}": "{name} が {p}", - "Busiest at {when}": "最も忙しい時間:{when}", - "Active time isn't kept by model.": "アクティブ時間はモデル別には記録されません。", - "No active time in this range.": "この期間のアクティブ時間はありません。", - "Tokens in and out per session: the middle session's, and what nine in ten stay under": "セッションあたりの入出力トークン:中央値と、9 割のセッションが収まる量", - "on {n} day": "{n} 日間", - "on {n} days": "{n} 日間", - "The time the sessions were at work: the pauses between one message and the next, each under five minutes": "セッションが作業していた時間:メッセージ間の間隔のうち、5 分未満のものだけを合計", "<1m": "<1 分", - "{m}m": "{m} 分", - "{h}h {m}m": "{h} 時間 {m} 分", - "By day": "日別", - "By week": "週別", "Tokens": "トークン", "Cost": "費用", - "{when} · {tokens} tokens": "{when} · {tokens} トークン", - "No known price for {models}": "{models} の価格は不明です", - "Not counted: {models}, with no known price": "計上されていません:{models}(価格不明)", "a model with no name": "名前のないモデル", "{n} session used a model with no known price; its share is not counted": "{n} 件のセッションで価格不明のモデルが使われました。その分は計上されていません", "{n} sessions used a model with no known price; their share is not counted": "{n} 件のセッションで価格不明のモデルが使われました。その分は計上されていません", @@ -10241,11 +9764,6 @@ const I18N = { "Chat requests": "チャットリクエスト", "Completions": "補完", "Premium requests": "プレミアムリクエスト", - "No calls today.": "今日の呼び出しはありません。", - "No calls in the last 7 days.": "過去 7 日間の呼び出しはありません。", - "No calls in the last 30 days.": "過去 30 日間の呼び出しはありません。", - "No calls yet.": "呼び出しはまだありません。", - "Point an agent at a catalog model and use it; every call through the gateway is counted here.": "エージェントにカタログのモデルを指定して使うと、ゲートウェイ経由のすべての呼び出しがここに集計されます。", "tokens": "トークン", "{a} in · {b} out": "入力 {a} · 出力 {b}", "cache read": "キャッシュ読み取り", @@ -10254,21 +9772,16 @@ const I18N = { "reasoning": "推論", "agent": "エージェント", "member": "メンバー", - "inside output": "出力に含む", "call": "回の呼び出し", "calls": "回の呼び出し", "{n} failed": "{n} 件が失敗", "{n} looped": "{n} 件はループ", "Replies magpie ended because the model kept repeating itself": "モデルが同じことを繰り返し続けたため magpie が止めた応答", "week of {label}": "{label} の週", - "{when} · {tokens} tokens · {n} call": "{when} · {tokens} トークン · {n} 回の呼び出し", - "{when} · {tokens} tokens · {n} calls": "{when} · {tokens} トークン · {n} 回の呼び出し", "{when} · nothing": "{when} · なし", "{n} call": "{n} 回の呼び出し", "{n} calls": "{n} 回の呼び出し", - "{n}% of tokens": "トークンの {n}%", "{n} cached": "キャッシュ {n}", - "Counted from the providers' own usage reports on every call through the gateway · {path}": "ゲートウェイ経由の各呼び出しでプロバイダが返した使用量から集計 · {path}", "Model lists refreshed": "モデル一覧を更新しました", "Sync failed: {e}": "同期に失敗しました:{e}", "Preferences": "環境設定", @@ -10445,17 +9958,8 @@ const I18N = { "This key is set to {api} only, but {name} has no {api} URL, so no request reaches {api} with it. Fill in the {api} URL, or set the key to Any protocol.": "このキーは {api} 専用ですが、{name} には {api} の URL がないため、このキーでのリクエストは {api} に届きません。{api} の URL を入力するか、キーを「任意のプロトコル」に戻してください。", "any API": "任意の API", "models agents pick as one": "エージェントが 1 つとして選ぶモデル群", - "Hide from this list": "この一覧から隠す", - "Count as an agent…": "エージェントとして数える…", - "Count {client} on its own": "{client} を別に数える", - "with {clients}": "{clients} を含む", - "Count this client's calls as": "このクライアントの呼び出しを数える先", - "{client} is counted as {agent}": "{client} を {agent} として数えます", - "{client} is counted on its own": "{client} を別に数えます", "Client": "クライアント", - "Actions for {name}": "{name} の操作", "Unhide": "再表示", - "Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "この一覧に表示しないだけで、呼び出しは合計とグラフに含まれます。クリックで表示します。", "found by magpie": "magpie が自動作成", "no member ready": "準備できたメンバーがありません", "Manual": "手動", @@ -10480,10 +9984,6 @@ const I18N = { "min": "分", "slow to start": "応答開始が遅い", "In magpie": "magpie 内", - "Vendor's first token": "ベンダーの最初のトークン", - "Tries that failed first": "先に失敗した試行", - "Waiting for a slot": "空き枠待ち", - "Connecting and sending": "接続と送信", "One rate limited while it still has quota rests as long as the vendor asks, then takes its place in the order again.": "クォータが残っているのにレート制限されたものは、ベンダーの指示する時間だけ休止し、その後また順番内の位置に戻ります。", "One rate limited (429) while it still has quota goes to the back of the order, behind every one not rate limited since, and comes round again once those ahead of it are rate limited in turn — so the load goes round rather than back to the first each time. Out of quota, it rests as usual. Kept until magpie restarts.": "クォータが残っているのにレート制限(429)されたものは順番の最後尾に回り、それ以降レート制限されていないすべての後ろに並びます。前にあるものが順にレート制限されると再び回ってくるため、負荷は毎回先頭に戻るのではなく順に回ります。クォータ切れの場合は通常どおり休止します。magpie を再起動するまで保持されます。", "Rules": "ルール", @@ -10563,7 +10063,6 @@ const I18N = { "A conversation stays put within a turn, while the agent sends tool results back; when you speak again, routing decides afresh.": "ターン内(エージェントがツール結果を返している間)は移りません。次に発言したときに、ルーティングが改めて決めます。", "Every request is routed afresh, whoever answered its conversation before.": "各リクエストは、以前に誰が会話に応答したかにかかわらず、改めてルーティングされます。", "Mask the accounts on this page — email addresses and account names — for a screenshot to share": "スクリーンショットを共有できるよう、このページのアカウント(メールアドレスとアカウント名)を伏せます", - "Refresh now, the allowances too; a Claude account's is read by running Claude Code's own /usage": "今すぐ更新し、利用枠も読み込み直します。Claude アカウントの利用枠は Claude Code 自身の /usage を実行して読み取ります", "Least used": "使用量が最少", "requests": "リクエスト", "request": "リクエスト", @@ -10627,7 +10126,6 @@ const I18N = { "Image description": "画像の説明", "Routing classifier": "ルーティング分類器", "magpie's own": "magpie 自身", - "{n} by magpie itself": "うち {n} 件は magpie 自身", "{n} request in this period was magpie's own": "この期間のリクエストのうち {n} 件は magpie 自身のものです", "{n} requests in this period were magpie's own": "この期間のリクエストのうち {n} 件は magpie 自身のものです", "Requests magpie made by itself, not an agent: a routing group's classifier, a web search or an image description. They count against the key or account like any other request.": "エージェントではなく magpie 自身が送ったリクエストです:ルーティンググループの分類器、Web 検索、画像の説明。ほかのリクエストと同じくキーやアカウントの使用量に数えられます。", @@ -10694,22 +10192,11 @@ const I18N = { "TTFT {ms}": "TTFT {ms}", "Speed": "速度", "Output speed": "出力速度", - "first token in {ms} on average": "最初のトークンまで平均 {ms}", - "no streamed replies timed": "計測できたストリーミング応答なし", "Output tokens a second after the first, over the streamed replies": "ストリーミング応答で、最初のトークン以降に毎秒出力されたトークン数", "No streamed replies timed in this period": "この期間に計測できたストリーミング応答はありません", - "Sent, Effort and the cache are in each row's details": "ウィンドウが狭いため、送信したモデル・推論レベル・キャッシュは各行の詳細にあります", - "{n} output tokens in {ms} after the first": "最初のトークン後 {ms} で {n} トークンを出力", - "At least: {n} output tokens in {ms}, from the line that asked for it to its last. The session file has no first token, so the wait for it is counted too": "下限:要求した行から最後の行まで {ms} で {n} トークンを出力。セッションファイルには最初のトークンの時刻がないため、それを待つ時間も含まれます", - "At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too": "下限:最初のトークン後 {ms} で回答 {n} トークン(推論 {r} トークンは含めず)。セッションファイルには最初の本文の時刻がないため、最初のトークン後の推論の時間も含まれます", - "At least: {n} output tokens in {ms}, the whole turn. What came after the first token ({after}) is too little to time a speed by: under a second or under 100 tokens, so the wait for it is counted too": "下限:ターン全体の {ms} で {n} トークンを出力。最初のトークン後は {after} だけで、1 秒未満か 100 トークン未満のため速度を計れず、それを待つ時間も含まれます", - "The session file has no first token to time a speed from": "セッションファイルには、速度を計れる最初のトークンの時刻がありません", "A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "推論した応答は、最初の本文からの回答部分のみ数えます。推論はストリームに出る前に書き終わっています", "No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "本文がない場合、継続的にストリームされた可視の推論のみ速度に含めます。非表示の推論には速度を表示しません", - "{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "最初の本文後 {ms} で回答 {n} トークン(その前の推論 {r} トークンは含めず)", - "Not streamed: no first token to time a speed from": "ストリーミングではないため、速度を計れる最初のトークンの時刻がありません", "Cache": "キャッシュ", - "{i} in · {o} out · {r} cache read · {w} cache creation": "入力 {i} · 出力 {o} · キャッシュ読み取り {r} · キャッシュ作成 {w}", "first token in {ms}": "最初のトークンまで {ms}", "{n} tok/s": "{n} トークン/秒", "{k} timed reply": "計測 {k} 件", @@ -10723,11 +10210,8 @@ const I18N = { "Measured on {k} replies, from their first token to their end": "{k} 件の応答で実測:最初のトークンから終わりまで", "At least: {k} reply read from a session file, which doesn't say when its answer began, so time before that is counted too": "下限:セッションファイルから読んだ {k} 件の応答。回答が始まった時刻がないため、その前の時間も含まれます", "At least: {k} replies read from session files, which don't say when their answers began, so time before that is counted too": "下限:セッションファイルから読んだ {k} 件の応答。回答が始まった時刻がないため、その前の時間も含まれます", - "Upstream provider": "上流プロバイダー", "Protocol": "プロトコル", "Upstream stop reason": "上流の終了理由", - "The agent spoke {from}; sent upstream as {to}": "エージェントは {from} で要求し、上流へは {to} で送信", - "Sent upstream as {to}, as the agent spoke it": "エージェントと同じ {to} で上流へ送信", "Open Routing": "ルーティングを開く", "{n} min": "{n} 分", "{n} h": "{n} 時間", @@ -11171,16 +10655,6 @@ const I18N = { "This request's text is no longer kept: magpie keeps the text of the last {n} requests, in memory only, while it runs.": "Der Text dieser Anfrage wird nicht mehr aufbewahrt: magpie behält den Text der letzten {n} Anfragen nur im Arbeitsspeicher, solange es läuft.", "As magpie sent it, masked where masking is on. Kept in memory for the last {n} requests only.": "So, wie magpie es gesendet hat, maskiert, wo Maskierung an ist. Nur für die letzten {n} Anfragen im Arbeitsspeicher aufbewahrt.", "All of {part} · {n}": "Alle: {part} · {n}", - "Yesterday": "Gestern", - "This month": "Dieser Monat", - "Last month": "Letzter Monat", - "Pick days": "Tage wählen", - "Previous month": "Vorheriger Monat", - "Next month": "Nächster Monat", - "Days picked: {days}": "Gewählte Tage: {days}", - "Now the last day": "Jetzt den letzten Tag", - "Pick the first day, then the last": "Erst den ersten Tag, dann den letzten wählen", - "No calls on the days picked.": "An den gewählten Tagen keine Aufrufe.", "{n} on {date}": "{n} am {date}", "roles": "Rollen", "plan": "Planung", @@ -11492,8 +10966,6 @@ const I18N = { "The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.": "Die von {name} verbrauchten Token und Kosten gehen zusammen auf 0, und jetzt beginnt ein neuer Zyklus von {n} Tagen.", "The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets {when}.": "Die von {name} verbrauchten Token und Kosten gehen zusammen auf 0. Bisherige Aufrufe in diesem Zeitraum zählen nicht mehr; zurückgesetzt wird weiterhin {when}.", "Usage reset for {name}": "Nutzung von {name} zurückgesetzt", - "All gateway keys": "Alle Zugangsschlüssel", - "All accounts": "Alle Konten", "account not recorded": "Konto nicht erfasst", "Use a gateway key to track usage": "Zugangsschlüssel verwenden, um die Nutzung zu erfassen", "Choose a gateway key to use as {env}; usage is tracked by key.": "Zugangsschlüssel für {env} wählen; die Nutzung wird je Schlüssel erfasst.", @@ -11854,6 +11326,7 @@ const I18N = { "Parts of magpie not everyone needs. Switched off, a part leaves the sidebar, its pages and Settings; magpie works the same either way.": "Teile von magpie, die nicht jeder braucht. Ausgeschaltet verschwindet ein Teil aus der Seitenleiste, seinen Seiten und den Einstellungen; magpie arbeitet weiter wie bisher.", "Your agents' past conversations: read, search, resume and export them": "Die bisherigen Unterhaltungen deiner Agenten: lesen, suchen, fortsetzen und exportieren", "Each request as the gateway routes it, the accounts it weighed and what each answered, and your routing groups": "Jede Anfrage, wie das Gateway sie weiterleitet, die abgewogenen Konten und was jedes antwortete, und deine Routing-Gruppen", + "Your allowances, what was spent and on what, each request, and what filled the context window": "Deine Kontingente, was ausgegeben wurde und wofür, jede Anfrage und was das Kontextfenster gefüllt hat", "Recording gateway conversations": "Gateway-Unterhaltungen werden aufgezeichnet", "Instructions, MCP servers, skills and hooks, kept once and given to every agent": "Anweisungen, MCP-Server, Skills und Hooks, einmal gepflegt und an jeden Agenten gegeben", "1 item given to agents": "1 Eintrag an Agenten gegeben", @@ -13392,8 +12865,6 @@ const I18N = { "All computers": "Alle Computer", "Other computers": "Andere Computer", "Computer": "Computer", - "{agent} · on {computer}": "{agent} · auf {computer}", - "What was said stays on {computer}: sync shares the usage alone.": "Die Inhalte bleiben auf {computer}: Die Synchronisierung teilt nur die Nutzung.", "Address": "Adresse", "User": "Benutzer", "Password": "Passwort", @@ -13469,7 +12940,6 @@ const I18N = { "Key": "Schlüssel", "{env}=magpie. The gateway trusts everything on loopback, so any value works.": "{env}=magpie. Der Zugangspunkt vertraut allem über Loopback, daher funktioniert jeder Wert.", "Model": "Modell", - "Model · provider": "Modell · Anbieter", "Model id": "Modell-ID", "Model ids": "Modell-IDs", "provider/model, as listed below. Click a model there to put it in the snippets.": "provider/model, wie unten aufgeführt. Klicken Sie dort auf ein Modell, um es in die Snippets zu übernehmen.", @@ -13523,7 +12993,6 @@ const I18N = { "This archive is {size}, too large to show here. Download it to read it.": "Dieses Archiv ist {size} groß, zu groß für die Anzeige hier. Laden Sie es zum Lesen herunter.", "very large": "sehr groß", "first {n} of {size}": "erste {n} von {size}", - "Not archived": "Nicht archiviert", "Reply": "Antwort", "Events": "Ereignisse", "Raw": "Roh", @@ -13562,11 +13031,7 @@ const I18N = { "A heavier model fills a window sooner: this holds for the models used so far": "Ein schwereres Modell füllt ein Fenster schneller: der Wert gilt für die bisher genutzten Modelle", "{n} call had no known price and is not counted": "{n} Aufruf hatte keinen bekannten Preis und wird nicht gezählt", "{n} calls had no known price and are not counted": "{n} Aufrufe hatten keinen bekannten Preis und werden nicht gezählt", - "Estimated using effective model prices, including custom prices": "Geschätzt mit effektiven Modellpreisen, einschließlich eigener Preise", - "Search models, providers, sessions": "Modelle, Anbieter, Sitzungen durchsuchen", "Export CSV": "CSV exportieren", - "Save every request listed, all pages, as a CSV file in Downloads": "Alle aufgeführten Anfragen aller Seiten als CSV-Datei unter „Downloads“ speichern", - "All agents": "Alle Agenten", "All purposes": "Alle Zwecke", "Purpose": "Zweck", "Filter the request list by purpose": "Anfrageliste nach Zweck filtern", @@ -13575,24 +13040,13 @@ const I18N = { "{n} request": "{n} Anfrage", "{n} requests": "{n} Anfragen", "{n} in": "{n} ein", - "{n} out": "{n} aus", - "{n} cache write": "{n} Cache-Schreiben", - "{n} cache read": "{n} Cache-Lesen", "through magpie": "über magpie", "not through magpie": "nicht über magpie", - "reported by apps": "von Apps gemeldet", "Reported": "Gemeldet", - "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "Von der App gemeldet, die die Anfrage gestellt hat (POST /v1/magpie/usage/requests): Die Anfrage ging direkt an den Anbieter, nicht über magpie.", - "all requests": "alle Anfragen", - "Show only these requests": "Nur diese Anfragen zeigen", - "Show every request again": "Wieder alle Anfragen zeigen", - "View routing": "Weiterleitung anzeigen", "Clear filter": "Filter zurücksetzen", - "Request: {what}": "Anfrage: {what}", "No requests match these filters.": "Keine Anfragen entsprechen diesen Filtern.", "Time": "Zeit", "Requested": "Angefragt", - "Provider · account": "Anbieter · Konto", "Sent": "Gesendet", "Served": "Bereitgestellt", "In": "Ein", @@ -13605,27 +13059,16 @@ const I18N = { "Long-context price, over": "Preis für langen Kontext, über", "Long-context price": "Preis für langen Kontext", "A long-context price starts over a number of input tokens, like 272K": "Ein Preis für langen Kontext gilt ab einer Zahl von Eingabe-Tokens, etwa 272K", - "{m} for 5 minutes, {h} for an hour": "{m} für 5 Minuten, {h} für eine Stunde", "Cache read": "Cache-Lesen", "Duration": "Dauer", "Status": "Status", - "session {id}": "Sitzung {id}", - "{agent} · via {host}": "{agent} · über {host}", - "Not kept for requests before this version": "Für Anfragen vor dieser Version nicht gespeichert", - "{n} reasoning, inside output": "{n} Reasoning, in der Ausgabe enthalten", - "No known price for this model": "Kein bekannter Preis für dieses Modell", - "Failed: the agent was answered {status}": "Fehlgeschlagen: Der Agent erhielt {status}", "Succeeded": "Erfolgreich", "Request ID": "Anfrage-ID", "Error": "Fehler", - "Error type": "Fehlertyp", - "Upstream said": "Upstream-Antwort", "First token": "Erstes Token", "Reasoning tokens": "Reasoning-Token", "Called for": "Aufgerufen für", - "Data source": "Datenquelle", "Session ID": "Sitzungs-ID", - "Nothing more was kept of this request": "Zu dieser Anfrage wurde nichts weiter gespeichert", "Input": "Eingabe", "Output": "Ausgabe", "You": "Sie", @@ -13641,15 +13084,10 @@ const I18N = { "Image": "Bild", "Show full content": "Gesamten Inhalt anzeigen", "Collapse content": "Inhalt einklappen", - "OFFICIAL": "OFFIZIELL", "Nothing was said here": "Hier gibt es keinen Inhalt", "There was more than is shown here": "Es gab mehr, als hier angezeigt wird", "… {n} more characters not shown": "… {n} weitere Zeichen nicht angezeigt", "Read from the agent's session file; magpie keeps no copy": "Aus der Sitzungsdatei des Agenten gelesen; magpie behält keine Kopie", - "No session was named with this request, so its session file can't be found": "Diese Anfrage nannte keine Sitzung, daher lässt sich ihre Sitzungsdatei nicht finden", - "magpie reads the session files of Claude Code, Claude Desktop and Codex only": "magpie liest nur die Sitzungsdateien von Claude Code, Claude Desktop und Codex", - "This request isn't in the agent's session files: they may be deleted, moved, or not written yet": "Diese Anfrage ist nicht in den Sitzungsdateien des Agenten: Die Dateien wurden eventuell gelöscht, verschoben oder noch nicht geschrieben", - "The session file couldn't be read": "Die Sitzungsdatei konnte nicht gelesen werden", "Cache hit rate": "Cache-Trefferquote", "Metrics": "Kennzahlen", "Usage trend": "Nutzungsverlauf", @@ -13658,23 +13096,15 @@ const I18N = { "10 s": "10 s", "30 s": "30 s", "1 min": "1 Min.", - "Refresh every": "Aktualisieren alle", "Refresh now": "Jetzt aktualisieren", "Refresh this card": "Diese Karte aktualisieren", "Read this card again": "Nur diese Karte neu lesen, die anderen bleiben, wie sie sind", "Read this card again, by running Claude Code's own /usage": "Nur diese Karte neu lesen, mit Claude Codes eigenem /usage; die anderen bleiben, wie sie sind", - "Updated {time}": "Aktualisiert {time}", - "Model recorded in the local session log; the outbound HTTP request was not captured.": "Modell laut lokalem Sitzungslog; die ausgehende HTTP-Anfrage wurde nicht erfasst.", - "About: told from the session file's times, a little more or less than it took": "Ungefähr: aus den Zeiten der Sitzungsdatei ermittelt, etwas mehr oder weniger als die tatsächliche Dauer", "Open Usage": "Nutzung öffnen", "No requests today": "Heute keine Anfragen", "No requests here": "Hier keine Anfragen", "Every request an agent sends to magpie, and every call the agents' own session files record, is counted here.": "Jede Anfrage eines Agenten an magpie und jeder Aufruf aus den Sitzungsdateien der Agenten wird hier gezählt.", "{n} unpriced": "{n} ohne Preis", - "{n} call unpriced": "{n} Aufruf ohne Preis", - "{n} calls unpriced": "{n} Aufrufe ohne Preis", - "{n} model unpriced": "{n} Modell ohne Preis", - "{n} models unpriced": "{n} Modelle ohne Preis", "of the prompt": "des Prompts", "Provider": "Anbieter", "All providers": "Alle Anbieter", @@ -13684,34 +13114,14 @@ const I18N = { "none failed": "keine fehlgeschlagen", "{n} answered on a retry": "{n} nach erneutem Versuch beantwortet", "Retried": "Wiederholt", - "Show only the requests answered on a retry": "Nur die nach erneutem Versuch beantworteten Anfragen zeigen", - "Show only the failed requests": "Nur die fehlgeschlagenen Anfragen zeigen", "handed on": "weitergereicht", - "This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "Dieser Versuch schlug fehl, und die Anfrage ging an den nächsten weiter: Gezählt wird die Anfrage nach ihrem Ausgang, nicht nach diesem Versuch", - "{p} succeeded": "{p} erfolgreich", - "{a} cache": "{a} Cache", "The share of the prompt read from the cache": "Anteil des Prompts, der aus dem Cache gelesen wurde", "Newer": "Neuer", "Older": "Älter", - "{a}–{b} of {n}": "{a}–{b} von {n}", - "Each request's tokens as its provider reported them; the cost estimated using effective model prices, including custom prices. Export CSV saves every page.": "Token jeder Anfrage laut Angabe des Anbieters; Kosten geschätzt mit effektiven Modellpreisen, einschließlich eigener Preise. „CSV exportieren“ speichert alle Seiten.", - "Saved {n} request to {path}": "{n} Anfrage unter {path} gespeichert", - "Saved {n} requests to {path}": "{n} Anfragen unter {path} gespeichert", "Overview": "Übersicht", "Local session": "Lokale Sitzung", - "Login method": "Anmeldemethode", - "Official login": "Offizielle Anmeldung", - "Duration colors: ≤10 s green · 10–30 s amber · >30 s red": "Farben der Dauer: ≤10 s grün · 10–30 s gelb · >30 s rot", - "Official login confirmed for this account by local login metadata. This does not establish the route or authentication used for this request.": "Offizielle Anmeldung für dieses Konto durch lokale Anmelde-Metadaten bestätigt. Weiterleitung oder Authentifizierung dieser Anfrage sind damit nicht belegt.", "Subscription": "Abo", - "API price reference": "API-Preisreferenz", - "Price reference: {model}": "Preisreferenz: {model}", - "Model used for the API price estimate; this is not an observed model forwarding event.": "Für die API-Preisschätzung verwendetes Modell; keine beobachtete Weiterleitung an ein Modell.", - "Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred.": "Aus der Sitzungsdatei des Agenten gelesen. Das Konto wird nur angezeigt, wenn lokale Metadaten es identifizieren; ein Dienstanbieter wird nicht abgeleitet.", - "Read from the agent's session file, which names the provider it was set up to call. The name shown is that record, not a route magpie saw.": "Aus der Sitzungsdatei des Agenten gelesen, die den Anbieter nennt, für den er eingerichtet wurde. Der angezeigte Name ist diese Aufzeichnung, keine von magpie gesehene Route.", "Recorded provider ID": "Erfasste Anbieter-ID", - "Session account": "Sitzungskonto", - "Gateway calls only; session-log calls are in Requests. Local rejections are excluded from totals.": "Nur Aufrufe über den Zugangspunkt; Aufrufe aus Sitzungslogs stehen unter „Anfragen“. Lokale Ablehnungen sind nicht in den Summen enthalten.", "Gateway and session-log calls; local rejections excluded from totals.": "Aufrufe über den Zugangspunkt und aus Sitzungslogs; lokale Ablehnungen nicht in den Summen enthalten.", "Sessions": "Sitzungen", "Search sessions": "Sitzungen durchsuchen", @@ -13744,31 +13154,15 @@ const I18N = { "{n} folder": "{n} Ordner", "{n} folders": "{n} Ordner", "cost": "Kosten", - "at effective prices": "zu effektiven Preisen", "just now": "gerade eben", "No session matches.": "Keine passende Sitzung.", "No sessions yet. Claude Code's, Codex's, Hermes, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.": "Noch keine Sitzungen. Sitzungen von Claude Code, Codex, Hermes, OpenCode und Pi auf diesem Computer erscheinen hier, jeweils mit Kosten und dem Befehl zum Fortsetzen.", - "Reading the agents' session files…": "Sitzungsdateien der Agenten werden gelesen…", "Totals count every session in the agents' own files; the list is the latest {n} by activity · {dirs}": "Summen zählen jede Sitzung in den Dateien der Agenten; die Liste zeigt die {n} zuletzt aktiven · {dirs}", - "Totals count native sessions and gateway requests with a session ID": "Summen zählen lokale Sitzungen und Gateway-Anfragen mit Sitzungs-ID", - "showing {drawn} of {n}": "{drawn} von {n} angezeigt", "90 days": "90 Tage", - "All folders": "Alle Ordner", "Search {n}…": "{n} durchsuchen…", "No match": "Kein Treffer", - "Indexing your sessions": "Ihre Sitzungen werden indiziert", - "Looking for session files…": "Sitzungsdateien werden gesucht…", - "Reading the kept index…": "Gespeicherter Index wird gelesen…", - "Indexed · putting the page together…": "Indiziert · Seite wird aufgebaut…", - "{done} of {files} files · {read} of {bytes}": "{done} von {files} Dateien · {read} von {bytes}", - "about {t} left": "noch etwa {t}", "{n}s": "{n} s", - "Read once, kept: after this the page opens from the index in a blink": "Einmal gelesen, dauerhaft gespeichert: Danach öffnet sich die Seite blitzschnell aus dem Index", - "Only what changed is read again, from where it was left": "Nur Änderungen werden erneut gelesen, ab der letzten Stelle", - "Every session is read on this computer; nothing leaves it": "Jede Sitzung wird auf diesem Computer gelesen; nichts verlässt ihn", - "The biggest files go first, so none is left running on alone": "Die größten Dateien zuerst, damit keine am Ende allein weiterläuft", "{n} more — type to narrow": "{n} weitere — zum Eingrenzen tippen", - "Nothing in this range.": "Nichts in diesem Zeitraum.", "active": "aktiv", "not kept by model": "nicht pro Modell erfasst", "Active": "Aktiv", @@ -13777,68 +13171,25 @@ const I18N = { "Activity": "Aktivität", "nothing": "nichts", "Less": "Weniger", - "Usage heatmap": "Nutzungs-Heatmap", - "Daily usage over the last 53 weeks": "Tägliche Nutzung der letzten 53 Wochen", "No requests": "Keine Anfragen", "More": "Mehr", "{n} session": "{n} Sitzung", "{n} sessions": "{n} Sitzungen", "{n} day": "{n} Tag", "{n} days": "{n} Tage", - "{d} active": "{d} aktiv", - "Latest sessions": "Neueste Sitzungen", "All sessions": "Alle Sitzungen", - "Open in Sessions": "In „Sitzungen“ öffnen", - "Top sessions": "Top-Sitzungen", "Output tokens": "Ausgabe-Token", "Messages": "Nachrichten", "{n} message": "{n} Nachricht", "{n} messages": "{n} Nachrichten", - "Session shape": "Sitzungsprofil", "Length": "Länge", "Tool calls": "Tool-Aufrufe", - "{r}m": "{r} Min.", - "{r} messages": "{r} Nachrichten", - "{r} minutes at work": "{r} Minuten aktiv", - "{r} tool calls a prompt": "{r} Tool-Aufrufe pro Prompt", - "Across: {axis} · Height: sessions": "Horizontal: {axis} · Höhe: Sitzungen", - "messages in a session, prompts and replies": "Nachrichten einer Sitzung, Prompts und Antworten", - "minutes a session was at work": "Minuten, die eine Sitzung aktiv war", - "tool calls the agent made on its own for each prompt": "Tool-Aufrufe, die der Agent pro Prompt selbstständig ausführte", "Tool use": "Tool-Nutzung", - "No tool calls in this range.": "Keine Tool-Aufrufe in diesem Zeitraum.", "Other": "Sonstige", - "Top skills": "Top-Skills", - "No skill was called up in this range.": "In diesem Zeitraum wurde kein Skill aufgerufen.", - "last {when}": "zuletzt {when}", - "By hour": "Nach Stunde", - "Still counting": "Wird noch gezählt", - "days at work": "aktive Tage", - "longest streak": "längste Serie", - "busiest day": "aktivster Tag", "+{n} more": "+{n} weitere", - "Reading the session…": "Sitzung wird gelesen…", - "Click to show only this": "Klicken, um nur dies anzuzeigen", - "Click again to show every one": "Erneut klicken, um alle anzuzeigen", - "median {m} · p90 {p}": "Median {m} · p90 {p}", - "{p} in {name}": "{p} in {name}", - "Busiest at {when}": "Am aktivsten: {when}", - "Active time isn't kept by model.": "Die aktive Zeit wird nicht pro Modell erfasst.", - "No active time in this range.": "Keine aktive Zeit in diesem Zeitraum.", - "Tokens in and out per session: the middle session's, and what nine in ten stay under": "Ein- und Ausgabe-Token pro Sitzung: der Median und der Wert, den neun von zehn Sitzungen nicht überschreiten", - "on {n} day": "an {n} Tag", - "on {n} days": "an {n} Tagen", - "The time the sessions were at work: the pauses between one message and the next, each under five minutes": "Die aktive Zeit der Sitzungen: die Pausen zwischen zwei Nachrichten, jeweils unter fünf Minuten", "<1m": "<1 Min.", - "{m}m": "{m} Min.", - "{h}h {m}m": "{h} Std. {m} Min.", - "By day": "Pro Tag", - "By week": "Pro Woche", "Tokens": "Token", "Cost": "Kosten", - "{when} · {tokens} tokens": "{when} · {tokens} Token", - "No known price for {models}": "Kein bekannter Preis für {models}", - "Not counted: {models}, with no known price": "Nicht gezählt: {models}, ohne bekannten Preis", "a model with no name": "ein Modell ohne Namen", "{n} session used a model with no known price; its share is not counted": "{n} Sitzung nutzte ein Modell ohne bekannten Preis; ihr Anteil wird nicht gezählt", "{n} sessions used a model with no known price; their share is not counted": "{n} Sitzungen nutzten ein Modell ohne bekannten Preis; ihr Anteil wird nicht gezählt", @@ -13952,11 +13303,6 @@ const I18N = { "Chat requests": "Chat-Anfragen", "Completions": "Completions", "Premium requests": "Premium-Anfragen", - "No calls today.": "Heute keine Aufrufe.", - "No calls in the last 7 days.": "Keine Aufrufe in den letzten 7 Tagen.", - "No calls in the last 30 days.": "Keine Aufrufe in den letzten 30 Tagen.", - "No calls yet.": "Noch keine Aufrufe.", - "Point an agent at a catalog model and use it; every call through the gateway is counted here.": "Richten Sie einen Agenten auf ein Katalogmodell aus und nutzen Sie ihn; jeder Aufruf über den Zugangspunkt wird hier gezählt.", "tokens": "Token", "{a} in · {b} out": "{a} Eingabe · {b} Ausgabe", "cache read": "Cache-Lesen", @@ -13965,21 +13311,16 @@ const I18N = { "reasoning": "Reasoning", "agent": "Agent", "member": "Mitglied", - "inside output": "in der Ausgabe enthalten", "call": "Aufruf", "calls": "Aufrufe", "{n} failed": "{n} fehlgeschlagen", "{n} looped": "{n} in einer Schleife", "Replies magpie ended because the model kept repeating itself": "Antworten, die magpie beendet hat, weil sich das Modell ständig wiederholte", "week of {label}": "Woche ab {label}", - "{when} · {tokens} tokens · {n} call": "{when} · {tokens} Token · {n} Aufruf", - "{when} · {tokens} tokens · {n} calls": "{when} · {tokens} Token · {n} Aufrufe", "{when} · nothing": "{when} · nichts", "{n} call": "{n} Aufruf", "{n} calls": "{n} Aufrufe", - "{n}% of tokens": "{n} % der Token", "{n} cached": "{n} im Cache", - "Counted from the providers' own usage reports on every call through the gateway · {path}": "Gezählt aus den Nutzungsangaben der Anbieter bei jedem Aufruf über den Zugangspunkt · {path}", "Model lists refreshed": "Modelllisten aktualisiert", "Sync failed: {e}": "Synchronisierung fehlgeschlagen: {e}", "Preferences": "Einstellungen", @@ -14156,17 +13497,8 @@ const I18N = { "This key is set to {api} only, but {name} has no {api} URL, so no request reaches {api} with it. Fill in the {api} URL, or set the key to Any protocol.": "Dieser Schlüssel ist nur für {api} eingestellt, aber {name} hat keine {api}-URL, daher erreicht keine Anfrage mit ihm {api}. Trag die {api}-URL ein oder stell den Schlüssel auf Beliebiges Protokoll.", "any API": "beliebige API", "models agents pick as one": "Modelle, die Agenten als eines wählen", - "Hide from this list": "In dieser Liste ausblenden", - "Count as an agent…": "Als Agent zählen…", - "Count {client} on its own": "{client} wieder einzeln zählen", - "with {clients}": "mit {clients}", - "Count this client's calls as": "Aufrufe dieses Clients zählen als", - "{client} is counted as {agent}": "{client} wird als {agent} gezählt", - "{client} is counted on its own": "{client} wird einzeln gezählt", "Client": "Client", - "Actions for {name}": "Aktionen für {name}", "Unhide": "Einblenden", - "Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "Nur in dieser Liste ausgeblendet: Ihre Aufrufe zählen weiter in den Summen und im Diagramm. Klicken, um sie zu sehen.", "found by magpie": "von magpie gefunden", "no member ready": "kein Mitglied bereit", "Manual": "Manuell", @@ -14191,10 +13523,6 @@ const I18N = { "min": "Min.", "slow to start": "langsamer Start", "In magpie": "In magpie", - "Vendor's first token": "Erstes Token des Anbieters", - "Tries that failed first": "Zuvor fehlgeschlagene Versuche", - "Waiting for a slot": "Warten auf einen freien Platz", - "Connecting and sending": "Verbinden und Senden", "One rate limited while it still has quota rests as long as the vendor asks, then takes its place in the order again.": "Ein Konto, das trotz verbleibendem Kontingent ein Rate-Limit erhält, pausiert so lange wie vom Anbieter verlangt und nimmt dann wieder seinen Platz in der Reihenfolge ein.", "One rate limited (429) while it still has quota goes to the back of the order, behind every one not rate limited since, and comes round again once those ahead of it are rate limited in turn — so the load goes round rather than back to the first each time. Out of quota, it rests as usual. Kept until magpie restarts.": "Ein Konto, das trotz verbleibendem Kontingent ein Rate-Limit (429) erhält, wandert ans Ende der Reihenfolge, hinter alle seither nicht begrenzten, und kommt wieder an die Reihe, sobald auch die vor ihm ein Rate-Limit erhalten – so rotiert die Last, statt jedes Mal zum ersten zurückzukehren. Ist das Kontingent aufgebraucht, pausiert es wie üblich. Gilt bis zum Neustart von magpie.", "Rules": "Regeln", @@ -14274,7 +13602,6 @@ const I18N = { "A conversation stays put within a turn, while the agent sends tool results back; when you speak again, routing decides afresh.": "Eine Unterhaltung bleibt innerhalb einer Runde, während der Agent Tool-Ergebnisse zurückschickt; wenn Sie wieder schreiben, entscheidet die Weiterleitung neu.", "Every request is routed afresh, whoever answered its conversation before.": "Jede Anfrage wird neu weitergeleitet, egal wer die Unterhaltung zuvor beantwortet hat.", "Mask the accounts on this page — email addresses and account names — for a screenshot to share": "Konten auf dieser Seite maskieren – E-Mail-Adressen und Kontonamen –, um einen Screenshot zu teilen", - "Refresh now, the allowances too; a Claude account's is read by running Claude Code's own /usage": "Jetzt aktualisieren, auch die Kontingente; das eines Claude-Kontos wird über das eigene /usage von Claude Code gelesen", "Least used": "Am wenigsten genutzt", "requests": "Anfragen", "request": "Anfrage", @@ -14338,7 +13665,6 @@ const I18N = { "Image description": "Bildbeschreibung", "Routing classifier": "Routing-Klassifikator", "magpie's own": "von magpie selbst", - "{n} by magpie itself": "{n} von magpie selbst", "{n} request in this period was magpie's own": "{n} Anfrage in diesem Zeitraum kam von magpie selbst", "{n} requests in this period were magpie's own": "{n} Anfragen in diesem Zeitraum kamen von magpie selbst", "Requests magpie made by itself, not an agent: a routing group's classifier, a web search or an image description. They count against the key or account like any other request.": "Anfragen, die magpie selbst gestellt hat, nicht ein Agent: der Klassifikator einer Routing-Gruppe, eine Websuche oder eine Bildbeschreibung. Sie zählen wie jede andere Anfrage gegen den Schlüssel oder das Konto.", @@ -14408,22 +13734,11 @@ const I18N = { "TTFT {ms}": "TTFT {ms}", "Speed": "Tempo", "Output speed": "Ausgabetempo", - "first token in {ms} on average": "erstes Token im Schnitt nach {ms}", - "no streamed replies timed": "keine gestreamte Antwort gemessen", "Output tokens a second after the first, over the streamed replies": "Ausgabe-Token pro Sekunde nach dem ersten, über die gestreamten Antworten", "No streamed replies timed in this period": "In diesem Zeitraum wurde keine gestreamte Antwort gemessen", - "Sent, Effort and the cache are in each row's details": "Schmales Fenster: Gesendet, Effort und Cache stehen in den Details jeder Zeile", - "{n} output tokens in {ms} after the first": "{n} Ausgabe-Token in {ms} nach dem ersten", - "At least: {n} output tokens in {ms}, from the line that asked for it to its last. The session file has no first token, so the wait for it is counted too": "Mindestens: {n} Ausgabe-Token in {ms}, von der Zeile, die sie anforderte, bis zu ihrer letzten. Die Sitzungsdatei hat kein erstes Token, also zählt das Warten darauf mit", - "At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too": "Mindestens: {n} Antwort-Token in {ms} nach dem ersten Token, ohne die {r} Reasoning-Token. Die Sitzungsdatei hat keinen ersten Text, also zählt Reasoning nach dem ersten Token mit", - "At least: {n} output tokens in {ms}, the whole turn. What came after the first token ({after}) is too little to time a speed by: under a second or under 100 tokens, so the wait for it is counted too": "Mindestens: {n} Ausgabe-Token in {ms}, der ganze Turn. Nach dem ersten Token kam nur {after}, unter einer Sekunde oder unter 100 Token, zu wenig für ein Tempo, also zählt das Warten darauf mit", - "The session file has no first token to time a speed from": "Die Sitzungsdatei hat kein erstes Token, an dem sich ein Tempo messen ließe", "A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "Eine Antwort mit Reasoning zählt nur ihre Antwort ab dem ersten Text: Das Reasoning entstand, bevor der Stream es zeigte", "No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "Ohne Antworttext zählt Reasoning nur bei sichtbar gestreamter Ausgabe; verborgenes Reasoning hat kein Tempo", - "{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "{n} Antwort-Token in {ms} nach dem ersten Text, ohne die {r} Reasoning-Token davor", - "Not streamed: no first token to time a speed from": "Nicht gestreamt: kein erstes Token, an dem sich ein Tempo messen ließe", "Cache": "Cache", - "{i} in · {o} out · {r} cache read · {w} cache creation": "{i} Eingabe · {o} Ausgabe · {r} Cache-Lesen · {w} Cache-Erstellung", "first token in {ms}": "erstes Token nach {ms}", "{n} tok/s": "{n} Token/s", "{k} timed reply": "{k} gemessene Antwort", @@ -14437,11 +13752,8 @@ const I18N = { "Measured on {k} replies, from their first token to their end": "Gemessen an {k} Antworten, vom ersten Token bis zum Ende", "At least: {k} reply read from a session file, which doesn't say when its answer began, so time before that is counted too": "Mindestens: {k} Antwort aus einer Sitzungsdatei. Sie sagt nicht, wann die Antwort begann, also zählt die Zeit davor mit", "At least: {k} replies read from session files, which don't say when their answers began, so time before that is counted too": "Mindestens: {k} Antworten aus Sitzungsdateien. Sie sagen nicht, wann die Antworten begannen, also zählt die Zeit davor mit", - "Upstream provider": "Upstream-Anbieter", "Protocol": "Protokoll", "Upstream stop reason": "Endgrund des Upstreams", - "The agent spoke {from}; sent upstream as {to}": "Der Agent sprach {from}; an den Upstream als {to} gesendet", - "Sent upstream as {to}, as the agent spoke it": "An den Upstream als {to} gesendet, wie der Agent es sprach", "Open Routing": "Weiterleitung öffnen", "{n} min": "{n} min", "{n} h": "{n} h", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 02a38f3a9..4694a7ee6 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -54,7 +54,7 @@ Insights - + Extend @@ -124,117 +124,6 @@ -
-
-
-
- - - - - - - - -
-
- -
-

Gateway calls only; session-log calls are in Requests. Local rejections are excluded from totals.

-
-
-
Agents
-
- -
Models
-
- - - - -

-
- - - -
@@ -561,9 +450,13 @@ + + + + diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index c432d077e..db611ea01 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -1682,6 +1682,7 @@ function routingPage(part) { el("span", "grow")); if (!rp && r.done) { const usage = el("button", "text", t("View usage")); + usage.dataset.feature = "usage"; // it opens on the Usage page usage.onclick = () => window.openUsageRoute(logR); logHead.append(usage); const again = el("button", "text", t("Replay")); diff --git a/internal/gui/assets/plugins/usage/client.js b/internal/gui/assets/plugins/usage/client.js new file mode 100644 index 000000000..ff2e7fc6b --- /dev/null +++ b/internal/gui/assets/plugins/usage/client.js @@ -0,0 +1,139 @@ +// The Usage page: the allowances, what was spent and on what, the +// sessions, each request, and what filled the context window. +// +// A page the Usage plugin adds to the window (kernel.js), its words in +// i18n.js beside this file. This file registers the page and its markup, +// before app.js; page.js, after app.js and the scripts it shares the page +// with, is the page's code, and start.js then shows the first page. The +// hooks are what the shell asks of it: open (the reader came to the page), +// refresh (the window came back: the tab shown read again, quietly when it +// has its figures), reload (Refresh in the sidebar), costs (the currency +// or a rate changed) and tab (the tab shown, for the allowance card a +// link opens on). The allowance cards themselves, which the tray panel +// shows too, stay app.js's. +magpie.plugin("usage", (ctx) => { + ctx.slots.add("page", { + key: "usage", + title: "Usage", + html: ` +
+
+
+ + + + + + + + +
+
+ +
+

Gateway calls only; session-log calls are in Requests. Local rejections are excluded from totals.

+
+
+
Agents
+
+ +
Models
+
+ + + + +

+
+ + + +`, + open() { return loadUsage(true).catch((e) => status(e.message, "err")); }, + refresh(again) { + // on the Overview, where the allowances are, coming back is opening them (#1588) + if (again && usageTab === "usage") quotasOpened(); + return (again && usageDrawn() ? refreshUsage() : loadUsage()).catch((e) => status(e.message, "err")); + }, + reload() { return refreshUsage(true); }, + costs() { renderCosts(); }, + tab() { return usageTab; }, + }); +}); diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js new file mode 100644 index 000000000..eab0312cb --- /dev/null +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -0,0 +1,704 @@ +// The Usage page's words in each language, the English the key: the +// kernel adds them to i18n.js's (magpie.strings). +magpie.strings({ + zh: { + "Yesterday": "昨天", + "This month": "本月", + "Last month": "上个月", + "Pick days": "选择日期", + "Previous month": "上个月", + "Next month": "下个月", + "Days picked: {days}": "所选日期:{days}", + "Now the last day": "再选最后一天", + "Pick the first day, then the last": "先选第一天,再选最后一天", + "No calls on the days picked.": "所选日期内没有调用。", + "All gateway keys": "全部网关密钥", + "All accounts": "全部账号", + "{agent} · on {computer}": "{agent} · 在 {computer}", + "What was said stays on {computer}: sync shares the usage alone.": "对话内容留在 {computer} 上:同步只共享用量。", + "Model · provider": "模型 · 供应商", + "Not archived": "无存档", + "Estimated using effective model prices, including custom prices": "按模型生效价格估算,包含自定义价格", + "Search models, providers, sessions": "搜索模型、供应商、会话", + "Save every request listed, all pages, as a CSV file in Downloads": "将列出的全部请求(所有页)存为 CSV,保存到“下载”文件夹", + "All agents": "全部 Agent", + "{n} out": "输出 {n}", + "{n} cache write": "缓存写入 {n}", + "{n} cache read": "缓存读取 {n}", + "reported by apps": "由应用上报", + "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "由发起请求的应用通过 POST /v1/magpie/usage/requests 上报:这次请求直接发给了服务商,没有经过 magpie。", + "all requests": "全部请求", + "Show only these requests": "只看这些请求", + "Show every request again": "重新显示全部请求", + "View routing": "查看路由", + "Request: {what}": "请求:{what}", + "Provider · account": "供应商 · 账号", + "{m} for 5 minutes, {h} for an hour": "{m} 保留 5 分钟,{h} 保留 1 小时", + "session {id}": "会话 {id}", + "{agent} · via {host}": "{agent} · 来自 {host}", + "Not kept for requests before this version": "此版本之前的请求没有记下", + "{n} reasoning, inside output": "其中推理 {n}(已计入输出)", + "No known price for this model": "此模型没有已知价格", + "Failed: the agent was answered {status}": "失败:Agent 收到的是 {status}", + "Error type": "错误类型", + "Upstream said": "上游返回", + "Data source": "数据来源", + "Nothing more was kept of this request": "这个请求没有更多记录", + "OFFICIAL": "官方", + "No session was named with this request, so its session file can't be found": "此请求未带会话 ID,找不到其会话文件", + "magpie reads the session files of Claude Code, Claude Desktop and Codex only": "magpie 只读 Claude Code、Claude Desktop 和 Codex 的会话文件", + "This request isn't in the agent's session files: they may be deleted, moved, or not written yet": "Agent 会话文件中没有此请求:文件可能已删除、移走或尚未写入", + "The session file couldn't be read": "会话文件读取失败", + "Refresh every": "刷新周期", + "Updated {time}": "更新于 {time}", + "Model recorded in the local session log; the outbound HTTP request was not captured.": "本地会话日志记录的模型;未采集实际发出的 HTTP 请求。", + "About: told from the session file's times, a little more or less than it took": "估算值:按会话文件中的时间计算,与实际耗时略有出入", + "{n} call unpriced": "{n} 次调用未计价", + "{n} calls unpriced": "{n} 次调用未计价", + "{n} model unpriced": "{n} 个模型未计价", + "{n} models unpriced": "{n} 个模型未计价", + "Show only the requests answered on a retry": "只看重试后成功的请求", + "Show only the failed requests": "只看失败的请求", + "This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "这次尝试失败,请求已转交给下一个:请求按最终结果计数,不算这次尝试", + "{p} succeeded": "成功 {p}", + "{a} cache": "缓存 {a}", + "{a}–{b} of {n}": "第 {a}–{b} 条,共 {n} 条", + "Each request's tokens as its provider reported them; the cost estimated using effective model prices, including custom prices. Export CSV saves every page.": "每个请求的 token 数取自供应商报告,费用按模型生效价格(含自定义价格)估算。导出 CSV 包含所有页。", + "Saved {n} request to {path}": "已将 {n} 个请求保存到 {path}", + "Saved {n} requests to {path}": "已将 {n} 个请求保存到 {path}", + "Login method": "登录方式", + "Official login": "官方登录", + "Duration colors: ≤10 s green · 10–30 s amber · >30 s red": "耗时颜色:≤10 秒绿色 · 10–30 秒黄色 · >30 秒红色", + "Official login confirmed for this account by local login metadata. This does not establish the route or authentication used for this request.": "本地登录资料确认此账号采用官方登录;不代表已确认这次请求的渠道或认证方式。", + "API price reference": "API 估价参考模型", + "Price reference: {model}": "估价参考:{model}", + "Model used for the API price estimate; this is not an observed model forwarding event.": "用于 API 费用估算的参考模型;并非实际观测到的模型转发记录。", + "Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred.": "读自 Agent 的会话文件;仅在本地元数据能够明确识别时显示账号,不推断供应商。", + "Read from the agent's session file, which names the provider it was set up to call. The name shown is that record, not a route magpie saw.": "读自 Agent 的会话文件,其中记录了它被配置去调用的供应商。此处显示的就是那条记录,不是 magpie 看到的路由。", + "Session account": "会话账号", + "Gateway calls only; session-log calls are in Requests. Local rejections are excluded from totals.": "仅统计网关调用;会话日志调用请查看「请求」。本地拒绝的请求不计入汇总。", + "at effective prices": "按生效价格", + "Reading the agents' session files…": "正在读取 Agent 的会话文件…", + "Totals count native sessions and gateway requests with a session ID": "合计含本机会话和带有会话 ID 的网关请求", + "showing {drawn} of {n}": "显示 {n} 个中的 {drawn} 个", + "All folders": "全部文件夹", + "Indexing your sessions": "正在为你的会话建立索引", + "Looking for session files…": "正在查找会话文件…", + "Reading the kept index…": "正在读取已建好的索引…", + "Indexed · putting the page together…": "索引完成 · 正在生成页面…", + "{done} of {files} files · {read} of {bytes}": "{done} / {files} 个文件 · {read} / {bytes}", + "about {t} left": "约剩 {t}", + "Read once, kept: after this the page opens from the index in a blink": "只需索引一次:之后打开这一页几乎是瞬间的", + "Only what changed is read again, from where it was left": "之后只读新增的部分,从上次读到的地方接着读", + "Every session is read on this computer; nothing leaves it": "所有会话都在本机读取,不会上传到任何地方", + "The biggest files go first, so none is left running on alone": "最大的文件先读,所有核心一起跑满", + "Nothing in this range.": "这段时间没有用量。", + "Usage heatmap": "用量热力图", + "Daily usage over the last 53 weeks": "最近 53 周的每日用量", + "{d} active": "活跃 {d}", + "Latest sessions": "最近的会话", + "Open in Sessions": "在会话页打开", + "Top sessions": "最耗会话", + "Session shape": "会话形态", + "{r}m": "{r} 分钟", + "{r} messages": "{r} 条消息", + "{r} minutes at work": "工作 {r} 分钟", + "{r} tool calls a prompt": "每条提示 {r} 次工具调用", + "Across: {axis} · Height: sessions": "横轴:{axis} · 柱高:会话数", + "messages in a session, prompts and replies": "一个会话里的消息数(提示加回复)", + "minutes a session was at work": "一个会话实际工作的分钟数", + "tool calls the agent made on its own for each prompt": "你每发一条提示,Agent 自己调用工具的次数", + "No tool calls in this range.": "这段时间没有工具调用。", + "Top skills": "常用 Skills", + "No skill was called up in this range.": "这段时间没有调用 skill。", + "last {when}": "最近 {when}", + "By hour": "按时段", + "Still counting": "还在统计", + "days at work": "活跃天数", + "longest streak": "最长连续", + "busiest day": "最忙的一天", + "Reading the session…": "正在读取会话…", + "Click to show only this": "点击只看这一项", + "Click again to show every one": "再点一次显示全部", + "median {m} · p90 {p}": "中位 {m} · p90 {p}", + "{p} in {name}": "{name} 占 {p}", + "Busiest at {when}": "最忙:{when}", + "Active time isn't kept by model.": "活跃时长不按模型统计。", + "No active time in this range.": "这段时间没有活跃时长。", + "Tokens in and out per session: the middle session's, and what nine in ten stay under": "每个会话的输入加输出 token:中位数,以及九成会话不超过的量", + "on {n} day": "共 {n} 天", + "on {n} days": "共 {n} 天", + "The time the sessions were at work: the pauses between one message and the next, each under five minutes": "会话实际工作的时间:相邻两条消息之间的间隔,只计不到五分钟的", + "{m}m": "{m} 分钟", + "{h}h {m}m": "{h} 小时 {m} 分", + "By day": "每日趋势", + "By week": "每周趋势", + "{when} · {tokens} tokens": "{when} · {tokens} token", + "No known price for {models}": "{models} 没有已知价格", + "Not counted: {models}, with no known price": "未计入:{models},没有已知价格", + "No calls today.": "今天没有调用。", + "No calls in the last 7 days.": "最近 7 天没有调用。", + "No calls in the last 30 days.": "最近 30 天没有调用。", + "No calls yet.": "还没有调用。", + "Point an agent at a catalog model and use it; every call through the gateway is counted here.": "让某个 Agent 使用目录中的模型;每次经过网关的调用都会计入这里。", + "inside output": "计入输出", + "{when} · {tokens} tokens · {n} call": "{when} · {tokens} token · {n} 次调用", + "{when} · {tokens} tokens · {n} calls": "{when} · {tokens} token · {n} 次调用", + "{n}% of tokens": "占 token 的 {n}%", + "Counted from the providers' own usage reports on every call through the gateway · {path}": "根据供应商在每次网关调用中返回的用量统计 · {path}", + "Hide from this list": "从列表中隐藏", + "Count as an agent…": "计入某个 Agent…", + "Count {client} on its own": "将 {client} 单独计算", + "with {clients}": "含 {clients}", + "Count this client's calls as": "将此客户端的调用计入", + "{client} is counted as {agent}": "{client} 已计入 {agent}", + "{client} is counted on its own": "{client} 已单独计算", + "Actions for {name}": "{name} 的操作", + "Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "只是不在此列表中显示,它们的调用仍计入总数和图表。点击查看。", + "Vendor's first token": "厂商首字等待", + "Tries that failed first": "之前失败的尝试", + "Waiting for a slot": "排队等空位", + "Connecting and sending": "连接并发送请求", + "Refresh now, the allowances too; a Claude account's is read by running Claude Code's own /usage": "立即刷新,含额度;Claude 账号的额度通过运行 Claude Code 自带的 /usage 读取", + "{n} by magpie itself": "其中 {n} 次由 magpie 自身发出", + "first token in {ms} on average": "首字平均 {ms}", + "no streamed replies timed": "没有可计时的流式回复", + "Sent, Effort and the cache are in each row's details": "窗口较窄:发送模型、推理强度和缓存在每行的详情里", + "{n} output tokens in {ms} after the first": "首字后 {ms} 输出 {n} 个 token", + "At least: {n} output tokens in {ms}, from the line that asked for it to its last. The session file has no first token, so the wait for it is counted too": "下限:从发出请求的那一行到最后一行,{ms} 输出 {n} 个 token。会话文件没有首字时间,等首字的时间也算在里面", + "At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too": "下限:首字后 {ms} 输出 {n} 个正文 token,{r} 个推理 token 不计。会话文件没有首个正文的时间,首字后的推理时间也算在里面", + "At least: {n} output tokens in {ms}, the whole turn. What came after the first token ({after}) is too little to time a speed by: under a second or under 100 tokens, so the wait for it is counted too": "下限:整轮 {ms} 输出 {n} 个 token。首字后只有 {after},不足 1 秒或不足 100 个 token,测不出速度,等首字的时间也算在里面", + "The session file has no first token to time a speed from": "会话文件没有首字时间,算不出速度", + "{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "首个正文后 {ms} 输出 {n} 个正文 token,之前的 {r} 个推理 token 不计", + "Not streamed: no first token to time a speed from": "非流式:没有首字时间,算不出速度", + "{i} in · {o} out · {r} cache read · {w} cache creation": "输入 {i} · 输出 {o} · 缓存读取 {r} · 缓存创建 {w}", + "Upstream provider": "上游", + "The agent spoke {from}; sent upstream as {to}": "agent 用 {from} 协议请求;以 {to} 协议发往上游", + "Sent upstream as {to}, as the agent spoke it": "以 {to} 协议发往上游,与 agent 所用协议相同", + }, + "zh-TW": { + "Yesterday": "昨天", + "This month": "本月", + "Last month": "上個月", + "Pick days": "選擇日期", + "Previous month": "上個月", + "Next month": "下個月", + "Days picked: {days}": "所選日期:{days}", + "Now the last day": "再選最後一天", + "Pick the first day, then the last": "先選第一天,再選最後一天", + "No calls on the days picked.": "所選日期內沒有呼叫。", + "All gateway keys": "全部閘道金鑰", + "All accounts": "全部帳號", + "{agent} · on {computer}": "{agent} · 在 {computer}", + "What was said stays on {computer}: sync shares the usage alone.": "對話內容留在 {computer} 上:同步只共享用量。", + "Model · provider": "模型 · 供應商", + "Not archived": "無存檔", + "Estimated using effective model prices, including custom prices": "按模型生效價格估算,包含自定義價格", + "Search models, providers, sessions": "搜尋模型、供應商、會話", + "Save every request listed, all pages, as a CSV file in Downloads": "將列出的全部請求(所有頁)存為 CSV,儲存到「下載」資料夾", + "All agents": "全部 Agent", + "{n} out": "輸出 {n}", + "{n} cache write": "快取寫入 {n}", + "{n} cache read": "快取讀取 {n}", + "reported by apps": "由應用程式回報", + "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "由發出請求的應用程式透過 POST /v1/magpie/usage/requests 回報:這次請求直接送往服務商,沒有經過 magpie。", + "all requests": "全部請求", + "Show only these requests": "只看這些請求", + "Show every request again": "重新顯示全部請求", + "View routing": "檢視路由", + "Request: {what}": "請求:{what}", + "Provider · account": "供應商 · 帳號", + "{m} for 5 minutes, {h} for an hour": "{m} 保留 5 分鐘,{h} 保留 1 小時", + "session {id}": "會話 {id}", + "{agent} · via {host}": "{agent} · 來自 {host}", + "Not kept for requests before this version": "此版本之前的請求沒有記下", + "{n} reasoning, inside output": "其中推理 {n}(已計入輸出)", + "No known price for this model": "此模型沒有已知價格", + "Failed: the agent was answered {status}": "失敗:Agent 收到的是 {status}", + "Error type": "錯誤型別", + "Upstream said": "上游返回", + "Data source": "資料來源", + "Nothing more was kept of this request": "這個請求沒有更多記錄", + "OFFICIAL": "官方", + "No session was named with this request, so its session file can't be found": "此請求未帶會話 ID,找不到其會話檔案", + "magpie reads the session files of Claude Code, Claude Desktop and Codex only": "magpie 只讀 Claude Code、Claude Desktop 和 Codex 的會話檔案", + "This request isn't in the agent's session files: they may be deleted, moved, or not written yet": "Agent 會話檔案中沒有此請求:檔案可能已刪除、移走或尚未寫入", + "The session file couldn't be read": "會話檔案讀取失敗", + "Refresh every": "重新整理週期", + "Updated {time}": "更新於 {time}", + "Model recorded in the local session log; the outbound HTTP request was not captured.": "本地會話日誌記錄的模型;未採集實際發出的 HTTP 請求。", + "About: told from the session file's times, a little more or less than it took": "估算值:按會話檔案中的時間計算,與實際耗時略有出入", + "{n} call unpriced": "{n} 次呼叫未計價", + "{n} calls unpriced": "{n} 次呼叫未計價", + "{n} model unpriced": "{n} 個模型未計價", + "{n} models unpriced": "{n} 個模型未計價", + "Show only the requests answered on a retry": "只看重試後成功的請求", + "Show only the failed requests": "只看失敗的請求", + "This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "這次嘗試失敗,請求已轉交給下一個:請求依最終結果計數,不算這次嘗試", + "{p} succeeded": "成功 {p}", + "{a} cache": "快取 {a}", + "{a}–{b} of {n}": "第 {a}–{b} 條,共 {n} 條", + "Each request's tokens as its provider reported them; the cost estimated using effective model prices, including custom prices. Export CSV saves every page.": "每個請求的 token 數取自供應商報告,費用按模型生效價格(含自定義價格)估算。匯出 CSV 包含所有頁。", + "Saved {n} request to {path}": "已將 {n} 個請求儲存到 {path}", + "Saved {n} requests to {path}": "已將 {n} 個請求儲存到 {path}", + "Login method": "登入方式", + "Official login": "官方登入", + "Duration colors: ≤10 s green · 10–30 s amber · >30 s red": "耗時顏色:≤10 秒綠色 · 10–30 秒黃色 · >30 秒紅色", + "Official login confirmed for this account by local login metadata. This does not establish the route or authentication used for this request.": "本地登入資料確認此帳號採用官方登入;不代表已確認這次請求的渠道或認證方式。", + "API price reference": "API 估價參考模型", + "Price reference: {model}": "估價參考:{model}", + "Model used for the API price estimate; this is not an observed model forwarding event.": "用於 API 費用估算的參考模型;並非實際觀測到的模型轉發記錄。", + "Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred.": "讀自 Agent 的會話檔案;僅在本地後設資料能夠明確識別時顯示帳號,不推斷供應商。", + "Read from the agent's session file, which names the provider it was set up to call. The name shown is that record, not a route magpie saw.": "讀自 Agent 的會話檔案,其中記錄了它被設定去呼叫的供應商。此處顯示的就是那條記錄,不是 magpie 看到的路由。", + "Session account": "會話帳號", + "Gateway calls only; session-log calls are in Requests. Local rejections are excluded from totals.": "僅統計閘道呼叫;會話日誌呼叫請檢視「請求」。本地拒絕的請求不計入彙總。", + "at effective prices": "按生效價格", + "Reading the agents' session files…": "正在讀取 Agent 的會話檔案…", + "Totals count native sessions and gateway requests with a session ID": "合計含本機會話和帶有會話 ID 的閘道請求", + "showing {drawn} of {n}": "顯示 {n} 箇中的 {drawn} 個", + "All folders": "全部資料夾", + "Indexing your sessions": "正在為你的會話建立索引", + "Looking for session files…": "正在查詢會話檔案…", + "Reading the kept index…": "正在讀取已建好的索引…", + "Indexed · putting the page together…": "索引完成 · 正在生成頁面…", + "{done} of {files} files · {read} of {bytes}": "{done} / {files} 個檔案 · {read} / {bytes}", + "about {t} left": "約剩 {t}", + "Read once, kept: after this the page opens from the index in a blink": "只需索引一次:之後開啟這一頁幾乎是瞬間的", + "Only what changed is read again, from where it was left": "之後只讀新增的部分,從上次讀到的地方接著讀", + "Every session is read on this computer; nothing leaves it": "所有會話都在本機讀取,不會上傳到任何地方", + "The biggest files go first, so none is left running on alone": "最大的檔案先讀,所有核心一起跑滿", + "Nothing in this range.": "這段時間沒有用量。", + "Usage heatmap": "用量熱力圖", + "Daily usage over the last 53 weeks": "最近 53 週的每日用量", + "{d} active": "活躍 {d}", + "Latest sessions": "最近的會話", + "Open in Sessions": "在會話頁開啟", + "Top sessions": "最耗會話", + "Session shape": "會話形態", + "{r}m": "{r} 分鐘", + "{r} messages": "{r} 條訊息", + "{r} minutes at work": "工作 {r} 分鐘", + "{r} tool calls a prompt": "每條提示 {r} 次工具呼叫", + "Across: {axis} · Height: sessions": "橫軸:{axis} · 柱高:會話數", + "messages in a session, prompts and replies": "一個會話裡的訊息數(提示加回覆)", + "minutes a session was at work": "一個會話實際工作的分鐘數", + "tool calls the agent made on its own for each prompt": "你每發一條提示,Agent 自己呼叫工具的次數", + "No tool calls in this range.": "這段時間沒有工具呼叫。", + "Top skills": "常用 Skills", + "No skill was called up in this range.": "這段時間沒有呼叫 skill。", + "last {when}": "最近 {when}", + "By hour": "按時段", + "Still counting": "還在統計", + "days at work": "活躍天數", + "longest streak": "最長連續", + "busiest day": "最忙的一天", + "Reading the session…": "正在讀取會話…", + "Click to show only this": "點選只看這一項", + "Click again to show every one": "再點一次顯示全部", + "median {m} · p90 {p}": "中位 {m} · p90 {p}", + "{p} in {name}": "{name} 佔 {p}", + "Busiest at {when}": "最忙:{when}", + "Active time isn't kept by model.": "活躍時長不按模型統計。", + "No active time in this range.": "這段時間沒有活躍時長。", + "Tokens in and out per session: the middle session's, and what nine in ten stay under": "每個會話的輸入加輸出 token:中位數,以及九成會話不超過的量", + "on {n} day": "共 {n} 天", + "on {n} days": "共 {n} 天", + "The time the sessions were at work: the pauses between one message and the next, each under five minutes": "會話實際工作的時間:相鄰兩條訊息之間的間隔,只計不到五分鐘的", + "{m}m": "{m} 分鐘", + "{h}h {m}m": "{h} 小時 {m} 分", + "By day": "每日趨勢", + "By week": "每週趨勢", + "{when} · {tokens} tokens": "{when} · {tokens} token", + "No known price for {models}": "{models} 沒有已知價格", + "Not counted: {models}, with no known price": "未計入:{models},沒有已知價格", + "No calls today.": "今天沒有呼叫。", + "No calls in the last 7 days.": "最近 7 天沒有呼叫。", + "No calls in the last 30 days.": "最近 30 天沒有呼叫。", + "No calls yet.": "還沒有呼叫。", + "Point an agent at a catalog model and use it; every call through the gateway is counted here.": "讓某個 Agent 使用目錄中的模型;每次經過閘道的呼叫都會計入這裡。", + "inside output": "計入輸出", + "{when} · {tokens} tokens · {n} call": "{when} · {tokens} token · {n} 次呼叫", + "{when} · {tokens} tokens · {n} calls": "{when} · {tokens} token · {n} 次呼叫", + "{n}% of tokens": "佔 token 的 {n}%", + "Counted from the providers' own usage reports on every call through the gateway · {path}": "根據供應商在每次閘道呼叫中返回的用量統計 · {path}", + "Hide from this list": "從列表中隱藏", + "Count as an agent…": "計入某個 Agent…", + "Count {client} on its own": "將 {client} 單獨計算", + "with {clients}": "含 {clients}", + "Count this client's calls as": "將此用戶端的呼叫計入", + "{client} is counted as {agent}": "{client} 已計入 {agent}", + "{client} is counted on its own": "{client} 已單獨計算", + "Actions for {name}": "{name} 的操作", + "Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "只是不在此列表中顯示,它們的呼叫仍計入總數和圖表。點按查看。", + "Vendor's first token": "廠商首字等待", + "Tries that failed first": "之前失敗的嘗試", + "Waiting for a slot": "排隊等空位", + "Connecting and sending": "連線並傳送請求", + "Refresh now, the allowances too; a Claude account's is read by running Claude Code's own /usage": "立即重新整理,含額度;Claude 帳號的額度透過執行 Claude Code 自帶的 /usage 讀取", + "{n} by magpie itself": "其中 {n} 次由 magpie 自身發出", + "first token in {ms} on average": "首字平均 {ms}", + "no streamed replies timed": "沒有可計時的流式回覆", + "Sent, Effort and the cache are in each row's details": "視窗較窄:傳送模型、推理強度和快取在每行的詳情裡", + "{n} output tokens in {ms} after the first": "首字後 {ms} 輸出 {n} 個 token", + "At least: {n} output tokens in {ms}, from the line that asked for it to its last. The session file has no first token, so the wait for it is counted too": "下限:從發出請求的那一行到最後一行,{ms} 輸出 {n} 個 token。會話檔案沒有首字時間,等首字的時間也算在裡面", + "At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too": "下限:首字後 {ms} 輸出 {n} 個正文 token,{r} 個推理 token 不計。會話檔案沒有首個正文的時間,首字後的推理時間也算在裡面", + "At least: {n} output tokens in {ms}, the whole turn. What came after the first token ({after}) is too little to time a speed by: under a second or under 100 tokens, so the wait for it is counted too": "下限:整輪 {ms} 輸出 {n} 個 token。首字後只有 {after},不足 1 秒或不足 100 個 token,測不出速度,等首字的時間也算在裡面", + "The session file has no first token to time a speed from": "會話檔案沒有首字時間,算不出速度", + "{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "首個正文後 {ms} 輸出 {n} 個正文 token,之前的 {r} 個推理 token 不計", + "Not streamed: no first token to time a speed from": "非流式:沒有首字時間,算不出速度", + "{i} in · {o} out · {r} cache read · {w} cache creation": "輸入 {i} · 輸出 {o} · 快取讀取 {r} · 快取建立 {w}", + "Upstream provider": "上游", + "The agent spoke {from}; sent upstream as {to}": "agent 用 {from} 協議請求;以 {to} 協議發往上游", + "Sent upstream as {to}, as the agent spoke it": "以 {to} 協議發往上游,與 agent 所用協議相同", + }, + ja: { + "Yesterday": "昨日", + "This month": "今月", + "Last month": "先月", + "Pick days": "日付を選ぶ", + "Previous month": "前の月", + "Next month": "次の月", + "Days picked: {days}": "選んだ日付:{days}", + "Now the last day": "次に最終日を選択", + "Pick the first day, then the last": "最初の日、次に最終日を選択", + "No calls on the days picked.": "選んだ日付の呼び出しはありません。", + "All gateway keys": "すべてのゲートウェイキー", + "All accounts": "すべてのアカウント", + "{agent} · on {computer}": "{agent} · {computer} 上", + "What was said stays on {computer}: sync shares the usage alone.": "会話内容は {computer} に残ります。同期で共有されるのは使用量だけです。", + "Model · provider": "モデル · プロバイダ", + "Not archived": "アーカイブなし", + "Estimated using effective model prices, including custom prices": "カスタム価格を含む、モデルの適用価格で見積もり", + "Search models, providers, sessions": "モデル、プロバイダ、セッションを検索", + "Save every request listed, all pages, as a CSV file in Downloads": "一覧のリクエストを全ページ分、CSV ファイルとして「ダウンロード」フォルダに保存", + "All agents": "すべてのエージェント", + "{n} out": "出力 {n}", + "{n} cache write": "キャッシュ書き込み {n}", + "{n} cache read": "キャッシュ読み取り {n}", + "reported by apps": "アプリからの報告", + "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "リクエストを送ったアプリが POST /v1/magpie/usage/requests で報告したものです。このリクエストは magpie を経由せず、直接ベンダーに送られました。", + "all requests": "すべてのリクエスト", + "Show only these requests": "これらのリクエストだけを表示", + "Show every request again": "すべてのリクエストを再表示", + "View routing": "ルーティングを表示", + "Request: {what}": "リクエスト:{what}", + "Provider · account": "プロバイダ · アカウント", + "{m} for 5 minutes, {h} for an hour": "{m} は 5 分間、{h} は 1 時間保持", + "session {id}": "セッション {id}", + "{agent} · via {host}": "{agent} · {host} 経由", + "Not kept for requests before this version": "このバージョンより前のリクエストでは記録されていません", + "{n} reasoning, inside output": "推論 {n}(出力に含む)", + "No known price for this model": "このモデルの価格は不明です", + "Failed: the agent was answered {status}": "失敗:エージェントには {status} が返されました", + "Error type": "エラーの種類", + "Upstream said": "上流の応答", + "Data source": "データソース", + "Nothing more was kept of this request": "このリクエストについてこれ以上の記録はありません", + "OFFICIAL": "公式", + "No session was named with this request, so its session file can't be found": "このリクエストにはセッションが指定されていないため、セッションファイルが見つかりません", + "magpie reads the session files of Claude Code, Claude Desktop and Codex only": "magpie が読み取れるのは Claude Code、Claude Desktop、Codex のセッションファイルのみです", + "This request isn't in the agent's session files: they may be deleted, moved, or not written yet": "このリクエストはエージェントのセッションファイルにありません。削除・移動されたか、まだ書き込まれていない可能性があります", + "The session file couldn't be read": "セッションファイルを読み取れませんでした", + "Refresh every": "更新間隔", + "Updated {time}": "{time} に更新", + "Model recorded in the local session log; the outbound HTTP request was not captured.": "ローカルのセッションログに記録されたモデルです。実際に送信された HTTP リクエストは取得していません。", + "About: told from the session file's times, a little more or less than it took": "概算:セッションファイルの時刻から算出しており、実際の所要時間とは多少ずれます", + "{n} call unpriced": "{n} 件の呼び出しは価格不明", + "{n} calls unpriced": "{n} 件の呼び出しは価格不明", + "{n} model unpriced": "{n} 個のモデルは価格不明", + "{n} models unpriced": "{n} 個のモデルは価格不明", + "Show only the requests answered on a retry": "再試行で成功したリクエストだけを表示", + "Show only the failed requests": "失敗したリクエストだけを表示", + "This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "この試行は失敗し、リクエストは次へ引き継がれました。リクエストはこの試行ではなく最終結果で数えます", + "{p} succeeded": "成功 {p}", + "{a} cache": "キャッシュ {a}", + "{a}–{b} of {n}": "{n} 件中 {a}–{b}", + "Each request's tokens as its provider reported them; the cost estimated using effective model prices, including custom prices. Export CSV saves every page.": "各リクエストのトークン数はプロバイダの報告によるもので、費用はカスタム価格を含む有効なモデル価格で見積もっています。CSV エクスポートは全ページを保存します。", + "Saved {n} request to {path}": "{n} 件のリクエストを {path} に保存しました", + "Saved {n} requests to {path}": "{n} 件のリクエストを {path} に保存しました", + "Login method": "ログイン方法", + "Official login": "公式ログイン", + "Duration colors: ≤10 s green · 10–30 s amber · >30 s red": "所要時間の色:≤10 秒 緑 · 10–30 秒 黄 · >30 秒 赤", + "Official login confirmed for this account by local login metadata. This does not establish the route or authentication used for this request.": "ローカルのログイン情報により、このアカウントは公式ログインであることが確認されています。このリクエストの経路や認証方式を確認するものではありません。", + "API price reference": "API 価格の参考モデル", + "Price reference: {model}": "価格の参考:{model}", + "Model used for the API price estimate; this is not an observed model forwarding event.": "API 費用の見積もりに使った参考モデルです。実際に観測されたモデル転送ではありません。", + "Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred.": "エージェントのセッションファイルから読み取り。アカウントはローカルのメタデータで特定できる場合のみ表示し、プロバイダは推測しません。", + "Read from the agent's session file, which names the provider it was set up to call. The name shown is that record, not a route magpie saw.": "エージェントのセッションファイルから読み取り。呼び出すよう設定されたプロバイダが記録されています。ここに表示されるのはその記録であり、magpie が確認したルートではありません。", + "Session account": "セッションのアカウント", + "Gateway calls only; session-log calls are in Requests. Local rejections are excluded from totals.": "ゲートウェイ経由の呼び出しのみ。セッションログの呼び出しは「リクエスト」にあります。ローカルで拒否されたものは合計に含みません。", + "at effective prices": "有効な価格で", + "Reading the agents' session files…": "エージェントのセッションファイルを読み取り中…", + "Totals count native sessions and gateway requests with a session ID": "合計にはローカルのセッションとセッション ID のあるゲートウェイ要求が含まれます", + "showing {drawn} of {n}": "{n} 件中 {drawn} 件を表示", + "All folders": "すべてのフォルダ", + "Indexing your sessions": "セッションのインデックスを作成中", + "Looking for session files…": "セッションファイルを探しています…", + "Reading the kept index…": "保存済みのインデックスを読み取り中…", + "Indexed · putting the page together…": "インデックス作成完了 · ページを準備しています…", + "{done} of {files} files · {read} of {bytes}": "{done} / {files} ファイル · {read} / {bytes}", + "about {t} left": "残り約 {t}", + "Read once, kept: after this the page opens from the index in a blink": "一度読み取れば保存されます。次回からはインデックスから一瞬で開きます", + "Only what changed is read again, from where it was left": "次回からは変更された部分だけを、前回の続きから読み取ります", + "Every session is read on this computer; nothing leaves it": "すべてのセッションはこのコンピュータ上で読み取られ、外部には送信されません", + "The biggest files go first, so none is left running on alone": "大きいファイルから先に読むので、最後に 1 つだけ残って時間がかかることはありません", + "Nothing in this range.": "この期間のデータはありません。", + "Usage heatmap": "使用量ヒートマップ", + "Daily usage over the last 53 weeks": "直近 53 週間の日ごとの使用量", + "{d} active": "アクティブ {d}", + "Latest sessions": "最近のセッション", + "Open in Sessions": "セッションで開く", + "Top sessions": "上位のセッション", + "Session shape": "セッションの傾向", + "{r}m": "{r} 分", + "{r} messages": "{r} 件のメッセージ", + "{r} minutes at work": "作業時間 {r} 分", + "{r} tool calls a prompt": "プロンプトあたり {r} 回のツール呼び出し", + "Across: {axis} · Height: sessions": "横軸:{axis} · 高さ:セッション数", + "messages in a session, prompts and replies": "セッション内のメッセージ数(プロンプトと応答)", + "minutes a session was at work": "セッションが作業していた分数", + "tool calls the agent made on its own for each prompt": "プロンプト 1 つにつきエージェントが自ら行ったツール呼び出しの回数", + "No tool calls in this range.": "この期間のツール呼び出しはありません。", + "Top skills": "よく使うスキル", + "No skill was called up in this range.": "この期間に呼び出されたスキルはありません。", + "last {when}": "最終 {when}", + "By hour": "時間帯別", + "Still counting": "集計中", + "days at work": "作業日数", + "longest streak": "最長連続日数", + "busiest day": "最も忙しかった日", + "Reading the session…": "セッションを読み取り中…", + "Click to show only this": "クリックでこれだけを表示", + "Click again to show every one": "もう一度クリックですべて表示", + "median {m} · p90 {p}": "中央値 {m} · p90 {p}", + "{p} in {name}": "{name} が {p}", + "Busiest at {when}": "最も忙しい時間:{when}", + "Active time isn't kept by model.": "アクティブ時間はモデル別には記録されません。", + "No active time in this range.": "この期間のアクティブ時間はありません。", + "Tokens in and out per session: the middle session's, and what nine in ten stay under": "セッションあたりの入出力トークン:中央値と、9 割のセッションが収まる量", + "on {n} day": "{n} 日間", + "on {n} days": "{n} 日間", + "The time the sessions were at work: the pauses between one message and the next, each under five minutes": "セッションが作業していた時間:メッセージ間の間隔のうち、5 分未満のものだけを合計", + "{m}m": "{m} 分", + "{h}h {m}m": "{h} 時間 {m} 分", + "By day": "日別", + "By week": "週別", + "{when} · {tokens} tokens": "{when} · {tokens} トークン", + "No known price for {models}": "{models} の価格は不明です", + "Not counted: {models}, with no known price": "計上されていません:{models}(価格不明)", + "No calls today.": "今日の呼び出しはありません。", + "No calls in the last 7 days.": "過去 7 日間の呼び出しはありません。", + "No calls in the last 30 days.": "過去 30 日間の呼び出しはありません。", + "No calls yet.": "呼び出しはまだありません。", + "Point an agent at a catalog model and use it; every call through the gateway is counted here.": "エージェントにカタログのモデルを指定して使うと、ゲートウェイ経由のすべての呼び出しがここに集計されます。", + "inside output": "出力に含む", + "{when} · {tokens} tokens · {n} call": "{when} · {tokens} トークン · {n} 回の呼び出し", + "{when} · {tokens} tokens · {n} calls": "{when} · {tokens} トークン · {n} 回の呼び出し", + "{n}% of tokens": "トークンの {n}%", + "Counted from the providers' own usage reports on every call through the gateway · {path}": "ゲートウェイ経由の各呼び出しでプロバイダが返した使用量から集計 · {path}", + "Hide from this list": "この一覧から隠す", + "Count as an agent…": "エージェントとして数える…", + "Count {client} on its own": "{client} を別に数える", + "with {clients}": "{clients} を含む", + "Count this client's calls as": "このクライアントの呼び出しを数える先", + "{client} is counted as {agent}": "{client} を {agent} として数えます", + "{client} is counted on its own": "{client} を別に数えます", + "Actions for {name}": "{name} の操作", + "Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "この一覧に表示しないだけで、呼び出しは合計とグラフに含まれます。クリックで表示します。", + "Vendor's first token": "ベンダーの最初のトークン", + "Tries that failed first": "先に失敗した試行", + "Waiting for a slot": "空き枠待ち", + "Connecting and sending": "接続と送信", + "Refresh now, the allowances too; a Claude account's is read by running Claude Code's own /usage": "今すぐ更新し、利用枠も読み込み直します。Claude アカウントの利用枠は Claude Code 自身の /usage を実行して読み取ります", + "{n} by magpie itself": "うち {n} 件は magpie 自身", + "first token in {ms} on average": "最初のトークンまで平均 {ms}", + "no streamed replies timed": "計測できたストリーミング応答なし", + "Sent, Effort and the cache are in each row's details": "ウィンドウが狭いため、送信したモデル・推論レベル・キャッシュは各行の詳細にあります", + "{n} output tokens in {ms} after the first": "最初のトークン後 {ms} で {n} トークンを出力", + "At least: {n} output tokens in {ms}, from the line that asked for it to its last. The session file has no first token, so the wait for it is counted too": "下限:要求した行から最後の行まで {ms} で {n} トークンを出力。セッションファイルには最初のトークンの時刻がないため、それを待つ時間も含まれます", + "At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too": "下限:最初のトークン後 {ms} で回答 {n} トークン(推論 {r} トークンは含めず)。セッションファイルには最初の本文の時刻がないため、最初のトークン後の推論の時間も含まれます", + "At least: {n} output tokens in {ms}, the whole turn. What came after the first token ({after}) is too little to time a speed by: under a second or under 100 tokens, so the wait for it is counted too": "下限:ターン全体の {ms} で {n} トークンを出力。最初のトークン後は {after} だけで、1 秒未満か 100 トークン未満のため速度を計れず、それを待つ時間も含まれます", + "The session file has no first token to time a speed from": "セッションファイルには、速度を計れる最初のトークンの時刻がありません", + "{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "最初の本文後 {ms} で回答 {n} トークン(その前の推論 {r} トークンは含めず)", + "Not streamed: no first token to time a speed from": "ストリーミングではないため、速度を計れる最初のトークンの時刻がありません", + "{i} in · {o} out · {r} cache read · {w} cache creation": "入力 {i} · 出力 {o} · キャッシュ読み取り {r} · キャッシュ作成 {w}", + "Upstream provider": "上流プロバイダー", + "The agent spoke {from}; sent upstream as {to}": "エージェントは {from} で要求し、上流へは {to} で送信", + "Sent upstream as {to}, as the agent spoke it": "エージェントと同じ {to} で上流へ送信", + }, + de: { + "Yesterday": "Gestern", + "This month": "Dieser Monat", + "Last month": "Letzter Monat", + "Pick days": "Tage wählen", + "Previous month": "Vorheriger Monat", + "Next month": "Nächster Monat", + "Days picked: {days}": "Gewählte Tage: {days}", + "Now the last day": "Jetzt den letzten Tag", + "Pick the first day, then the last": "Erst den ersten Tag, dann den letzten wählen", + "No calls on the days picked.": "An den gewählten Tagen keine Aufrufe.", + "All gateway keys": "Alle Zugangsschlüssel", + "All accounts": "Alle Konten", + "{agent} · on {computer}": "{agent} · auf {computer}", + "What was said stays on {computer}: sync shares the usage alone.": "Die Inhalte bleiben auf {computer}: Die Synchronisierung teilt nur die Nutzung.", + "Model · provider": "Modell · Anbieter", + "Not archived": "Nicht archiviert", + "Estimated using effective model prices, including custom prices": "Geschätzt mit effektiven Modellpreisen, einschließlich eigener Preise", + "Search models, providers, sessions": "Modelle, Anbieter, Sitzungen durchsuchen", + "Save every request listed, all pages, as a CSV file in Downloads": "Alle aufgeführten Anfragen aller Seiten als CSV-Datei unter „Downloads“ speichern", + "All agents": "Alle Agenten", + "{n} out": "{n} aus", + "{n} cache write": "{n} Cache-Schreiben", + "{n} cache read": "{n} Cache-Lesen", + "reported by apps": "von Apps gemeldet", + "Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie.": "Von der App gemeldet, die die Anfrage gestellt hat (POST /v1/magpie/usage/requests): Die Anfrage ging direkt an den Anbieter, nicht über magpie.", + "all requests": "alle Anfragen", + "Show only these requests": "Nur diese Anfragen zeigen", + "Show every request again": "Wieder alle Anfragen zeigen", + "View routing": "Weiterleitung anzeigen", + "Request: {what}": "Anfrage: {what}", + "Provider · account": "Anbieter · Konto", + "{m} for 5 minutes, {h} for an hour": "{m} für 5 Minuten, {h} für eine Stunde", + "session {id}": "Sitzung {id}", + "{agent} · via {host}": "{agent} · über {host}", + "Not kept for requests before this version": "Für Anfragen vor dieser Version nicht gespeichert", + "{n} reasoning, inside output": "{n} Reasoning, in der Ausgabe enthalten", + "No known price for this model": "Kein bekannter Preis für dieses Modell", + "Failed: the agent was answered {status}": "Fehlgeschlagen: Der Agent erhielt {status}", + "Error type": "Fehlertyp", + "Upstream said": "Upstream-Antwort", + "Data source": "Datenquelle", + "Nothing more was kept of this request": "Zu dieser Anfrage wurde nichts weiter gespeichert", + "OFFICIAL": "OFFIZIELL", + "No session was named with this request, so its session file can't be found": "Diese Anfrage nannte keine Sitzung, daher lässt sich ihre Sitzungsdatei nicht finden", + "magpie reads the session files of Claude Code, Claude Desktop and Codex only": "magpie liest nur die Sitzungsdateien von Claude Code, Claude Desktop und Codex", + "This request isn't in the agent's session files: they may be deleted, moved, or not written yet": "Diese Anfrage ist nicht in den Sitzungsdateien des Agenten: Die Dateien wurden eventuell gelöscht, verschoben oder noch nicht geschrieben", + "The session file couldn't be read": "Die Sitzungsdatei konnte nicht gelesen werden", + "Refresh every": "Aktualisieren alle", + "Updated {time}": "Aktualisiert {time}", + "Model recorded in the local session log; the outbound HTTP request was not captured.": "Modell laut lokalem Sitzungslog; die ausgehende HTTP-Anfrage wurde nicht erfasst.", + "About: told from the session file's times, a little more or less than it took": "Ungefähr: aus den Zeiten der Sitzungsdatei ermittelt, etwas mehr oder weniger als die tatsächliche Dauer", + "{n} call unpriced": "{n} Aufruf ohne Preis", + "{n} calls unpriced": "{n} Aufrufe ohne Preis", + "{n} model unpriced": "{n} Modell ohne Preis", + "{n} models unpriced": "{n} Modelle ohne Preis", + "Show only the requests answered on a retry": "Nur die nach erneutem Versuch beantworteten Anfragen zeigen", + "Show only the failed requests": "Nur die fehlgeschlagenen Anfragen zeigen", + "This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "Dieser Versuch schlug fehl, und die Anfrage ging an den nächsten weiter: Gezählt wird die Anfrage nach ihrem Ausgang, nicht nach diesem Versuch", + "{p} succeeded": "{p} erfolgreich", + "{a} cache": "{a} Cache", + "{a}–{b} of {n}": "{a}–{b} von {n}", + "Each request's tokens as its provider reported them; the cost estimated using effective model prices, including custom prices. Export CSV saves every page.": "Token jeder Anfrage laut Angabe des Anbieters; Kosten geschätzt mit effektiven Modellpreisen, einschließlich eigener Preise. „CSV exportieren“ speichert alle Seiten.", + "Saved {n} request to {path}": "{n} Anfrage unter {path} gespeichert", + "Saved {n} requests to {path}": "{n} Anfragen unter {path} gespeichert", + "Login method": "Anmeldemethode", + "Official login": "Offizielle Anmeldung", + "Duration colors: ≤10 s green · 10–30 s amber · >30 s red": "Farben der Dauer: ≤10 s grün · 10–30 s gelb · >30 s rot", + "Official login confirmed for this account by local login metadata. This does not establish the route or authentication used for this request.": "Offizielle Anmeldung für dieses Konto durch lokale Anmelde-Metadaten bestätigt. Weiterleitung oder Authentifizierung dieser Anfrage sind damit nicht belegt.", + "API price reference": "API-Preisreferenz", + "Price reference: {model}": "Preisreferenz: {model}", + "Model used for the API price estimate; this is not an observed model forwarding event.": "Für die API-Preisschätzung verwendetes Modell; keine beobachtete Weiterleitung an ein Modell.", + "Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred.": "Aus der Sitzungsdatei des Agenten gelesen. Das Konto wird nur angezeigt, wenn lokale Metadaten es identifizieren; ein Dienstanbieter wird nicht abgeleitet.", + "Read from the agent's session file, which names the provider it was set up to call. The name shown is that record, not a route magpie saw.": "Aus der Sitzungsdatei des Agenten gelesen, die den Anbieter nennt, für den er eingerichtet wurde. Der angezeigte Name ist diese Aufzeichnung, keine von magpie gesehene Route.", + "Session account": "Sitzungskonto", + "Gateway calls only; session-log calls are in Requests. Local rejections are excluded from totals.": "Nur Aufrufe über den Zugangspunkt; Aufrufe aus Sitzungslogs stehen unter „Anfragen“. Lokale Ablehnungen sind nicht in den Summen enthalten.", + "at effective prices": "zu effektiven Preisen", + "Reading the agents' session files…": "Sitzungsdateien der Agenten werden gelesen…", + "Totals count native sessions and gateway requests with a session ID": "Summen zählen lokale Sitzungen und Gateway-Anfragen mit Sitzungs-ID", + "showing {drawn} of {n}": "{drawn} von {n} angezeigt", + "All folders": "Alle Ordner", + "Indexing your sessions": "Ihre Sitzungen werden indiziert", + "Looking for session files…": "Sitzungsdateien werden gesucht…", + "Reading the kept index…": "Gespeicherter Index wird gelesen…", + "Indexed · putting the page together…": "Indiziert · Seite wird aufgebaut…", + "{done} of {files} files · {read} of {bytes}": "{done} von {files} Dateien · {read} von {bytes}", + "about {t} left": "noch etwa {t}", + "Read once, kept: after this the page opens from the index in a blink": "Einmal gelesen, dauerhaft gespeichert: Danach öffnet sich die Seite blitzschnell aus dem Index", + "Only what changed is read again, from where it was left": "Nur Änderungen werden erneut gelesen, ab der letzten Stelle", + "Every session is read on this computer; nothing leaves it": "Jede Sitzung wird auf diesem Computer gelesen; nichts verlässt ihn", + "The biggest files go first, so none is left running on alone": "Die größten Dateien zuerst, damit keine am Ende allein weiterläuft", + "Nothing in this range.": "Nichts in diesem Zeitraum.", + "Usage heatmap": "Nutzungs-Heatmap", + "Daily usage over the last 53 weeks": "Tägliche Nutzung der letzten 53 Wochen", + "{d} active": "{d} aktiv", + "Latest sessions": "Neueste Sitzungen", + "Open in Sessions": "In „Sitzungen“ öffnen", + "Top sessions": "Top-Sitzungen", + "Session shape": "Sitzungsprofil", + "{r}m": "{r} Min.", + "{r} messages": "{r} Nachrichten", + "{r} minutes at work": "{r} Minuten aktiv", + "{r} tool calls a prompt": "{r} Tool-Aufrufe pro Prompt", + "Across: {axis} · Height: sessions": "Horizontal: {axis} · Höhe: Sitzungen", + "messages in a session, prompts and replies": "Nachrichten einer Sitzung, Prompts und Antworten", + "minutes a session was at work": "Minuten, die eine Sitzung aktiv war", + "tool calls the agent made on its own for each prompt": "Tool-Aufrufe, die der Agent pro Prompt selbstständig ausführte", + "No tool calls in this range.": "Keine Tool-Aufrufe in diesem Zeitraum.", + "Top skills": "Top-Skills", + "No skill was called up in this range.": "In diesem Zeitraum wurde kein Skill aufgerufen.", + "last {when}": "zuletzt {when}", + "By hour": "Nach Stunde", + "Still counting": "Wird noch gezählt", + "days at work": "aktive Tage", + "longest streak": "längste Serie", + "busiest day": "aktivster Tag", + "Reading the session…": "Sitzung wird gelesen…", + "Click to show only this": "Klicken, um nur dies anzuzeigen", + "Click again to show every one": "Erneut klicken, um alle anzuzeigen", + "median {m} · p90 {p}": "Median {m} · p90 {p}", + "{p} in {name}": "{p} in {name}", + "Busiest at {when}": "Am aktivsten: {when}", + "Active time isn't kept by model.": "Die aktive Zeit wird nicht pro Modell erfasst.", + "No active time in this range.": "Keine aktive Zeit in diesem Zeitraum.", + "Tokens in and out per session: the middle session's, and what nine in ten stay under": "Ein- und Ausgabe-Token pro Sitzung: der Median und der Wert, den neun von zehn Sitzungen nicht überschreiten", + "on {n} day": "an {n} Tag", + "on {n} days": "an {n} Tagen", + "The time the sessions were at work: the pauses between one message and the next, each under five minutes": "Die aktive Zeit der Sitzungen: die Pausen zwischen zwei Nachrichten, jeweils unter fünf Minuten", + "{m}m": "{m} Min.", + "{h}h {m}m": "{h} Std. {m} Min.", + "By day": "Pro Tag", + "By week": "Pro Woche", + "{when} · {tokens} tokens": "{when} · {tokens} Token", + "No known price for {models}": "Kein bekannter Preis für {models}", + "Not counted: {models}, with no known price": "Nicht gezählt: {models}, ohne bekannten Preis", + "No calls today.": "Heute keine Aufrufe.", + "No calls in the last 7 days.": "Keine Aufrufe in den letzten 7 Tagen.", + "No calls in the last 30 days.": "Keine Aufrufe in den letzten 30 Tagen.", + "No calls yet.": "Noch keine Aufrufe.", + "Point an agent at a catalog model and use it; every call through the gateway is counted here.": "Richten Sie einen Agenten auf ein Katalogmodell aus und nutzen Sie ihn; jeder Aufruf über den Zugangspunkt wird hier gezählt.", + "inside output": "in der Ausgabe enthalten", + "{when} · {tokens} tokens · {n} call": "{when} · {tokens} Token · {n} Aufruf", + "{when} · {tokens} tokens · {n} calls": "{when} · {tokens} Token · {n} Aufrufe", + "{n}% of tokens": "{n} % der Token", + "Counted from the providers' own usage reports on every call through the gateway · {path}": "Gezählt aus den Nutzungsangaben der Anbieter bei jedem Aufruf über den Zugangspunkt · {path}", + "Hide from this list": "In dieser Liste ausblenden", + "Count as an agent…": "Als Agent zählen…", + "Count {client} on its own": "{client} wieder einzeln zählen", + "with {clients}": "mit {clients}", + "Count this client's calls as": "Aufrufe dieses Clients zählen als", + "{client} is counted as {agent}": "{client} wird als {agent} gezählt", + "{client} is counted on its own": "{client} wird einzeln gezählt", + "Actions for {name}": "Aktionen für {name}", + "Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "Nur in dieser Liste ausgeblendet: Ihre Aufrufe zählen weiter in den Summen und im Diagramm. Klicken, um sie zu sehen.", + "Vendor's first token": "Erstes Token des Anbieters", + "Tries that failed first": "Zuvor fehlgeschlagene Versuche", + "Waiting for a slot": "Warten auf einen freien Platz", + "Connecting and sending": "Verbinden und Senden", + "Refresh now, the allowances too; a Claude account's is read by running Claude Code's own /usage": "Jetzt aktualisieren, auch die Kontingente; das eines Claude-Kontos wird über das eigene /usage von Claude Code gelesen", + "{n} by magpie itself": "{n} von magpie selbst", + "first token in {ms} on average": "erstes Token im Schnitt nach {ms}", + "no streamed replies timed": "keine gestreamte Antwort gemessen", + "Sent, Effort and the cache are in each row's details": "Schmales Fenster: Gesendet, Effort und Cache stehen in den Details jeder Zeile", + "{n} output tokens in {ms} after the first": "{n} Ausgabe-Token in {ms} nach dem ersten", + "At least: {n} output tokens in {ms}, from the line that asked for it to its last. The session file has no first token, so the wait for it is counted too": "Mindestens: {n} Ausgabe-Token in {ms}, von der Zeile, die sie anforderte, bis zu ihrer letzten. Die Sitzungsdatei hat kein erstes Token, also zählt das Warten darauf mit", + "At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too": "Mindestens: {n} Antwort-Token in {ms} nach dem ersten Token, ohne die {r} Reasoning-Token. Die Sitzungsdatei hat keinen ersten Text, also zählt Reasoning nach dem ersten Token mit", + "At least: {n} output tokens in {ms}, the whole turn. What came after the first token ({after}) is too little to time a speed by: under a second or under 100 tokens, so the wait for it is counted too": "Mindestens: {n} Ausgabe-Token in {ms}, der ganze Turn. Nach dem ersten Token kam nur {after}, unter einer Sekunde oder unter 100 Token, zu wenig für ein Tempo, also zählt das Warten darauf mit", + "The session file has no first token to time a speed from": "Die Sitzungsdatei hat kein erstes Token, an dem sich ein Tempo messen ließe", + "{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "{n} Antwort-Token in {ms} nach dem ersten Text, ohne die {r} Reasoning-Token davor", + "Not streamed: no first token to time a speed from": "Nicht gestreamt: kein erstes Token, an dem sich ein Tempo messen ließe", + "{i} in · {o} out · {r} cache read · {w} cache creation": "{i} Eingabe · {o} Ausgabe · {r} Cache-Lesen · {w} Cache-Erstellung", + "Upstream provider": "Upstream-Anbieter", + "The agent spoke {from}; sent upstream as {to}": "Der Agent sprach {from}; an den Upstream als {to} gesendet", + "Sent upstream as {to}, as the agent spoke it": "An den Upstream als {to} gesendet, wie der Agent es sprach", + }, +}); diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js new file mode 100644 index 000000000..5219c861b --- /dev/null +++ b/internal/gui/assets/plugins/usage/page.js @@ -0,0 +1,3061 @@ +// The Usage page's code (client.js has its markup and hooks): run after +// app.js, whose helpers and state it shares, and before start.js shows the +// first page. +const PERIODS = [["today", "Today"], ["7d", "7 days"], ["30d", "30 days"], ["all", "All"]]; + +// asked: the reader opened the page, so a Claude account's usage is read +// at once, by running Claude Code's own /usage, rather than when its last +// reading is due (every 5 to 15 minutes, at random, once Claude Code was used). +// The Overview's reads share one count: only the newest draws, and only for the +// period and tab the page is on, whether a pick or the timer asked for it. +let usageRead = 0; +async function loadUsage(asked) { + renderUsageTab(); + renderUsageEvery(); // the refresh's tooltip says what it reads on this tab + if (asked) quotasOpened(); + if (usageTab === "sessions") return loadSessions(); + if (usageTab === "requests") return loadLedger(); + if (usageTab === "context") return window.loadContext?.(); + renderUsageLoading(); + if (!asked) loadQuotas(); + const p = period, read = ++usageRead; + const next = await api("usage?period=" + encodeURIComponent(p)); + if (read !== usageRead || view !== "usage" || usageTab !== "usage" || period !== p) return; + usage = next; + renderUsage(); +} + +// the period picker, in the page's head, for the Overview and Requests +function renderPeriod(loading) { + const seg = $("#period"); + seg.replaceChildren(); + for (const [id, name] of PERIODS) { + const b = el("button", "opt" + (id === period ? " on" : ""), t(name)); + b.disabled = !!loading; + b.onclick = () => { for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b); slide(seg, "period"); pickPeriod(id); }; + seg.append(b); + } + // days of the reader's own (#1492): the last opt names them once picked, + // and opens the range menu to pick them, or others + const range = periodDays(period); + const b = el("button", "opt range-opt" + (range ? " on" : "")); + b.type = "button"; + b.disabled = !!loading; + b.setAttribute("aria-haspopup", "dialog"); + b.setAttribute("aria-expanded", "false"); + b.setAttribute("aria-label", range ? t("Days picked: {days}", { days: rangeName(range) }) : t("Pick days")); + b.append(svg("M3 4.5h10v8.5H3zM3 7h10M5.5 3v3M10.5 3v3", 12, 1.4), el("span", "", range ? rangeName(range) : t("Custom"))); + if (range) b.title = t("Days picked: {days}", { days: rangeName(range) }); + b.onclick = () => { + if (b.classList.contains("open")) return closeProtoMenu(); + openRangeMenu(b, range, (from, to) => { + for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b); + b.lastChild.textContent = rangeName({ from, to }); + b.title = t("Days picked: {days}", { days: rangeName({ from, to }) }); + b.setAttribute("aria-label", b.title); + slide(seg, "period"); + pickPeriod(from + ".." + to); + }); + }; + seg.append(b); + slide(seg, "period"); +} + +function pickPeriod(id) { + period = id; ledDay = ""; ledOffset = 0; + loadUsage().catch((e) => status(e.message, "err")); +} + +const dayKeyOf = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; +// rangeName says picked days short: "Oct 1 – Oct 7", the year only when it +// isn't this one, one day alone as itself +function rangeName({ from, to }) { + const year = new Date().getFullYear(); + const name = (k) => dayOfKey(k).toLocaleDateString(intlLang(), { month: "short", day: "numeric", ...(dayOfKey(k).getFullYear() !== year ? { year: "numeric" } : {}) }); + return from === to ? name(from) : name(from) + " – " + name(to); +} +// noCallsIn is what an empty page says of the period it is on +function noCallsIn(p) { + if (periodDays(p)) return "No calls on the days picked."; + return { today: "No calls today.", "7d": "No calls in the last 7 days.", "30d": "No calls in the last 30 days.", all: "No calls yet." }[p] || "No calls yet."; +} + +// openRangeMenu is the app's own menu for picking days (#1492): a few +// spans a click away, and a month to pick the first day on, then the last. +// Days after today can't be picked. choose gets the two days, in order. +function openRangeMenu(anchor, current, choose) { + closeProtoMenu(); + const today = dayKeyOf(new Date()); + let start = null; // the first day clicked, waiting for the last + let shown = dayOfKey(current?.to || today); + shown = new Date(shown.getFullYear(), shown.getMonth(), 1, 12); + const box = el("div", "pop proto-menu range-menu"); + box.setAttribute("role", "dialog"); + box.setAttribute("aria-label", t("Pick days")); + const head = el("div", "pm-head"); + const quick = el("div", "rm-quick"); + const span = (from, to) => ({ from: dayKeyOf(from), to: dayKeyOf(to) }); + const now = new Date(); + now.setHours(12, 0, 0, 0); + const back = (n) => { const d = new Date(now); d.setDate(d.getDate() - n); return d; }; + const quicks = [ + ["Yesterday", span(back(1), back(1))], + ["This month", span(new Date(now.getFullYear(), now.getMonth(), 1, 12), now)], + ["Last month", span(new Date(now.getFullYear(), now.getMonth() - 1, 1, 12), new Date(now.getFullYear(), now.getMonth(), 0, 12))], + ["90 days", span(back(89), now)], + ]; + for (const [name, r] of quicks) { + const b = el("button", "rm-span" + (current && current.from === r.from && current.to === r.to ? " on" : ""), t(name)); + b.type = "button"; + b.title = rangeName(r); + b.onclick = (e) => { e.stopPropagation(); closeProtoMenu(); choose(r.from, r.to); }; + quick.append(b); + } + const nav = el("div", "rm-nav"); + const prev = el("button", "rm-step"), next = el("button", "rm-step"), month = el("span", "rm-month"); + prev.type = next.type = "button"; + prev.setAttribute("aria-label", t("Previous month")); + next.setAttribute("aria-label", t("Next month")); + prev.append(svg("M10 4 6 8l4 4", 12, 1.6)); + next.append(svg("m6 4 4 4-4 4", 12, 1.6)); + nav.append(prev, month, next); + const grid = el("div", "rm-grid"); + grid.setAttribute("role", "grid"); + box.append(head, quick, nav, grid); + const draw = (focusDay) => { + head.textContent = start ? t("Now the last day") : t("Pick the first day, then the last"); + month.textContent = shown.toLocaleDateString(intlLang(), { year: "numeric", month: "long" }); + next.disabled = dayKeyOf(new Date(shown.getFullYear(), shown.getMonth() + 1, 1, 12)) > today; + const cells = []; + // the weekdays, Monday first, as the app's weeks are + for (let i = 0; i < 7; i++) cells.push(el("span", "rm-wd", new Date(2024, 0, 1 + i, 12).toLocaleDateString(intlLang(), { weekday: "narrow" }))); + const first = new Date(shown); + const lead = (first.getDay() + 6) % 7; + for (let i = 0; i < lead; i++) cells.push(el("span", "rm-pad")); + const lo = start || current?.from, hi = start ? null : current?.to; + for (let d = new Date(first); d.getMonth() === shown.getMonth(); d.setDate(d.getDate() + 1)) { + const k = dayKeyOf(d); + const b = el("button", "rm-day", String(d.getDate())); + b.type = "button"; + b.dataset.day = k; + b.setAttribute("aria-label", d.toLocaleDateString(intlLang(), { year: "numeric", month: "long", day: "numeric" })); + if (k === today) b.classList.add("today"); + if (lo && (k === lo || k === hi)) b.classList.add("end"); + if (lo && hi && k > lo && k < hi) b.classList.add("in"); + b.disabled = k > today; + b.onclick = (e) => { + e.stopPropagation(); + if (!start) { start = k; draw(k); return; } + const [from, to] = start <= k ? [start, k] : [k, start]; + closeProtoMenu(); + choose(from, to); + }; + cells.push(b); + } + grid.replaceChildren(...cells); + (focusDay && grid.querySelector(`[data-day="${focusDay}"]`))?.focus({ preventScroll: true }); + }; + const turn = (by) => (e) => { e.stopPropagation(); shown = new Date(shown.getFullYear(), shown.getMonth() + by, 1, 12); draw(); }; + prev.onclick = turn(-1); + next.onclick = turn(1); + draw(); + document.body.append(box); + placeMenu(box, anchor); + anchor.classList.add("open"); + anchor.setAttribute("aria-expanded", "true"); + const outside = (e) => { if (!box.contains(e.target) && !anchor.contains(e.target)) closeProtoMenu(); }; + const scroll = (e) => { if (scrollCloses(box, e)) closeProtoMenu(); }; + // Escape closes; arrows walk the days, a week up or down + const keys = (e) => { + if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeProtoMenu(); anchor.focus({ preventScroll: true }); return; } + const at = document.activeElement?.dataset?.day; + const by = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 }[e.key]; + if (!at || !by || !box.contains(document.activeElement)) return; + e.preventDefault(); e.stopPropagation(); + const d = dayOfKey(at); + d.setDate(d.getDate() + by); + const k = dayKeyOf(d); + if (k > today) return; + if (d.getMonth() !== shown.getMonth() || d.getFullYear() !== shown.getFullYear()) shown = new Date(d.getFullYear(), d.getMonth(), 1, 12); + draw(k); + }; + document.addEventListener("mousedown", outside, true); + document.addEventListener("keydown", keys, true); + document.addEventListener("scroll", scroll, true); + addEventListener("resize", closeProtoMenu); + protoMenu = { box, anchor, outside, keys, scroll, done: null }; + (grid.querySelector(".rm-day.end") || grid.querySelector(".rm-day.today") || quick.firstChild).focus({ preventScroll: true }); +} + +function renderUsageLoading() { + const view = $("#view-usage"); + view.classList.add("loading"); + view.setAttribute("aria-busy", "true"); + renderPeriod(true); + $("#usageCost").replaceChildren(el("span", "skeleton sk-cost")); + renderQuotas(); + const stats = $("#stats"); + stats.classList.remove("empty"); + stats.replaceChildren(); + for (let i = 0; i < 4; i++) { + const tile = el("div", "kpi loading-kpi"); + tile.append(el("span", "skeleton sk-number"), el("span", "skeleton sk-label")); + stats.append(tile); + } + $("#chart").hidden = true; + for (const id of ["usageAgents", "usageAgentsHid", "usageModels", "usageKeys"]) $("#" + id).hidden = true; + // the allowances' head is renderQuotas' alone: the quotas it heads are + // still there while the period loads (#809, Hu9956: 用量界面红框这行会延迟几秒才会出现) + for (const h of $$("#view-usage .row-head:not(#quotaHead)")) h.hidden = true; + $("#usageNote").textContent = ""; +} + +// costHead is the Usage head's sum: the cost at effective prices, or, when +// some of what it sums has no known price, how many beside it (#1856) — a +// total never reads as if those cost nothing — and with none priced, the +// count alone. note is that count in words ("" when everything was +// priced), title the tooltip. +function costHead(c, note, title) { + const cost = $("#usageCost"); + cost.replaceChildren(); + cost.title = ""; + if (!c && !note) return; + if (c) cost.append(el("b", "", "≈" + c)); + cost.append(el("span", note ? "unpriced" : "", note || t("effective prices"))); + cost.title = title; +} +const unpricedCalls = (n) => t(n === 1 ? "{n} call unpriced" : "{n} calls unpriced", { n: ledNum(n) }); +const unpricedCallsWhy = (n) => n ? t(n === 1 ? "{n} call had no known price and is not counted" : "{n} calls had no known price and are not counted", { n }) : t("Estimated using effective model prices, including custom prices"); +// renderCosts redraws whatever on the Usage page shows a cost, once the +// currency changes — the numbers alone, not the page around them, so a +// click on the setting never moves anything it isn't showing (#212) +function renderCosts() { + if (usage) renderUsage(); + if (ledger && usageTab === "requests") renderLedger(); + if (sessions) renderSessions(); + document.dispatchEvent(new Event("magpie-costs-changed")); +} +// quotaWho is how an account's card names it (#1515): by the name the user +// gave it, the account beside it, else the account; and the key plan it +// stands in for (seat) when that isn't already its name. A team's GLM +// seats read as the user tells them apart, not as 31****36@qq.com. +function quotaWho(q) { + const out = []; + if (q.alias) { + const a = el("span", "user quota-alias", q.alias); + a.title = q.user ? q.alias + " · " + q.user : q.alias; + out.push(a); + if (q.user) { + const u = el("span", "quota-of", q.user); + u.title = q.user; + out.push(u); + } + } else if (q.user) { + const u = el("span", "user", q.user); + u.title = q.user; + out.push(u); + } + if (q.seat && q.seat !== q.alias) { + const s = el("span", "quota-seat", "≡ " + q.seat); + s.title = t("The same seat as the key plan {name}, shown once, on this account's card", { name: q.seat }); + out.push(s); + } else if (q.seat) out[0].title += "\n" + t("The same seat as the key plan {name}, shown once, on this account's card", { name: q.seat }); + return out; +} + +function ownCalls(n) { + return t("{n} by magpie itself", { n: fmtN(n) }); +} +// quotaReadings: a line's last eight readings, newest first, each what was +// left and when it was read (#802), a line each, ↻ where the window +// started again; for its legend key's title +function quotaReadings(l, now) { + const pts = l.points.slice(-8); + return pts.map((p, i) => (i > 0 && quotaCycleBreak(pts[i - 1], p) ? "↻ " : "") + Math.round(p.left) + "% · " + quotaTimeText(p.at, now)).reverse(); +} +// Keep the last date and as many earlier dates as fit, without clipping their +// text. Visibility keeps each label aligned to its bar; resizing restores them. +function fitChartLabels() { + const narrow = web && matchMedia("(max-width: 760px), (pointer: coarse) and (max-width: 1024px)").matches; + for (const labels of document.querySelectorAll(".chart .labels")) { + const spans = [...labels.children]; + for (const span of spans) span.style.visibility = ""; + if (!narrow || !labels.offsetWidth) continue; + const box = labels.getBoundingClientRect(); + let right = box.right + 8; + for (const span of spans.reverse()) { + if (!span.textContent) continue; + const range = document.createRange(); + range.selectNodeContents(span); + const r = range.getBoundingClientRect(); + if (r.right + 8 > right + 1 || r.left < box.left - 1) span.style.visibility = "hidden"; + else right = r.left; + } + } +} +new ResizeObserver(fitChartLabels).observe($("#view-usage")); + +function renderUsage() { + const u = usage; + const view = $("#view-usage"); + view.classList.remove("loading"); + view.removeAttribute("aria-busy"); + renderPeriod(); + costHead(fmtCost(u), u.unpriced ? unpricedCalls(u.unpriced) : "", unpricedCallsWhy(u.unpriced)); + + const stats = $("#stats"); + stats.replaceChildren(); + const empty = !u.calls; + $("#chart").hidden = empty; + for (const id of ["usageAgents", "usageModels"]) $("#" + id).hidden = empty; + if (empty) $("#usageAgentsHid").hidden = true; + for (const h of $$("#view-usage .row-head:not(#quotaHead)")) h.hidden = empty; + $("#usageKeysHead").hidden = $("#usageKeys").hidden = empty || !u.callerKeys?.length; + // each subscription account's share, by the account that answered (#557) + $("#usageAccountsHead").hidden = $("#usageAccounts").hidden = empty || !u.accounts?.length; + if (empty) { + stats.classList.add("empty"); + const none = noCallsIn(period); + stats.append(el("div", "none", t(none) + " " + t("Point an agent at a catalog model and use it; every call through the gateway is counted here."))); + $("#usageNote").textContent = ""; + return; + } + stats.classList.remove("empty"); + const tile = (n, label, sub, title) => { + const t = el("div", "kpi"); + if (title) t.title = title; + t.append(el("b", "", n), el("span", "", label)); + if (sub) t.append(el("small", "", sub)); + stats.append(t); + }; + tile(fmtN(tokensOf(u)), t("tokens"), t("{a} in · {b} out", { a: fmtN(u.input), b: fmtN(u.output) })); + // cache reads are billed at a fraction of input, so how much of the prompt + // came from cache is the number that explains the bill; input here already + // excludes the cached tokens, read and written (the gateway subtracts + // them), so what was written counts in the prompt too: left out, a prompt + // written to the cache again at every turn showed a rate near 100%. The + // written count is secondary and only fits in the tooltip. + const promptTokens = u.input + u.cache_read + u.cache_write; + const hit = u.cache_read && promptTokens ? t("hit rate {p}", { p: Math.round(100 * u.cache_read / promptTokens) + "%" }) : ""; + tile(fmtN(u.cache_read), t("cache read"), hit, u.cache_write ? t("{n} written", { n: fmtN(u.cache_write) }) + cacheTTLs(u, fmtN) : ""); + tile(fmtN(u.reasoning), t("reasoning"), t("inside output")); + tile(String(u.calls), t(u.calls === 1 ? "call" : "calls"), [u.errors ? t("{n} failed", { n: u.errors }) : "", u.retried ? t("{n} answered on a retry", { n: u.retried }) : "", u.unpriced ? t("{n} unpriced", { n: u.unpriced }) : ""].filter(Boolean).join(" · "), u.unpriced ? unpricedCallsWhy(u.unpriced) : ""); + + // the timeline: one bar per hour, day or week; output sits on top of input + const chart = $("#chart"); + chart.replaceChildren(); + const bars = el("div", "bars"); + const peak = Math.max(1, ...u.series.map(tokensOf)); + const labels = el("div", "labels"); + const n = u.series.length; + const every = n <= 8 ? 1 : n <= 31 ? Math.ceil(n / 6) : Math.ceil(n / 5); + // the day in the reader's language (the label comes as "Sep 5" in every one) + const dayOf = (p) => u.bucket === "hour" || !p.time ? p.label : new Date(p.time).toLocaleDateString(intlLang(), { month: "short", day: "numeric" }); + u.series.forEach((p, i) => { + const b = el("div", "bar"); + const inp = el("i", "in"), out = el("i", "out"); + inp.style.height = (100 * p.input / peak).toFixed(1) + "%"; + out.style.height = (100 * p.output / peak).toFixed(1) + "%"; + b.append(out, inp); + const when = u.bucket === "hour" ? `${p.label}:00` : u.bucket === "week" ? t("week of {label}", { label: dayOf(p) }) : dayOf(p); + b.title = p.calls ? t(p.calls === 1 ? "{when} · {tokens} tokens · {n} call" : "{when} · {tokens} tokens · {n} calls", { when, tokens: fmtN(tokensOf(p)), n: p.calls }) + (fmtCost(p) ? " · ≈" + fmtCost(p) : "") : t("{when} · nothing", { when }); + bars.append(b); + const last = i === n - 1 && (n - 1) % every >= every / 2; + labels.append(el("span", "", i % every === 0 || last ? dayOf(p) : "")); + }); + chart.append(el("div", "peak", fmtN(peak)), bars, labels); + fitChartLabels(); + + const total = Math.max(1, tokensOf(u)); + const list = (id, groups, act) => { + const box = typeof id === "string" ? $("#" + id) : id; + box.replaceChildren(); + for (const g of groups) { + const r = el("div", "row stat"); + r.dataset.id = g.id || ""; + r.append(icon(g.icon || "generic")); + const who = el("div", "who"); + who.append(el("div", "name" + (g.name ? "" : " faint"), g.name || t("account not recorded"))); + const sub = []; + if (g.sub) sub.push(g.sub); + sub.push(t(g.calls === 1 ? "{n} call" : "{n} calls", { n: g.calls })); + // magpie's own calls apart from the agents' (#1839): magpie's row + // says it is, and a model's, a key's or an account's how many of + // its calls were + if (id === "usageAgents" && g.id === "magpie") who.firstChild.append(ownBadge()); + else if (g.own?.calls) sub.push(ownCalls(g.own.calls)); + if (g.errors) sub.push(t("{n} failed", { n: g.errors })); + // of those, the replies magpie ended stuck in a loop (#1858) + if (g.loops) sub.push(t("{n} looped", { n: g.loops })); + if (g.retried) sub.push(t("{n} answered on a retry", { n: g.retried })); + // how long the streamed replies took to begin, and how fast they + // wrote after (#196) + if (g.timed) { + sub.push(t("TTFT {ms}", { ms: ledTook(Math.round(g.ttft_ms / g.timed)) })); + } + const gs = ledGroupSpeed(g); + if (gs) sub.push(gs.text); + const subLine = el("div", "sub", sub.join(" · ")); + if (g.own?.calls) subLine.title = ownWhy(); + who.append(subLine); + r.append(who); + const share = el("div", "share"); + const fill = el("i"); + fill.style.width = Math.max(1.5, 100 * tokensOf(g) / total).toFixed(1) + "%"; + share.append(fill); + share.title = t("{n}% of tokens", { n: Math.round(100 * tokensOf(g) / total) }); + r.append(share); + const num = el("div", "num"); + // how much of its prompt came from the cache, counted as the cache + // read tile counts it (#925) + const prompt = g.input + g.cache_read + (g.cache_write || 0); + const hit = g.cache_read && prompt ? " · " + t("hit rate {p}", { p: Math.round(100 * g.cache_read / prompt) + "%" }) : ""; + num.append(el("b", "", fmtN(tokensOf(g))), el("small", "", t("{a} in · {b} out", { a: fmtN(g.input), b: fmtN(g.output) }) + (g.cache_read ? " · " + t("{n} cached", { n: fmtN(g.cache_read) }) : "") + hit)); + r.append(num); + r.append(el("div", "cost", fmtCost(g) ? "≈" + fmtCost(g) : "")); + if (act) act(r, g); + box.append(r); + } + }; + // a client hidden from the Agents list (ikunbots on X: curl, + // Go-http-client, python-httpx beside the agents in use) is left out of + // it, and only of it: the totals, the chart and every share above still + // count its calls. One line under the list says how many, and opens them. + const hid = new Set(state.settings?.usageAgentsHidden || []); + const hidden = u.agents.filter((g) => hid.has(g.id)); + list("usageAgents", u.agents.filter((g) => !hid.has(g.id)), (r, g) => { + r.classList.add("acts"); + const b = el("button", "icon us-more"); + b.type = "button"; + b.setAttribute("aria-haspopup", "menu"); + b.setAttribute("aria-label", t("Actions for {name}", { name: g.name || g.id })); + b.append(svg(DOTS, 14, 2.2)); + // a client magpie doesn't know can be counted as one of the agents + // it does (#1958, NorethSea): a bridge that starts Codex under a name + // of its own; the agent counting one has it put back on its own + const counted = Object.entries(state.settings?.clientAgents || {}).filter(([, as]) => as === g.id).map(([c]) => c); + const menu = () => { + const again = agentMenu?.anchor === b; + closeAgentMenu(); + if (again) return; + openRowMenu(b, [ + ...(countable(g.id) ? [{ name: "Count as an agent…", icon: COUNT_AS, run: () => pickCountAs(b, g) }] : []), + ...counted.map((c) => ({ name: t("Count {client} on its own", { client: c }), icon: OUT, run: () => countClientAs(c, "") })), + { name: "Hide from this list", icon: EYE_OFF, sep: countable(g.id) || counted.length > 0, run: () => hideUsageAgent(g.id, true) }, + ]); + }; + if (counted.length) { + const sub = r.querySelector(".who .sub"); + sub.textContent = t("with {clients}", { clients: counted.join(", ") }) + " · " + sub.textContent; + } + b.onclick = (e) => { e.stopPropagation(); menu(); }; + r.oncontextmenu = (e) => { e.preventDefault(); menu(); }; + r.querySelector(".share").after(b); + }); + const hb = $("#usageAgentsHid"); + hb.hidden = !hidden.length; + if (!hidden.length) usageHidOpen = false; + const line = hb.querySelector(".us-hidline"), hl = hb.querySelector(".list"); + line.replaceChildren(el("span", "", t("{n} hidden", { n: hidden.length })), svg(CHEV, 11, 1.6)); + line.title = t("Hidden from this list only: their calls still count in the totals and the chart. Click to see them."); + line.setAttribute("aria-expanded", String(usageHidOpen)); + line.onclick = () => { usageHidOpen = !usageHidOpen; renderUsage(); }; + hl.hidden = !usageHidOpen; + list(hl, usageHidOpen ? hidden : [], (r, g) => { + r.classList.add("hid", "acts"); + const b = el("button", "text us-unhide", t("Unhide")); + b.type = "button"; + b.onclick = (e) => { e.stopPropagation(); hideUsageAgent(g.id, false); }; + r.append(b); + }); + list("usageModels", u.models); + list("usageAccounts", u.accounts || []); + list("usageKeys", u.callerKeys || []); + $("#usageNote").textContent = t("Counted from the providers' own usage reports on every call through the gateway · {path}", { path: u.path }); + // the account cards say how many of this period's requests were + // magpie's own (ownLine), which they could only once the summary came + if (quotas && (u.accounts?.some((g) => g.own?.calls) || $("#subscriptionUsage .quota-own"))) renderQuotas(); +} + +// countable is whether the Usage page's Agents list offers to count a +// client as an agent: one magpie doesn't know, not magpie's own (#1839) +// nor the calls that named no client. +const COUNT_AS = "M3 3v3.5A3.5 3.5 0 0 0 6.5 10H13M10 7l3 3-3 3"; +function countable(id) { + return !!id && id !== "other" && !/^magpie/i.test(id) && !(state.clients || []).some((a) => a.id === id); +} +// pickCountAs opens the agents a client can be counted as, under its menu +// button. +function pickCountAs(anchor, g) { + const opts = (state.clients || []).filter((a) => a.id !== "magpie").map((a) => ({ v: a.id, name: a.name, literalName: true, note: "" })); + openProtoMenu(anchor, opts, "", (v) => countClientAs(g.id, v), "Count this client's calls as", "", "left", false, opts.length > 8 ? "Search agents…" : ""); +} +// countClientAs counts a client's calls as an agent's on the Usage and +// Sessions pages, or on its own again (as ""), and draws the page again +// from the ledger read anew: the history is counted the new way too. +async function countClientAs(client, as) { + try { + const s = await api("usage/arrange", { count: { client, as } }); + state.settings = { ...state.settings, clientAgents: s.clientAgents || {} }; + status(as ? t("{client} is counted as {agent}", { client, agent: (state.clients || []).find((a) => a.id === as)?.name || as }) : t("{client} is counted on its own", { client }), "ok"); + await loadUsage(); + } catch (e) { + status(e.message, "err"); + } +} + +// hideUsageAgent takes a client out of the Usage page's Agents list, or +// puts it back: drawn at once, put back if the save fails. Its calls stay +// in the ledger and in every total. +async function hideUsageAgent(id, hide) { + const prev = state.settings || {}; + const cur = (prev.usageAgentsHidden || []).filter((k) => k !== id); + const agentsHidden = hide ? [...cur, id] : cur; + state.settings = { ...prev, usageAgentsHidden: agentsHidden }; + const again = () => { + if (!usage) return; + renderUsage(); + // the focus stays on the list: the row put back, else the hidden line + const to = hide ? $("#usageAgentsHid .us-hidline") : $(`#usageAgents .row.stat[data-id="${CSS.escape(id)}"] .us-more`); + (to && !to.closest("[hidden]") ? to : null)?.focus({ preventScroll: true }); + }; + again(); + try { + const s = await api("usage/arrange", { agentsHidden }); + state.settings = { ...state.settings, usageAgentsHidden: s.usageAgentsHidden || [] }; + } catch (e) { + state.settings = prev; + again(); + status(e.message, "err"); + } +} + +// ---------- requests ---------- +// +// The ledger: every request of the period, one row each, newest first — +// what the agent asked for, where it went, the model sent and the one the +// reply says answered, the tokens, what they cost at effective prices, how long +// it took and how it ended — to set beside a vendor's own bill. The +// server pages it (/api/usage/requests) and saves it whole as CSV. + +let ledger = null; // the page shown: { rows, offset, total, agents, …totals } +let ledOffset = 0, ledPurpose = "", ledAgent = "", ledProvider = "", ledAccount = "", ledCallerKey = "", ledFailed = false, ledRetried = false, ledQuery = "", ledModel = "", ledRoute = 0, ledComputer = "", ledDay = "", ledVia = ""; + +const LED_PAGE = 100; +// Remember the chart metric; start each app load split by model. +let ledMetric = "tokens", ledSplit = "model"; +try { + const m = localStorage.getItem("magpie.ledMetric"); + if (["tokens", "cost", "calls", "speed"].includes(m)) ledMetric = m; +} catch {} + +let ledRouteInfo = null, ledBeforeRoute = null; +window.openUsageRoute = (route) => { + if (!ledBeforeRoute) ledBeforeRoute = { period, ledOffset, ledPurpose, ledAgent, ledProvider, ledAccount, ledCallerKey, ledFailed, ledRetried, ledQuery, ledModel, ledComputer, ledDay, ledVia }; + ledRoute = route.id; + ledRouteInfo = route; + ledOffset = 0; ledPurpose = ""; ledAgent = ""; ledProvider = ""; ledAccount = ""; ledCallerKey = ""; ledFailed = false; ledRetried = false; ledQuery = ""; ledModel = ""; ledComputer = ""; ledVia = ""; + ledDay = ""; + $("#ledQ").value = ""; + period = "all"; + usageTab = "requests"; + ledger = null; + show("usage"); +}; + +function ledParams(extra) { + const q = new URLSearchParams({ period }); + if (ledDay) q.set("day", ledDay); + if (ledAgent) q.set("agent", ledAgent); + if (ledPurpose) q.set("purpose", ledPurpose); + if (ledProvider) q.set("provider", ledProvider); + if (ledAccount) q.set("account", ledAccount); + if (ledComputer) q.set("computer", ledComputer); + if (ledCallerKey) q.set("callerKey", ledCallerKey); + if (ledVia) q.set("via", ledVia); + if (ledRoute) q.set("route", ledRoute); + if (ledFailed) q.set("failed", "1"); + if (ledRetried) q.set("retried", "1"); + if (ledModel) q.set("model", ledModel); + else if (ledQuery.trim()) q.set("q", ledQuery.trim()); + if (extra) for (const k in extra) q.set(k, extra[k]); + return q.toString(); +} + +// One read of the ledger at a time (Vantiboo1ean, ~750k requests): the page +// asked again while it is read (the refresh button, the timer) waits for +// that read, and another page or filter cancels it. Each pick and press +// used to send one more, and a long history's reads, all still running, +// took the browser's few connections to magpie, so the page never came. +// flight: { want, ctl, p } +const ledFlights = { page: null, heat: null }; +function ledRead(kind, path, want) { + const was = ledFlights[kind]; + if (was?.want === want) return was.p; + was?.ctl.abort(); + const ctl = new AbortController(); + const f = { want, ctl, p: api(path + want, undefined, undefined, ctl.signal) }; + ledFlights[kind] = f; + const done = () => { if (ledFlights[kind] === f) ledFlights[kind] = null; }; + f.p.then(done, done); + return f.p; +} +const ledAborted = (e) => e?.name === "AbortError"; + +// quiet: a refresh while it's looked at, redrawn only on a change +async function loadLedger(quiet) { + if (!ledger && !quiet) renderLedgerLoading(); + loadLedHeat().catch(() => {}); + const want = ledParams({ offset: ledOffset, limit: LED_PAGE }); + let l; + try { l = await ledRead("page", "usage/requests?", want); } catch (e) { + if (ledAborted(e)) return; // another page or filter was picked, and is read instead + throw e; + } + if (want !== ledParams({ offset: ledOffset, limit: LED_PAGE })) return; // another page or filter was picked meanwhile + if (quiet && JSON.stringify(l) === JSON.stringify(ledger)) return; + ledger = l; + if (view === "usage" && usageTab === "requests") renderLedger(); +} + +function renderLedgerLoading() { + const view = $("#view-usage"); + view.classList.add("loading"); + view.setAttribute("aria-busy", "true"); + renderPeriod(true); + $("#usageCost").replaceChildren(el("span", "skeleton sk-cost")); + $("#ledSum").textContent = ""; + $("#ledPager").hidden = true; + const wrap = $("#ledWrap"); + wrap.classList.remove("none"); + wrap.replaceChildren(); + $("#ledHScroll").hidden = true; + for (let i = 0; i < 5; i++) { + const r = el("div", "led-sk"); + r.append(el("span", "skeleton sk-line")); + wrap.append(r); + } +} + +function ledTime(when) { + const d = new Date(when), now = new Date(); + const opts = { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false }; + if (d.toDateString() !== now.toDateString()) Object.assign(opts, { month: "short", day: "numeric" }); + return d.toLocaleString(intlLang(), opts); +} +// the model the reply named: amber, as the Routing page's tag, when it is +// another than the one sent; plain when it is that one under a dated name, +// or the member a remote magpie's routing group sent it to, said in its title +function ledServed(r) { + if (!r.served) return el("span", "faint", "—"); + if (r.routed && !r.swapped) { + const k = el("span", "muted model-value routed", r.served); + k.title = window.routedWhy ? window.routedWhy({ model: r.model, served: r.served }) : ""; + return k; + } + if (!r.swapped) return el("span", "model-value", r.served); + const k = el("span", "swap", r.served); + k.title = window.swapWhy ? window.swapWhy({ model: r.model, served: r.served }) : ""; + return k; +} + +// the protocol a request was sent upstream in, told by the path it went +// out on, and the one its agent spoke when that was another: the +// endpoint reads "/v1/chat/completions → /v1/messages" for a request +// translated, the agent's own path alone for one sent as it came (蓝猫 on +// Discord). null for a request with no path kept, a session file's. Gemini's +// is generateContent, or streamGenerateContent streamed (Gemini CLI's, +// Vertex AI's). +const ledProtoOf = (path) => /\/messages\b/.test(path) ? "Anthropic" : /\/responses\b/.test(path) ? "Responses" + : /\/chat\/completions\b/.test(path) ? "Chat" : /[gG]enerateContent|\/generate\b/.test(path) ? "Gemini" : ""; +function ledProtos(r) { + if (!r.ep || r.source === "log") return null; + const [a, b] = String(r.ep).split(" → "); + const from = ledProtoOf(a), to = b ? ledProtoOf(b) : from; + if (!to) return null; + return { from: from || to, to }; +} +function ledProtoBadge(r) { + const p = ledProtos(r); + if (!p) return null; + const k = el("span", "src proto proto-" + p.to.toLowerCase(), p.from !== p.to ? p.from + " → " + p.to : p.to); + k.title = p.from !== p.to ? t("The agent spoke {from}; sent upstream as {to}", p) : t("Sent upstream as {to}, as the agent spoke it", p); + return k; +} + +// a request that failed: told by its status, or, for one read from a +// session file, which records none, by the error that ended it +const ledFailed_ = (r) => r.status >= 400 || !!r.err; +const ledKey = (r) => [r.t, r.agent, r.model, r.rid, r.session, r.computer || ""].join("|"); +const ledOpen = new Set(); // the rows opened, kept across a refresh + +// what is known of one request beyond its row: the id its vendor gave it, +// the path it went to, and, if it failed, what the vendor said +function ledDetail(r, cols) { + const dl = el("dl", "led-dl"); + const add = (name, value, cls) => { + if (value === "" || value == null) return; + dl.append(el("dt", "", t(name)), el("dd", cls || "", value)); + }; + if (ledFailed_(r)) { + add("Status", r.status ? String(r.status) : "—", "bad"); + add("Error type", r.err_type, "bad"); + add(r.source === "log" ? "Error" : "Upstream said", r.err, "said"); + } else { + // how it went, here as well as in the row's last column, which a narrow + // window leaves out of sight (#799) + add("Status", r.status ? String(r.status) : r.source === "log" ? t("Succeeded") : ""); + } + if (Number.isFinite(r.ms) && r.ms > 0) add("Duration", (r.source === "log" ? "≈" : "") + ledTook(r.ms)); + // the way it was routed: the row's time links there too, which reads as + // a time rather than a link (#799) + // (with the Routing page switched off there is nowhere to see it) + if (r.route_id && !featuresOff.has("routing")) { + const go = el("button", "text led-route-link", t("View routing")); + go.onclick = (e) => { e.stopPropagation(); window.openRoute(r.route_id, r.t).catch((err) => status(err.message, "err")); }; + const dd = el("dd"); + dd.append(go); + dl.append(el("dt", "", t("Routing")), dd); + } + if (r.computerName) add("Computer", r.computerName); + // the client's own name, for one the user counts as an agent (#1958) + add("Client", r.client); + // the columns a narrow window leaves out, shown only while it does (#860) + const opt = (name, value) => { + if (!value) return; + add(name, value); + dl.lastChild.classList.add("lc-opt"); + dl.lastChild.previousSibling.classList.add("lc-opt"); + }; + opt("Sent", r.model); + opt("Effort", r.effort); + // its tokens at every width, the cache's beside in and out: a prompt read + // from the cache is told from one that missed it, whose input is the + // whole of it, where the row's cache columns are out of sight (#1839). + // In leaves the cache out, as Anthropic counts it. + if (r.in || r.out || r.cache_read || r.cache_write || !ledFailed_(r)) { + add("Tokens", t("{i} in · {o} out · {r} cache read · {w} cache creation", { i: ledNum(r.in || 0), o: ledNum(r.out || 0), r: ledNum(r.cache_read || 0), w: ledNum(r.cache_write || 0) }) + cacheTTLs(r, ledNum), "led-tokens"); + } + if (ledRowSpeed(r)) add("Speed", t("{n} tok/s", { n: ledNum(Math.round(ledRowSpeed(r))) })); + else if (ledFloorSpeed(r)) add("Speed", "≥" + t("{n} tok/s", { n: ledNum(Math.round(ledFloorSpeed(r))) })); + add("Request ID", r.rid); + add("Endpoint", r.ep); + const protos = ledProtos(r); + if (protos) add("Protocol", protos.from !== protos.to ? protos.from + " → " + protos.to : protos.to); + // why the upstream said its reply ended, in its own words: a reply that + // ended too soon is told apart by it (蓝猫 on Discord) + add("Upstream stop reason", r.stop); + // the provider an aggregator (OpenRouter …) said answered behind it + add("Upstream provider", r.upstream); + add("Session ID", r.session); + // a call that isn't a turn of the conversation says what it was for, as + // the agent named it: a subagent's, a title, an approval check… — a + // model the conversation never picked reads as what it is (#714) + if (r.kind) add("Called for", window.kindName ? window.kindName(r.kind) : r.kind); + if (r.ttft_ms) add("First token", ledTook(r.ttft_ms)); + // of it, what came before the request went to the vendor, and the + // vendor's wait from then to its first token. Before it, magpie's own + // time is told apart from the tries that failed first, a wait for a + // slot and connecting and sending the body (#1532: a vendor that held a + // try ~100 s before its 503 read as 104 s in magpie); a record from + // before they were kept has only the whole + if (r.ttft_ms && r.sent_ms) { + const split = r.own_ms != null; + add("In magpie", ledTook(split ? r.own_ms : r.sent_ms)); + if (split) { + if (r.retried_ms > 0) add("Tries that failed first", ledTook(r.retried_ms)); + if (r.queued_ms > 0) add("Waiting for a slot", ledTook(r.queued_ms)); + const sending = r.sent_ms - r.own_ms - (r.retried_ms || 0) - (r.queued_ms || 0); + if (sending > 0) add("Connecting and sending", ledTook(sending)); + } + add("Vendor's first token", ledTook(Math.max(0, r.ttft_ms - r.sent_ms))); + } + if (r.reasoning) add("Reasoning tokens", ledNum(r.reasoning)); + if (r.session_provider) add("Recorded provider ID", r.session_provider); + if (r.session_account) add("Session account", r.session_account); + if (r.source === "log" && r.session_account && r.session_official_login) add("Login method", t("Official login")); + if (r.pricing_model) add("API price reference", r.pricing_model); + // with the archive on, a request it has no copy of says so: from before + // it was on, or not through the gateway + if (!r.archive && !r.computer && (providers?.gateway?.archive?.on ?? state.settings?.requestArchive)) add("Request archive", t("Not archived"), "muted"); + if (r.source === "log") add("Data source", t("Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred."), "muted"); + const tr = el("tr", "led-detail"); + const td = el("td"); + td.colSpan = cols; + const box = el("div", "led-box"); + box.append(dl.childElementCount ? dl : el("span", "faint", t("Nothing more was kept of this request"))); + // the call as the request archive kept it, when it was on (#447) + if (r.archive) { + const ab = el("div", "led-archive"); + const draw = () => ab.replaceChildren(archivePanel(r.archive, "led|" + ledKey(r), draw)); + draw(); + box.append(ab); + } + // what was said: read from the agent's session file, when the row is + // opened; one made on another computer has its files there, and sync + // brings none of what was said + const cx = el("div", "led-cx"); + if (r.computer) { + cx.append(el("p", "cx-none", t("What was said stays on {computer}: sync shares the usage alone.", { computer: r.computerName || r.computer }))); + } else { + cx.append(el("p", "cx-none", t("Loading…"))); + ledLoadContent(r).then((c) => { if (cx.isConnected) cx.replaceChildren(ledContentBox(c)); }); + } + box.append(cx); + td.append(box); + tr.append(td); + return tr; +} + +// What was said in a request — what its agent was given, and what came back — +// is in the agent's own session file, and read from it when a row is opened +// (the server finds the call by its session and time); magpie keeps no copy. +// What came is kept here while the list is looked at, so a row opened again, or +// drawn again as the list is read anew, doesn't ask again. +const ledContent = new Map(); +function ledLoadContent(r) { + const key = ledKey(r); + if (!ledContent.has(key)) { + if (ledContent.size > 60) ledContent.delete(ledContent.keys().next().value); + const t0 = new Date(r.t).getTime(); + // a call of a session file is at its own time; a request the gateway logged began + // a little before the file wrote it, and the call is in the span it took + const [a, b] = r.source === "log" ? [t0 - 1, t0 + 1] : [t0 - 5e3, t0 + (r.ms || 0) + 30e3]; + // the window can hold the next calls of a quick tool loop too: the one that + // ended nearest the request's own end is its call + const at = r.source === "log" ? t0 : t0 + (r.ms || 0); + const q = new URLSearchParams({ agent: r.agent, session: r.native_session || r.session || "", from: new Date(a).toISOString(), to: new Date(b).toISOString(), at: new Date(at).toISOString() }); + const pending = api("usage/requests/content?" + q).catch(() => ({ found: false, why: "read" })).then((c) => { + if (!c.found && ledContent.get(key) === pending) ledContent.delete(key); + return c; + }); + ledContent.set(key, pending); + } + return ledContent.get(key); +} +const LED_WHY = { + session: "No session was named with this request, so its session file can't be found", + agent: "magpie reads the session files of Claude Code, Claude Desktop and Codex only", + missing: "This request isn't in the agent's session files: they may be deleted, moved, or not written yet", + read: "The session file couldn't be read", +}; +function ledContentBox(c) { + const box = el("div", "cx"); + if (!c.found) { + box.append(el("p", "cx-none", t(LED_WHY[c.why] || LED_WHY.read))); + return box; + } + for (const [name, parts] of [["Input", c.input || []], ["Output", c.output || []]]) { + const sec = el("section", "cx-sec"); + sec.append(el("h4", "", t(name))); + if (!parts.length) sec.append(el("p", "cx-none", t("Nothing was said here"))); + for (const p of parts) sec.append(ledSaid(p)); + box.append(sec); + } + if (c.cut) box.append(el("p", "cx-none", t("There was more than is shown here"))); + box.append(el("p", "cx-src", t("Read from the agent's session file; magpie keeps no copy"))); + return box; +} + +// ---- the totals and the trend over the requests listed +// +// A strip of four totals, then the trend of one metric — tokens, cost or +// requests — as columns by the hour, day or week, each told apart by provider, +// agent or model, beside a ranking of the same: which is the chart's legend +// and a way in (a click on a provider or agent lists only its requests). The +// server sums it all (the ledger's "series" and "by"); the tray panel's Usage +// tab draws the same from the same answer. + +// the window's chart can also say how fast the replies came (#860) +const LED_TREND = [...LED_METRICS, ["speed", "Speed"]]; +// "modelAt" is a model at the provider it went to, so one model's speed at +// each provider is ranked side by side (inaction on Discord) +const LED_SPLITS = [["model", "Model"], ["modelAt", "Model · provider"], ["provider", "Provider"], ["agent", "Agent"]]; +// cacheTTLs: a call's cache writes split by how long they are kept, where +// some were for an hour (Anthropic bills those at 2× input, 5 minutes' +// at 1.25×); nothing when none were +function cacheTTLs(x, fmt) { + const h = Math.min(x.cache_write_1h || 0, x.cache_write || 0); + return h ? " · " + t("{m} for 5 minutes, {h} for an hour", { m: fmt(x.cache_write - h), h: fmt(h) }) : ""; +} +// the rail's thumb drags the ranking; a click on the rail takes it there +function ledRail(rail, box) { + box.rail = rail; + rail.onpointerdown = (e) => { + if (e.button !== 0) return; + e.preventDefault(); + const end = box.scrollHeight - box.clientHeight, thumb = rail.firstChild.offsetHeight, room = rail.clientHeight - thumb; + if (end <= 0 || room <= 0) return; + if (e.target !== rail.firstChild) { + // the thumb's middle to where the rail was clicked + const y = e.clientY - rail.getBoundingClientRect().top - thumb / 2; + box.scrollTop = (Math.max(0, Math.min(room, y)) / room) * end; + } + const y0 = e.clientY, top0 = box.scrollTop; + rail.setPointerCapture(e.pointerId); + rail.classList.add("drag"); + rail.onpointermove = (m) => { box.scrollTop = top0 + ((m.clientY - y0) / room) * end; }; + rail.onpointerup = rail.onpointercancel = () => { + rail.classList.remove("drag"); + rail.onpointermove = rail.onpointerup = rail.onpointercancel = null; + }; + }; +} + +// the request list's status filter: "" for all, "failed" or "retried" +const ledStatusOf = () => ledFailed ? "failed" : ledRetried ? "retried" : ""; +function ledShowStatus(to) { + if (to === ledStatusOf()) return; + ledFailed = to === "failed"; + ledRetried = to === "retried"; + ledOffset = 0; + loadLedger().catch((e) => status(e.message, "err")); +} + +function renderLedgerDash(l) { + const dash = $("#ledDash"); + dash.hidden = !l.total && !l.day; + if (dash.hidden) return; + const total = allTokens(l); + const prompt = l.input + l.cache_write + l.cache_read; + const rate = prompt ? l.cache_read / prompt : 0; + const strip = $("#ledKpi"); + strip.replaceChildren(); + const block = (label, value, sub, cls, title) => { + const b = el("div", "blk"); + if (title) b.title = title; + // a value in parts (an array) keeps each whole, wrapping between them + const v = el("span", "v" + (cls ? " " + cls : "") + (Array.isArray(value) ? " parts" : ""), Array.isArray(value) ? undefined : value); + // (a space between two stays out of them: one leading a part is dropped) + if (Array.isArray(value)) value.forEach((x, i) => v.append(...(i && /^\s/.test(x) ? [" "] : []), el("span", "", x.trim()))); + b.append(el("span", "k", t(label)), v); + if (sub) b.append(sub); + strip.append(b); + return b; + }; + const line = (...parts) => { const s = el("span", "sub"); s.append(...parts); return s; }; + // a line holding a count's button wraps rather than cut the button off + // (German's "nach erneutem Versuch beantwortet" runs past a narrow card) + const jumps = (...parts) => { const s = line(...parts); s.classList.add("jumps"); return s; }; + block("Tokens", fmtN(total), line(t("{a} in · {b} out", { a: fmtN(l.input), b: fmtN(l.output) }), " · ", t("{a} cache", { a: fmtN(l.cache_read + l.cache_write) })), "", ledNum(total)); + // a request is counted once, by how it ended: one a later try answered + // is not a failure, and is counted beside them as answered on a retry + // (小一 on Discord). Each count is a button for its requests in the list. + const jump = (text, to, title) => { + const b = el("button", "led-jump" + (to === "failed" ? " bad" : "") + (ledStatusOf() === to ? " on" : ""), text); + b.type = "button"; + b.title = title; + b.setAttribute("aria-pressed", ledStatusOf() === to ? "true" : "false"); + b.onclick = () => ledShowStatus(ledStatusOf() === to ? "" : to); + return b; + }; + block("Requests", ledNum(l.calls), l.errors + ? jumps(jump(t("{n} failed", { n: ledNum(l.errors) }), "failed", t("Show only the failed requests")), " · " + t("{p} succeeded", { p: (100 * (1 - l.errors / l.calls)).toFixed(1) + "%" })) + : line(t("none failed"))); + if (l.retried) strip.lastChild.append(jumps(jump(t("{n} answered on a retry", { n: ledNum(l.retried) }), "retried", t("Show only the requests answered on a retry")))); + const c = fmtCost(l); + block("Cost", c ? "≈" + c : "—", line(l.unpriced ? t(l.unpriced === 1 ? "{n} call had no known price and is not counted" : "{n} calls had no known price and are not counted", { n: l.unpriced }) : t("effective prices")), c ? "cost" : ""); + const hit = block("Cache hit rate", (100 * rate).toFixed(1) + "%", null, "", t("The share of the prompt read from the cache")); + const meter = el("div", "meter"), fill = el("i"); + fill.style.width = (100 * rate).toFixed(1) + "%"; + meter.append(fill); + hit.append(meter); + // how fast the streamed replies wrote, and how long they took to begin (#860): + // the figure of more replies, its count beside it; the other under it; the + // wait for the first token on a line of its own, with how many it is of + // (Fallmonkey on Discord) + const gs = ledGroupSpeed(l); + const ttft = ledTTFT(l) ? t("first token in {ms} on average", { ms: ledTook(ledTTFT(l)) }) + " · " + t(l.timed === 1 ? "{k} timed reply" : "{k} timed replies", { k: ledNum(l.timed) }) : t("no streamed replies timed"); + const speedCard = block("Output speed", gs ? gs.mainParts : "—", gs?.other ? line(gs.other) : null, + "", [gs?.title, t("Output tokens a second after the first, over the streamed replies") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it") + ". " + t("No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed")].filter(Boolean).join("\n")); + speedCard.append(Object.assign(line(ttft), { className: "sub ttft" })); + drawLedTrend(); +} + +function drawLedTrend() { + const l = ledger; + if (!l || $("#ledDash").hidden) return; + // the two switches + const pill = (host, key, opts, cur, pick) => { + host.replaceChildren(); + for (const [id, name] of opts) { + const b = el("button", "opt" + (id === cur ? " on" : ""), t(name)); + b.onclick = () => { if (id !== cur) pick(id); }; + host.append(b); + } + slide(host, key); + }; + pill($("#ledMetric"), "ledMetric", LED_TREND, ledMetric, (id) => { ledMetric = id; try { localStorage.setItem("magpie.ledMetric", id); } catch {} drawLedTrend(); }); + pill($("#ledSplit"), "ledSplit", LED_SPLITS, ledSplit, (id) => { ledSplit = id; drawLedTrend(); }); + const chart = $("#ledChart"), rank = $("#ledRank"); + drawLedColumns(chart, l, ledSplit, ledMetric, false, (day) => { + ledDay = ledDay === day ? "" : day; + ledOffset = 0; + loadLedger().catch((e) => status(e.message, "err")); + }); + rank.chart = chart; + if (!rank.rail) ledRail($("#ledRail"), rank); + const picked = ledSplit === "provider" ? ledProvider : ledSplit === "agent" ? ledAgent + : ledSplit === "modelAt" ? (ledProvider && ledModel ? ledProvider + "/" + ledModel : "") : ledModel; + drawLedRank(rank, l, ledSplit, ledMetric, picked, (x) => { + // a click lists only that one's requests; on the one listed, all again + if (ledSplit === "modelAt") { + // provider/model: both filters, the provider's id has no "/" + const q = $("#ledQ"), cut = x.id.indexOf("/"), off = picked === x.id; + ledProvider = off ? "" : x.id.slice(0, cut); + ledModel = off ? "" : x.id.slice(cut + 1); + ledQuery = ledModel; q.value = ledQuery; + } else if (ledSplit === "provider") ledProvider = ledProvider === x.id ? "" : x.id; + else if (ledSplit === "agent") ledAgent = ledAgent === x.id ? "" : x.id; + else { const q = $("#ledQ"); ledModel = ledModel === x.id ? "" : x.id; ledQuery = ledModel; q.value = ledQuery; } + ledOffset = 0; + loadLedger().catch((e) => status(e.message, "err")); + }, false); +} +// ---------- the heatmap (#1369) ---------- +// +// The last 53 weeks a day each, Monday on top, as a calendar of +// contributions lays them out: each day as dark as it is busy among the +// others, by tokens, requests or cost. It is of the requests the filters +// above keep, whatever the period (the server's /api/usage/heatmap, read +// from the same index as the page), its days in the gateway's time zone. A +// narrow window scrolls it sideways inside its card, the newest week in +// sight; the pointer on a day says its date and what it had. +let ledHeat = null, ledHeatWant = "", ledHeatMetric = "tokens"; +try { + const m = localStorage.getItem("magpie.ledHeatMetric"); + if (["tokens", "calls", "cost"].includes(m)) ledHeatMetric = m; +} catch {} +const LED_HEAT = [["tokens", "Tokens"], ["calls", "Requests"], ["cost", "Cost"]]; +function ledHeatParams() { + const q = new URLSearchParams(ledParams()); + q.delete("period"); + q.delete("day"); + return q.toString(); +} +async function loadLedHeat() { + const want = ledHeatParams(); + ledHeatWant = want; + const h = await ledRead("heat", "usage/heatmap?", want).catch((e) => { if (ledAborted(e)) return ledAborted; throw e; }); + if (h === ledAborted) return; + if (want !== ledHeatWant) return; // another filter was picked meanwhile + if (ledHeat && ledHeat.want === want && JSON.stringify(ledHeat.data) === JSON.stringify(h)) return; + ledHeat = { want, data: h }; + if (view === "usage" && usageTab === "requests") drawLedHeat(); +} +const ledHeatDate = (s) => { const [y, m, d] = String(s).split("-").map(Number); return new Date(y, m - 1, d); }; +function ledHeatTip(x) { + const loc = intlLang(); + const tip = el("div"); + tip.append(el("b", "", x.day.toLocaleDateString(loc, { year: "numeric", month: "short", day: "numeric", weekday: "short" }))); + if (!x.calls) { + tip.append(el("span", "", t("No requests"))); + return tip; + } + const parts = [t("{n} tokens", { n: fmtN(x.tokens) }), t(x.calls === 1 ? "{n} request" : "{n} requests", { n: ledNum(x.calls) })]; + const c = fmtCost(x); + if (c) parts.push("≈" + c); + const order = { tokens: 0, calls: 1, cost: 2 }[ledHeatMetric]; + if (order && parts[order]) parts.unshift(...parts.splice(order, 1)); // the metric shown first + tip.append(el("span", "", parts.join(" · "))); + return tip; +} +function drawLedHeat() { + const box = $("#ledHeat"), h = ledHeat?.data; + const at = new Map((h?.days || []).map((d) => [d.date, d])); + box.hidden = !h?.from || !h?.to || ![...at.values()].some((d) => d.calls > 0); + if (box.hidden) return; + const first = ledHeatDate(h.from), last = ledHeatDate(h.to); + const days = []; + for (const d = new Date(first); d <= last; d.setDate(d.getDate() + 1)) { + const x = at.get(sessISO(d)) || { calls: 0, tokens: 0, cost: 0 }; + days.push({ ...x, day: new Date(d) }); + } + const value = (x) => ledHeatMetric === "cost" ? x.cost : ledHeatMetric === "calls" ? x.calls : x.tokens; + const lv = sessLevels(days.map(value)); + const seg = $("#ledHeatMetric"); + seg.replaceChildren(); + for (const [id, name] of LED_HEAT) { + const b = el("button", "opt" + (id === ledHeatMetric ? " on" : ""), t(name)); + b.type = "button"; + b.onclick = () => { + if (id === ledHeatMetric) return; + ledHeatMetric = id; + try { localStorage.setItem("magpie.ledHeatMetric", id); } catch {} + drawLedHeat(); + }; + seg.append(b); + } + slide(seg, "ledHeatMetric"); + const scroll = $("#ledHeatScroll"); + // the same days in the same language keep their cells, coloured again, so + // a refresh moves nothing and the scroll stays where the reader left it + const shape = [h.from, h.to, locale].join("|"); + let grid = scroll.querySelector(".heat-grid"); + if (!grid || grid.dataset.shape !== shape) { + grid = el("div", "heat-grid"); + grid.dataset.shape = shape; + grid.setAttribute("role", "img"); + const names = sessWeekdays(); + // every row has its place at the edge, named every other day + for (let i = 0; i < 7; i++) { + const l = el("span", "wd", i % 2 ? "" : names[i]); + l.style.gridArea = `${i + 2} / 1`; + grid.append(l); + } + const loc = intlLang(); + const weeks = Math.ceil(days.length / 7), labels = []; + let month = -1; + days.forEach((x, i) => { + const w = Math.floor(i / 7), wd = i % 7; + if (wd === 0 && x.day.getMonth() !== month) { + month = x.day.getMonth(); + // a month mostly gone in the first week is left unnamed, so as not + // to crowd out the next one's name, and so is one begun in the last + // week, with no room for its name + if ((!labels.length || w - labels.at(-1).w >= 3) && !(w === 0 && x.day.getDate() > 14) && w < weeks - 1) { + const m = el("span", "mo", x.day.toLocaleDateString(loc, { month: "short" })); + labels.push({ m, w }); + grid.append(m); + } + } + const c = el("i"); + c.dataset.date = sessISO(x.day); + c.style.gridArea = `${wd + 2} / ${w + 2}`; + grid.append(c); + }); + // a month's name spans its weeks up to the next name, cut there, so a + // long one never widens the grid past its last week + labels.forEach(({ m, w }, i) => { m.style.gridArea = `1 / ${w + 2} / 2 / ${(labels[i + 1]?.w ?? weeks) + 2}`; }); + grid.onpointerover = (e) => { if (e.target.dataset?.date) ledHeatShow(e.target); }; + grid.onpointerleave = () => { $("#ledHeatTip").hidden = true; }; + scroll.replaceChildren(grid); + if (!scroll.onscroll) { + // the newest week in sight, by the card's own scroll, never the page's: + // kept there as the card is laid out or resized, until the reader + // scrolls it back, and again once they scroll to the end + scroll.onscroll = () => { + $("#ledHeatTip").hidden = true; + // its own scroll to the end, seen after the card narrowed, is not the reader's + if (scroll.clientWidth && scroll.scrollLeft !== ledHeatSetAt) ledHeatAtEnd = scroll.scrollLeft >= scroll.scrollWidth - scroll.clientWidth - 2; + }; + } + ledHeatSized.disconnect(); + ledHeatSized.observe(scroll); + ledHeatSized.observe(grid); + ledHeatKeepEnd(); + } + grid.setAttribute("aria-label", t("Usage heatmap")); + const cells = grid.querySelectorAll("i"); + days.forEach((x, i) => { + const c = cells[i]; + c.className = "l" + lv(value(x)); + c.day = x; + }); + const legend = box.querySelector(".heat-foot"); + legend.replaceChildren(sessLegend()); + const tip = $("#ledHeatTip"); + if (!tip.hidden && tip.cell?.isConnected) ledHeatShow(tip.cell); + else tip.hidden = true; +} +let ledHeatAtEnd = true, ledHeatSetAt = -1; +const ledHeatSized = new ResizeObserver(() => ledHeatKeepEnd()); +function ledHeatKeepEnd() { + const scroll = $("#ledHeatScroll"); + if (!ledHeatAtEnd || !scroll.clientWidth || scroll.scrollWidth <= scroll.clientWidth) return; + scroll.scrollLeft = scroll.scrollWidth; + ledHeatSetAt = scroll.scrollLeft; +} +// the tip over a day, above it, kept inside the card +function ledHeatShow(cell) { + const box = $("#ledHeat"), tip = $("#ledHeatTip"); + if (!cell.day) return; + tip.replaceChildren(...ledHeatTip(cell.day).children); // the date over the figures + tip.cell = cell; + tip.hidden = false; + const b = box.getBoundingClientRect(), c = cell.getBoundingClientRect(); + const w = tip.offsetWidth, hgt = tip.offsetHeight; + const left = Math.max(6, Math.min(b.width - w - 6, c.left - b.left + c.width / 2 - w / 2)); + let top = c.top - b.top - hgt - 6; + if (top < 4) top = c.bottom - b.top + 6; + tip.style.left = left + "px"; + tip.style.top = top + "px"; +} +// the table's scrollbar, kept in view at the window's foot (#799): as wide +// as the table can go sideways, and moving it as the table moves it +function ledHScroll() { + const wrap = $("#ledWrap"), bar = $("#ledHScroll"); + const over = !!wrap.querySelector("table") && wrap.scrollWidth > wrap.clientWidth + 1; + bar.hidden = !over; + if (!over) return; + bar.firstElementChild.style.width = wrap.scrollWidth - wrap.clientWidth + bar.clientWidth + "px"; + bar.scrollLeft = wrap.scrollLeft; +} +$("#ledWrap").addEventListener("scroll", () => { const bar = $("#ledHScroll"); if (bar.scrollLeft !== $("#ledWrap").scrollLeft) bar.scrollLeft = $("#ledWrap").scrollLeft; }, { passive: true }); +$("#ledHScroll").addEventListener("scroll", () => { const wrap = $("#ledWrap"); if (wrap.scrollLeft !== $("#ledHScroll").scrollLeft) wrap.scrollLeft = $("#ledHScroll").scrollLeft; }, { passive: true }); +// a window that changes size redraws the chart at its new width +// a new width fits the table again, on the next frame, and so do the +// details' width (--ledw) and the scrollbar: each changes the table's or the +// wrap's height, which this would be told of in its own call, and WebKit +// reports that as a ResizeObserver loop (number-units' page error) +let ledFitW = 0, ledFitFrame = 0; +new ResizeObserver(() => { + if (ledFitFrame) return; + ledFitFrame = requestAnimationFrame(() => { + ledFitFrame = 0; + const wrap = $("#ledWrap"); + wrap.style.setProperty("--ledw", wrap.clientWidth + "px"); + if (wrap.clientWidth !== ledFitW) { ledFitW = wrap.clientWidth; ledFit(); } + ledHScroll(); + }); +}).observe($("#ledWrap")); +// a table that grows past the window when its width didn't change (a font +// arriving, a redraw while out of sight) leaves its columns out then too; +// and its scrollbar goes once a table left without them has come to fit, +// rather than staying under a table with nothing to scroll +let ledGrowFrame = 0; +const ledGrow = new ResizeObserver(() => { + if (ledGrowFrame) return; + ledGrowFrame = requestAnimationFrame(() => { + ledGrowFrame = 0; + const wrap = $("#ledWrap"), table = wrap.querySelector("table.led"); + if (table && !table.classList.contains("tighter") && wrap.clientWidth && wrap.scrollWidth > wrap.clientWidth + 1) ledFit(); + ledHScroll(); + }); +}); +new ResizeObserver(() => { + if (!ledger || usageTab !== "requests" || view !== "usage" || $("#ledDash").hidden) return; + drawLedColumns($("#ledChart"), ledger, ledSplit, ledMetric, false); + ledRankEdges($("#ledRank")); +}).observe($("#ledChart")); + +// the third: a column a narrow window leaves out, its value in the row's +// details (#860) +const LED_COLS = [ + ["Time"], ["Agent"], ["Requested"], ["Provider · account"], ["Sent", "", true], ["Served"], ["Effort", "", true], + ["In", "n"], ["Out", "n"], ["Cache write", "n", true], ["Cache read", "n", true], ["Cost", "n"], ["Duration", "n"], ["Speed", "n"], ["Status"], +]; + +// the tokens a reply was seen to write and the ms it took, as +// usage.DecodeOf and routing/client.js's decodeOf tell them: one that reasoned +// counts its answer from its first text, its reasoning written before +// the stream showed any (tony on Discord); null when it tells no speed. +// A reply held back and let go in a burst at its end tells none (John on +// Discord): its content came in under a quarter of its window (flow_ms), +// or its answer at over 20 times the pace its reasoning came before it +const ledDecode = (r) => { + if (ledFailed_(r) || r.reasoning_hidden && !(r.first_text_ms > 0) || !(r.ttft_ms > 0)) return null; + const think = r.reasoning > 0, visible = think && !(r.first_text_ms > 0) && r.first_reasoning_ms >= r.ttft_ms && r.flow_ms > 0 && r.reasoning <= r.out; + const n = think && !visible ? r.out - r.reasoning : r.out, from = visible ? r.first_reasoning_ms : think ? r.first_text_ms : r.ttft_ms; + const w = r.ms - from; + if (!(n > 0 && from > 0 && w >= 100 && n * 1000 <= 10000 * w)) return null; + if (r.flow_ms > 0 && r.flow_ms * 4 < w) return null; + if (think && r.first_text_ms > 0 && n * (r.first_text_ms - r.ttft_ms) > 20 * r.reasoning * w) return null; + if (ledCodexTurn(r) && (w < LED_CODEX_WINDOW_MS || n < LED_CODEX_BODY)) return null; + return { n, w }; +}; +// a Codex turn of one call read from its session file, its first token +// known: its window after the first token can be one network push, not the +// writing (Fallmonkey on Discord: a first token at 6.8 s, the rest 0.2 s +// later), so it tells a speed only over a second or more and 100 tokens or +// more (usage.CodexWindowMs, CodexBodyTokens); else ledFloor_ tells the +// least it wrote at over the whole turn +const LED_CODEX_WINDOW_MS = 1000, LED_CODEX_BODY = 100; +const ledCodexTurn = (r) => r.source === "log" && r.agent === "codex" && r.ttft_ms > 0; +// how fast a reply wrote, in tokens a second: 0 when it can't tell +const ledRowSpeed = (r) => { const d = ledDecode(r); return d ? d.n / (d.w / 1000) : 0; }; +// the least a reply read from a session file wrote at, in tokens a second: +// the file has no first token, only when the line that asked for it and its +// last line were written (Claude Code's are each block's end), so its tokens +// over that whole time, the wait for the first one in it, are a floor the +// speed after the first token can't be under. Against Claude Code's own +// stream it read 2–5% under for a reply of 1,400 tokens or more, 11–33% for +// a shorter one or one asked with a tool's result, so only a reply of 1,000 +// or more is told. 0 when it tells none, and a call magpie timed tells its +// own (ledDecode). Only the row's: the period's speed counts timed calls. +// Claude Code's, Claude Desktop's and Codex's files only (usage.FloorAgents): +// a call's time is from what asked for it, never from inside it. OpenCode's +// isn't checked against real sessions, and tells none. +// A Codex turn of one call that reasoned has its first token but not its +// first text (Fallmonkey on Discord): its answer, its output less the +// reasoning, all came after the first token, so the answer over the time +// after it is a floor of the answer's speed, when that time is a second or +// more and the answer 100 tokens or more, as a measured one is. A Codex turn +// of one call that tells neither tells its output over the whole turn, the +// wait in it, by the same 1,000-token rule as any whole-time floor (Fallmonkey +// on Discord: 11 tokens in 2.75 s read ≥4 tok/s). ledFloor_ says the tokens, +// the ms, and which it is (answer, turn). +const LED_FLOOR_AGENTS = new Set(["claude", "claude-desktop", "codex"]); +const ledFloor_ = (r) => { + if (r.source !== "log" || !LED_FLOOR_AGENTS.has(r.agent) || ledFailed_(r) || ledRowSpeed(r)) return null; + if (ledCodexTurn(r)) { + const n = r.out - (r.reasoning || 0), w = r.ms - r.ttft_ms; + if (r.reasoning > 0 && n >= LED_CODEX_BODY && w >= LED_CODEX_WINDOW_MS && n * 1000 <= 10000 * w) return { n, w, answer: true }; + return r.out >= 1000 && r.ms >= 1000 && r.out * 1000 <= 10000 * r.ms ? { n: r.out, w: r.ms, turn: true } : null; + } + return r.out >= 1000 && r.ms >= 1000 && r.out * 1000 <= 10000 * r.ms ? { n: r.out, w: r.ms } : null; +}; +const ledFloorSpeed = (r) => { const f = ledFloor_(r); return f ? f.n / (f.w / 1000) : 0; }; + +// the table as wide as the window, when leaving out what the row's details +// say anyway makes it so: else it scrolls sideways (#799) +function ledFit() { + const wrap = $("#ledWrap"), table = wrap.querySelector("table.led"); + let hint = $("#ledTight"); + if (!table) { if (hint) hint.hidden = true; return; } + table.classList.remove("tight", "tighter"); + const over = () => wrap.scrollWidth > wrap.clientWidth + 1; + const tight = over(); + table.classList.toggle("tight", tight); + // still too wide (#860: a Windows window at 175%, its wider fonts): the + // price reference line goes too, in the cost's tooltip and the details + // as well, and names are cut shorter, whole in their tooltips + if (tight && over()) table.classList.add("tighter"); + if (!hint) { + hint = el("span", "led-tight"); + hint.id = "ledTight"; + $("#ledSum").after(hint); + } + hint.textContent = hint.title = t("Sent, Effort and the cache are in each row's details"); + hint.hidden = !tight; +} + +function renderLedger() { + const l = ledger; + const callers = l.callerKeys || []; + const providers = l.providers || []; + const missingAgent = ledAgent && !l.agents.some((a) => a.id === ledAgent); + const missingProvider = ledProvider && !providers.some((p) => p.id === ledProvider); + const accounts = l.accounts || []; + const missingAccount = ledAccount && !accounts.some((a) => a.id === ledAccount); + const missingCaller = ledCallerKey && !callers.some((k) => k.id === ledCallerKey); + const computers = computerOpts(l.computers); + const missingComputer = ledComputer && !computers.some((c) => c.v === ledComputer); + if (missingAgent || missingProvider || missingAccount || missingCaller || missingComputer) { + if (missingComputer) ledComputer = ""; + if (missingAccount) ledAccount = ""; + if (missingAgent) ledAgent = ""; + if (missingProvider) ledProvider = ""; + if (missingCaller) ledCallerKey = ""; + ledOffset = 0; + // Reload the rows too: this response still belongs to the missing filters. + loadLedger().catch((e) => status(e.message, "err")); + return; + } + const view = $("#view-usage"); + view.classList.remove("loading"); + view.removeAttribute("aria-busy"); + renderPeriod(); + renderArchive(); + + costHead(fmtCost(l), l.unpriced ? unpricedCalls(l.unpriced) : "", unpricedCallsWhy(l.unpriced)); + + // the filters: choices seen in the period, and failures alone + sessPick($("#ledPurpose"), "All purposes", ledPurpose, purposeOptions(l.purposes || [], ledPurpose), "Purpose", (v) => { ledPurpose = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); }); + $("#ledPurpose").title = t("Purpose"); + sessPick($("#ledComputer"), "All computers", ledComputer, computers, "Computer", (v) => { ledComputer = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); }); + sessPick($("#ledAgent"), "All agents", ledAgent, l.agents.map((a) => ({ v: a.id, name: a.name, note: "" })), "Agent", (v) => { ledAgent = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); }); + sessPick($("#ledProvider"), "All providers", ledProvider, providers.map((p) => ({ v: p.id, name: t(p.name), note: "" })), "Provider", (v) => { ledProvider = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); }); + sessPick($("#ledAccount"), "All accounts", ledAccount, accounts.map((a) => ({ v: a.id, name: a.id, note: (a.providers || []).map((p) => t(p)).join(" · ") })), "Account", (v) => { ledAccount = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); }); + sessPick($("#ledKey"), "All gateway keys", ledCallerKey, callers.map((k) => ({ + v: k.id, name: k.name, note: "", + })), "Gateway keys", (v) => { ledCallerKey = v; ledOffset = 0; loadLedger().catch((e) => status(e.message, "err")); }); + const seg = $("#ledStatus"); + seg.replaceChildren(); + // every request, those the agent got an error for, and those answered + // after a try that failed first + const shown = ledStatusOf(); + for (const [on, name] of [["", "All"], ["failed", "Failed"], ["retried", "Retried"]]) { + const b = el("button", "opt" + (on === shown ? " on" : ""), t(name)); + if (on === "retried") b.title = t("Show only the requests answered on a retry"); + b.onclick = () => { + if (on === ledStatusOf()) return; + for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b); + slide(seg, "ledStatus"); + ledShowStatus(on); + }; + seg.append(b); + } + slide(seg, "ledStatus"); + $("#ledExport").disabled = !l.total; + + const sum = [t(l.total === 1 ? "{n} request" : "{n} requests", { n: ledNum(l.total) })]; + if (l.total) { + sum.push(t("{n} in", { n: fmtN(l.input) }), t("{n} out", { n: fmtN(l.output) }), t("{n} cache write", { n: fmtN(l.cache_write) }), t("{n} cache read", { n: fmtN(l.cache_read) })); + if (l.errors) sum.push(t("{n} failed", { n: l.errors })); + if (l.retried) sum.push(t("{n} answered on a retry", { n: l.retried })); + } + $("#ledSum").textContent = sum.join(" · "); + // the two sources and their total, in the same block of cells as the totals + // above them: what magpie carried, what it only read about in the agents' + // own session files, and the two together. Each is a filter: picking one + // lists only its requests, and the total is the way back. Its own numbers + // are counted with the pick cleared (usage.RequestPage), so all three stay + // switchable whichever is on. + const via = $("#ledVia"); + const thru = l.through || { calls: 0 }, dir = l.direct || { calls: 0 }, rep = l.reported || { calls: 0 }; + if (thru.calls + dir.calls + rep.calls > 0) { + // the total is the two sources added up, not the page's own totals: those + // are the rows the filter keeps, so with one source picked the total cell + // would read that one's figures under the whole period's count + const all = {}; + for (const k of ["calls", "errors", "input", "output", "cache_read", "cache_write", "cost", "timed", "ttft_ms", "decode_ms", "decode_out"]) { + all[k] = (thru[k] || 0) + (dir[k] || 0) + (rep[k] || 0); + } + const tile = (b, label, calls, tot, pick) => { + const on = ledVia === pick; + b.className = "blk" + (on ? " on" : ""); + b.type = "button"; + b.setAttribute("aria-pressed", on ? "true" : "false"); + b.title = pick ? t("Show only these requests") : t("Show every request again"); + const v = el("span", "v", ledNum(calls)); + // the unit, so a bare number isn't read as the tokens below it + v.append(el("em", "", t(calls === 1 ? "request" : "requests"))); + b.replaceChildren(el("span", "k", t(label)), v, + el("span", "sub", t("{n} tokens", { n: fmtN(allTokens(tot)) }))); + b.onclick = () => { + const next = ledVia === pick ? "" : pick; + if (next === ledVia) return; + ledVia = next; + ledOffset = 0; + loadLedger().catch((e) => status(e.message, "err")); + }; + return b; + }; + // the calls apps reported themselves (#1874) are a fourth cell, once + // there are some, or while they are the ones picked + const n = rep.calls > 0 || ledVia === "reported" ? 4 : 3; + // the cells are the same elements from one redraw to the next, so + // one being pressed or focused is never swapped out from under a reader + let cells = [...via.children]; + if (cells.length !== n) { + cells = cells.slice(0, n); + while (cells.length < n) cells.push(el("button")); + via.replaceChildren(...cells); + } + via.style.setProperty("--vias", String(n)); + tile(cells[0], "all requests", thru.calls + dir.calls + rep.calls, all, ""); + tile(cells[1], "through magpie", thru.calls, thru, "through"); + tile(cells[2], "not through magpie", dir.calls, dir, "direct"); + if (n === 4) tile(cells[3], "reported by apps", rep.calls, rep, "reported"); + via.hidden = false; + } else { + via.replaceChildren(); + via.hidden = true; + } + const routeFilter = $("#ledRoute"); + routeFilter.hidden = !ledRoute; + $("#ledRouteLabel").textContent = ledRouteInfo ? t("Request: {what}", { what: new Date(ledRouteInfo.time).toLocaleString(intlLang()) + " · " + ledRouteInfo.model }) : ""; + $("#ledRouteClear").title = t("Clear filter"); + $("#ledRouteClear").setAttribute("aria-label", t("Clear filter")); + $("#ledRouteClear").onclick = () => { + ledRoute = 0; ledRouteInfo = null; + if (ledBeforeRoute) ({ period, ledOffset, ledPurpose = "", ledAgent, ledProvider, ledAccount = "", ledCallerKey, ledFailed, ledRetried = false, ledQuery, ledModel, ledComputer = "", ledDay = "", ledVia = "" } = ledBeforeRoute); + ledBeforeRoute = null; + $("#ledQ").value = ledQuery; + loadLedger().catch((e) => status(e.message, "err")); + }; + renderLedgerDash(l); + drawLedHeat(); + + const wrap = $("#ledWrap"); + const pager = $("#ledPager"); + if (!l.total) { + wrap.classList.add("none"); + const filtered = ledPurpose || ledDay || ledRoute || ledAgent || ledProvider || ledAccount || ledComputer || ledCallerKey || ledModel || ledVia || ledFailed || ledRetried || ledQuery.trim(); + const none = noCallsIn(period); + wrap.replaceChildren(el("div", "led-none", filtered ? t("No requests match these filters.") : t(none))); + ledFit(); + ledHScroll(); + pager.hidden = true; + $("#ledNote").textContent = ""; + return; + } + wrap.classList.remove("none"); + const table = el("table", "led"); + const head = el("tr"); + for (const [name, cls, opt] of LED_COLS) head.append(el("th", (cls || "") + (opt ? " lc-opt" : ""), t(name))); + table.append(el("thead"), el("tbody")); + table.tHead.append(head); + for (const r of l.rows) { + const bad = ledFailed_(r); + const key = ledKey(r); + const tr = el("tr", "led-row" + (bad ? " bad" : "") + (ledOpen.has(key) ? " open" : "")); + tr.tabIndex = 0; + tr.setAttribute("aria-expanded", ledOpen.has(key) ? "true" : "false"); + const td = (child, cls, title) => { + const c = el("td", (cls || "") + (LED_COLS[tr.childElementCount]?.[2] ? " lc-opt" : "")); + if (typeof child === "string") c.textContent = child; else c.append(child); + if (title) c.title = title; + tr.append(c); + return c; + }; + const routed = r.route_id && !featuresOff.has("routing"); // the Routing page there to open it on + const when = routed ? el("button", "text led-route-link", ledTime(r.t)) : ledTime(r.t); + if (routed) { + when.title = t("View routing"); + // the link opens the route, not the row's details as well + when.onclick = (e) => { e.stopPropagation(); window.openRoute(r.route_id, r.t).catch((err) => status(err.message, "err")); }; + } + td(when, "when", new Date(r.t).toLocaleString(intlLang())); + const who = el("span", "who"); + // an agent on another computer, whose magpie passed the request on + const name = r.agentName || r.agent; + // one made on another computer, whose usage sync brought (#542) + const at = r.computerName ? t("{agent} · on {computer}", { agent: name, computer: r.computerName }) : name; + who.append(icon(r.icon || "generic"), el("span", "", [r.via ? t("{agent} · via {host}", { agent: at, host: r.via }) : at, r.callerKeyLabel || r.callerKeyName].filter(Boolean).join(" · "))); + // a request magpie made by itself, apart from the agents' own (#1839) + if (r.agent === "magpie") who.append(ownBadge()); + td(who, "", [r.kind, r.session && t("session {id}", { id: r.session })].filter(Boolean).join(" · ")); + td(r.req || "—", "model" + (r.req ? "" : " faint"), r.req || t("Not kept for requests before this version")); + const local = r.source === "log"; + // A session file names the provider it was set up to call, which is + // where a call that went straight to a vendor went: nothing stood + // between the agent and it. It is the file's own record and not a route + // magpie saw, so the id the file carries is shown as it is — never + // resolved to a provider's name, which would promote an unknown request + // to an official provider — and the row keeps saying it is a local + // session. A row whose file names none says only that. + const where = local ? (r.session_account || r.session_provider || t("Local session")) : t(r.providerName) + (r.host ? " · " + r.host : ""); + const wc = td(el("div", "where-name", where), "where", where); + const badges = el("div", "source-badges"); + if (local && r.session_account && r.session_official_login) { + const badge = el("span", "src official", t("OFFICIAL")); + badge.title = t("Official login confirmed for this account by local login metadata. This does not establish the route or authentication used for this request."); + badges.append(badge); + } + let access = ""; + if (!local && r.access === "subscription") access = "Subscription"; + else if (!local && r.access === "api") access = "API"; + if (access) { + const badge = el("span", "src access access-" + r.access, t(access)); + badge.title = t(access); + badges.append(badge); + } + const proto = ledProtoBadge(r); + if (proto) badges.append(proto); + // the badge says where the row came from, beside a name that is not + // that: a row whose name already says it has nothing to add + if (local && (r.session_account || r.session_provider)) { + const k = el("span", "src local", t("Local session")); + k.title = r.session_provider + ? t("Read from the agent's session file, which names the provider it was set up to call. The name shown is that record, not a route magpie saw.") + : t("Read from the agent's session file. The account is shown only when local metadata identifies it; no service provider is inferred."); + badges.append(k); + } + // a call an app reported itself (#1874): it went straight to its vendor + if (r.source === "reported") { + const k = el("span", "src reported", t("Reported")); + k.title = t("Reported by the app that made it, through POST /v1/magpie/usage/requests: the call went straight to its vendor, not through magpie."); + badges.append(k); + } + if (badges.childElementCount) wc.append(badges); + // the model sent is what the gateway sent the vendor: a session file has none + // The log names a model, but does not capture the outbound HTTP request. + td(r.model || "—", "model " + (r.model ? "model-value" : "faint"), r.source === "log" && r.model ? t("Model recorded in the local session log; the outbound HTTP request was not captured.") : r.model); + td(ledServed(r), "model"); + td(r.effort || "—", r.effort ? "" : "faint"); + td(ledNum(r.in), "n"); + td(ledNum(r.out), "n", r.reasoning ? t("{n} reasoning, inside output", { n: ledNum(r.reasoning) }) : ""); + td(ledNum(r.cache_write), "n" + (r.cache_write ? "" : " faint"), cacheTTLs(r, ledNum).replace(/^ · /, "")); + td(ledNum(r.cache_read), "n" + (r.cache_read ? "" : " faint")); + const cost = td(r.priced ? "≈" + fmtCost({ cost: r.cost, unpriced: 0 }) : "—", "n cost" + (r.priced ? "" : " faint"), r.priced ? (r.pricing_model ? t("API price reference") + ": " + r.pricing_model : "") : t("No known price for this model")); + if (r.priced && r.pricing_model) { + const reference = el("div", "price-reference", t("Price reference: {model}", { model: r.pricing_model })); + reference.title = t("Model used for the API price estimate; this is not an observed model forwarding event."); + cost.append(reference); + } + // a session file has the times of its lines: a call took about from the line that + // asked for it to its last; some have none, and are dashes, not 0 ms + const timed = r.source === "log"; + const untimed = !Number.isFinite(r.ms) || r.ms <= 0; + const durationBand = untimed ? "" : r.ms <= 10000 ? "fast" : r.ms <= 30000 ? "slow" : "long"; + td(untimed ? "—" : (timed ? "≈" : "") + ledTook(r.ms), "n duration " + (untimed ? "faint" : "duration-" + durationBand), + [!untimed ? t("{n} ms", { n: ledNum(r.ms) }) : "", !untimed ? t("Duration colors: ≤10 s green · 10–30 s amber · >30 s red") : "", timed && !untimed ? t("About: told from the session file's times, a little more or less than it took") : "", r.ttft_ms ? t("TTFT {ms}", { ms: ledTook(r.ttft_ms) }) : ""].filter(Boolean).join(" · ")); + // how fast it wrote once it began, as CC Switch's log has it (#860) + const v = ledRowSpeed(r), floor = ledFloorSpeed(r); + td(v ? t("{n} tok/s", { n: ledNum(Math.round(v)) }) : floor ? "≥" + t("{n} tok/s", { n: ledNum(Math.round(floor)) }) : "—", "n speed" + (v || floor ? "" : " faint"), + v ? (r.reasoning > 0 && r.first_text_ms > 0 ? t("{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out", { n: ledNum(ledDecode(r).n), ms: ledTook(ledDecode(r).w), r: ledNum(r.reasoning) }) + : t("{n} output tokens in {ms} after the first", { n: ledNum(ledDecode(r).n), ms: ledTook(ledDecode(r).w) })) + " · " + t("TTFT {ms}", { ms: ledTook(r.ttft_ms) }) + : floor && ledFloor_(r).answer ? t("At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. The session file has no first text, so reasoning after the first token is counted too", { n: ledNum(ledFloor_(r).n), ms: ledTook(ledFloor_(r).w), r: ledNum(r.reasoning) }) + " · " + t("TTFT {ms}", { ms: ledTook(r.ttft_ms) }) + : floor && ledFloor_(r).turn ? t("At least: {n} output tokens in {ms}, the whole turn. What came after the first token ({after}) is too little to time a speed by: under a second or under 100 tokens, so the wait for it is counted too", { n: ledNum(r.out), ms: ledTook(r.ms), after: ledTook(r.ms - r.ttft_ms) }) + " · " + t("TTFT {ms}", { ms: ledTook(r.ttft_ms) }) + : floor ? t("At least: {n} output tokens in {ms}, from the line that asked for it to its last. The session file has no first token, so the wait for it is counted too", { n: ledNum(r.out), ms: ledTook(r.ms) }) + : r.ttft_ms || untimed || ledFailed_(r) ? "" : timed ? t("The session file has no first token to time a speed from") : t("Not streamed: no first token to time a speed from")); + const st = el("span", "st"); + // a status when the gateway logged the call; a session file has none, + // and says only whether it went well + let word = r.status ? String(r.status) : r.source === "log" ? (bad ? r.err_type || t("Failed") : t("Succeeded")) : "—"; + if (r.status && bad && r.err_type) word += " · " + r.err_type; + if (r.handed_on) word += " · " + t("handed on"); + else if (r.tries > 1) word += " · " + t("{n} tries", { n: r.tries }); + st.append(el("i", "dot"), document.createTextNode(word)); + td(st, "", [r.handed_on && t("This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try"), + bad ? (r.err || t("Failed: the agent was answered {status}", { status: r.status })) : ""].filter(Boolean).join("\n")); + const detail = ledOpen.has(key) ? ledDetail(r, LED_COLS.length) : null; + const toggle = () => { + if (ledOpen.delete(key)) { tr.classList.remove("open"); tr.setAttribute("aria-expanded", "false"); tr.nextElementSibling?.classList.contains("led-detail") && tr.nextElementSibling.remove(); return; } + ledOpen.add(key); + tr.classList.add("open"); + tr.setAttribute("aria-expanded", "true"); + tr.after(ledDetail(r, LED_COLS.length)); + }; + // a click that ends a text selection is the reader copying, not asking + tr.onclick = () => { if (!String(getSelection() || "")) toggle(); }; + tr.onkeydown = (e) => { if (e.target === tr && (e.key === "Enter" || e.key === " ")) { e.preventDefault(); toggle(); } }; + table.tBodies[0].append(tr); + if (detail) table.tBodies[0].append(detail); + } + wrap.replaceChildren(table); + wrap.style.setProperty("--ledw", wrap.clientWidth + "px"); + ledFit(); + ledHScroll(); + ledGrow.disconnect(); + ledGrow.observe(table); + + // a page at a time: the newest first + pager.hidden = l.total <= LED_PAGE; + pager.replaceChildren(); + if (!pager.hidden) { + const prev = el("button", "text", t("Newer")); + const next = el("button", "text", t("Older")); + prev.disabled = l.offset <= 0; + next.disabled = l.offset + l.rows.length >= l.total; + prev.onclick = () => { ledOffset = Math.max(0, l.offset - LED_PAGE); loadLedger().catch((e) => status(e.message, "err")); }; + next.onclick = () => { ledOffset = l.offset + LED_PAGE; loadLedger().catch((e) => status(e.message, "err")); }; + pager.append(prev, el("span", "", t("{a}–{b} of {n}", { a: ledNum(l.offset + 1), b: ledNum(l.offset + l.rows.length), n: ledNum(l.total) })), next); + } + $("#ledNote").textContent = t("Each request's tokens as its provider reported them; the cost estimated using effective model prices, including custom prices. Export CSV saves every page."); +} + +{ + let typing = 0; + $("#ledQ").oninput = (e) => { + ledQuery = e.target.value; + ledModel = ""; + clearTimeout(typing); + typing = setTimeout(() => { ledOffset = 0; loadLedger().catch((err) => status(err.message, "err")); }, 250); + }; + $("#ledQ").onkeydown = (e) => { + if (e.key === "Escape" && e.target.value) { e.stopPropagation(); e.target.value = ""; ledQuery = ""; ledModel = ""; ledOffset = 0; loadLedger().catch((err) => status(err.message, "err")); } + }; + $("#ledExport").onclick = async () => { + const b = $("#ledExport"); + // in a browser the file comes to it; in the app it goes to Downloads + if (web) { + const a = el("a"); + a.href = "/api/usage/requests.csv?" + ledParams(); + a.download = ""; + a.click(); + return; + } + b.classList.add("busy"); + try { + const r = await api("usage/requests/export?" + ledParams(), {}); + status(t(r.rows === 1 ? "Saved {n} request to {path}" : "Saved {n} requests to {path}", { n: ledNum(r.rows), path: r.path }), "ok"); + } catch (e) { + status(e.message, "err"); + } finally { + b.classList.remove("busy"); + } + }; +} + +// ---------- sessions ---------- +// +// The agents' own sessions, read from their session files: what each cost, +// and the command that picks it up again. A segment of the Usage page. + +const USAGE_TABS = [["usage", "Overview"], ["requests", "Requests"], ["sessions", "Sessions"], ["context", "Context"]]; +let usageTab = "usage"; +try { const k = localStorage.getItem("magpie.usageTab"); if (USAGE_TABS.some(([id]) => id === k)) usageTab = k; } catch {} +let sessAgent = "all"; +let sessQuery = ""; +// The list is drawn in pages: every session is read (so the count beside it +// and the list agree), but a filter click or a keystroke in Search draws +// SESS_PAGE rows and no more, and "Show N more" appends the next page. A +// history of thousands rebuilt whole on every keystroke took ~300ms a +// keystroke on a fast Mac (yetone, #1019). sessShown resets to one page +// whenever the filters change, so what is drawn never grows with the history. +const SESS_PAGE = 200; +let sessShown = SESS_PAGE; +// What the last draw put in the list, for the note under it to say: drawn is +// the rows drawn and total the rows the filters kept — the same list, so a +// search that matches one session says "1 session", never "1 of 2600" (the +// note is about the list, not about every session on the computer). +let sessDrawn = null, sessTotal = null; +// what the drawn list was filtered by, so a redraw from the same filters +// keeps the pages opened and a changed one starts again at the first +let sessListKey = null; +// The totals and the chart are every session's, by day, over a range; the +// list is the latest sessions within it. [id, name, days (0: all)] +const SESS_RANGES = [["today", "Today", 1], ["7d", "7 days", 7], ["30d", "30 days", 30], ["90d", "90 days", 90], ["all", "All", 0]]; +let sessRange = "30d"; +// what the activity chart counts each day +const SESS_METRICS = [["tokens", "Tokens"], ["output", "Output tokens"], ["messages", "Messages"], ["sessions", "Sessions"], ["cost", "Cost"], ["active", "Active"]]; +let sessMetric = "tokens"; +// what the top sessions are the top by +const SESS_TOPS = [["tokens", "Tokens"], ["cost", "Cost"], ["active", "Active"]]; +let sessTopBy = "tokens"; +try { + const r = localStorage.getItem("magpie.sessRange"); + if (SESS_RANGES.some(([id]) => id === r)) sessRange = r; + const m = localStorage.getItem("magpie.sessMetric"); + if (SESS_METRICS.some(([id]) => id === m)) sessMetric = m; + const b = localStorage.getItem("magpie.sessTop"); + if (SESS_TOPS.some(([id]) => id === b)) sessTopBy = b; +} catch {} +let sessStats = null; // { from, to, days: [{ date, usage, active }], agents } for sessRange +let sessModel = ""; // "" for every model +let sessFolder = ""; // "" for every folder +// the sessions of the range summed up under the filters, by the server: +// { count, median, p90, days, top: { tokens, cost, active } }, and the +// query it answers +let sessOver = null; +let sessOverAt = ""; +let sessOverLoading = ""; +let sessTopOpen = ""; // the top session opened to its details +const sessFull = new Map(); // a top session's key → the session read whole, or "…" while it is read + +function renderUsageTab() { + const seg = $("#usageTab"); + seg.replaceChildren(); + for (const [id, name] of USAGE_TABS) { + const b = el("button", "opt" + (id === usageTab ? " on" : ""), t(name)); + b.onclick = () => { + if (id === usageTab) return; + usageTab = id; + try { localStorage.setItem("magpie.usageTab", id); } catch {} + $("#usageCost").replaceChildren(); + // to the Overview is to the allowances (#1588) + loadUsage(id === "usage").catch((e) => status(e.message, "err")); + }; + seg.append(b); + } + slide(seg, "usageTab"); + const on = usageTab === "sessions"; + // the Context tab has its own range, in its pane + $("#period").hidden = on || usageTab === "context"; + $("#sessRange").hidden = !on; + $("#ctxRange").hidden = usageTab !== "context"; + $("#usagePane").hidden = usageTab !== "usage"; + $("#ledgerPane").hidden = usageTab !== "requests"; + $("#sessionsPane").hidden = !on; + $("#contextPane").hidden = usageTab !== "context"; +} + +const sessDays = () => SESS_RANGES.find(([id]) => id === sessRange)[2]; +async function loadSessions() { + const first = !sessions || !sessStats; + if (first) renderSessionsLoading(); + const range = sessRange, q = sessOverQ(); + const stop = first ? sessWatchIndex() : () => {}; + let s, st, o; + try { + [s, st, o] = await Promise.all([api("sessions"), api("sessions/stats?days=" + sessDays()), api("sessions/overview?" + q)]); + } finally { stop(); } + if (range !== sessRange) return; // another range was picked meanwhile; its load draws + const fresh = q === sessOverQ(); // no filter changed meanwhile + if (sessions && sessStats && JSON.stringify(s) === JSON.stringify(sessions) && JSON.stringify(st) === JSON.stringify(sessStats) && + (!fresh || JSON.stringify(o) === JSON.stringify(sessOver))) return; + sessions = s; + sessStats = st; + if (fresh) { sessOver = o; sessOverAt = q; } + if (view === "usage" && usageTab === "sessions") renderSessions(); +} + +// the overview's query: the range and the filters +const sessOverQ = () => new URLSearchParams({ days: sessDays(), agent: sessAgent === "all" ? "" : sessAgent, model: sessModel, cwd: sessFolder }).toString(); +// loadSessOverview reads the overview again when a filter changes, and draws +// the page once it is in; one read at a time for a query +function loadSessOverview() { + const q = sessOverQ(); + if (sessOverLoading === q) return; + sessOverLoading = q; + const done = () => { if (sessOverLoading === q) sessOverLoading = ""; }; + api("sessions/overview?" + q).then((o) => { + done(); + if (q !== sessOverQ()) return; + sessOver = o; + sessOverAt = q; + if (view === "usage" && usageTab === "sessions" && sessions && sessStats) renderSessions(); + }, (e) => { done(); status(e.message, "err"); }); +} + +function renderSessionsLoading() { + const view = $("#view-usage"); + view.classList.add("loading"); + view.setAttribute("aria-busy", "true"); + $("#usageCost").replaceChildren(el("span", "skeleton sk-cost")); + renderSessRange(true); + $("#sessAgent").replaceChildren(); + $("#sessModel").hidden = $("#sessFolder").hidden = true; + $("#sessChart").hidden = true; + $("#sessGrid").hidden = true; + $("#sessListHead").hidden = true; + const stats = $("#sessStats"); + stats.classList.remove("empty"); + stats.classList.add("six"); + stats.replaceChildren(); + for (let i = 0; i < 6; i++) { + const tile = el("div", "kpi loading-kpi"); + tile.append(el("span", "skeleton sk-number"), el("span", "skeleton sk-label")); + stats.append(tile); + } + const list = $("#sessList"); + list.hidden = false; + list.replaceChildren(); + for (let i = 0; i < 4; i++) { + const r = el("div", "row sess-sk"); + r.append(el("span", "skeleton sk-title"), el("span", "skeleton sk-line short")); + list.append(r); + } + $("#sessNote").textContent = t("Reading the agents' session files…"); +} + +const SESS_INDEX_SHOW = 700; + +// sessWatchIndex asks how far the reading of the session files has got +// while the page waits on it; a read of the kept index, over in a moment, +// shows the skeleton alone, and one that takes a while the indexing show. +// It returns the stop. +function sessWatchIndex() { + let on = true, timer = 0, shown = false, since = 0; + const tick = async () => { + if (!on) return; + let p = null; + try { p = await api("sessions/progress"); } catch {} + if (!on) return; + // only a real indexing run is shown: a read of the kept index, however + // long, keeps the skeleton, and so does the catch-up read of the few + // files the agents wrote to since (every reload has some, while an agent + // is at work), over well before SESS_INDEX_SHOW; the show would play + // again from nought for it + since = p?.indexing ? since || Date.now() : 0; + const long = since && Date.now() - since >= SESS_INDEX_SHOW; + if (p && (long || shown) && view === "usage" && usageTab === "sessions") { + const stats = $("#sessStats"); + let hero = stats.querySelector(".sess-indexing"); + if (!hero) { + hero = sessIndexHero(); + stats.replaceChildren(hero); + } + // an earlier watch's stop may have taken the class off the hero kept + stats.classList.add("indexing"); + shown = true; + hero.update(p); + } + timer = setTimeout(tick, 350); + }; + timer = setTimeout(tick, 150); + return () => { + on = false; + clearTimeout(timer); + if (shown) $("#sessStats").classList.remove("indexing"); + }; +} + +// sessIndexHero is the show put on while the session files are read: the +// words and how far it has got on the left, on the right a field of dots, the +// heatmap's cells, that light up as the files land, a wave running through +// them; a hairline along the foot. Still with reduced motion. +const SESS_TIPS = [ + "Read once, kept: after this the page opens from the index in a blink", + "Only what changed is read again, from where it was left", + "Every session is read on this computer; nothing leaves it", + "The biggest files go first, so none is left running on alone", +]; +function sessIndexHero() { + const hero = el("div", "sess-indexing"); + hero.setAttribute("role", "status"); + const field = el("div", "si-field"); + const cv = el("canvas", "si-canvas"); + cv.setAttribute("aria-hidden", "true"); + field.append(cv); + const words = el("div", "si-words"); + const head = el("div", "si-head"); + head.append(el("i", "si-spin"), el("span", "si-title", t("Indexing your sessions"))); + const pct = el("div", "si-pct"); + const num = el("b", "", ""); + pct.append(num, el("span", "", "%")); + const line = el("div", "si-line", t("Looking for session files…")); + const tip = el("div", "si-tip", t(SESS_TIPS[0])); + words.append(head, pct, line, tip); + const bar = el("div", "si-bar"); + const fill = el("i", ""); + bar.append(fill); + hero.append(words, field, bar); + + const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches; + let frac = 0, shown = 0, known = false, tipAt = Date.now(), tipI = 0, rate = 0, last = null; + let done = false; + hero.update = (p) => { + if (!(p.indexing && p.bytes > 0) && known) { + // the run is over while the page is put together: held full, never + // back to the unknown state or a second run from nought + if (!done) { + done = true; + frac = 1; + fill.style.width = "100%"; + hero.classList.add("done"); + line.textContent = t("Indexed · putting the page together…"); + } + return; + } + if (done) return; + known = !!p.indexing && p.bytes > 0; + const f = known ? Math.min(1, p.read / p.bytes) : 0; + // a steady speed, for the time left + if (known && last && p.read > last.read) { + const r = (p.read - last.read) / ((Date.now() - last.at) / 1000); + rate = rate ? rate * 0.8 + r * 0.2 : r; + } + if (known) last = { read: p.read, at: Date.now() }; + frac = Math.max(frac, f); + hero.classList.toggle("known", known); + fill.style.width = known ? (frac * 100).toFixed(1) + "%" : ""; + if (known) { + line.textContent = t("{done} of {files} files · {read} of {bytes}", { done: fmtN(p.done), files: fmtN(p.files), read: fmtBytes(p.read), bytes: fmtBytes(p.bytes) }); + const left = rate > 0 ? (p.bytes - p.read) / rate : 0; + if (left > 3) line.textContent += " · " + t("about {t} left", { t: left < 60 ? t("{n}s", { n: Math.ceil(left) }) : t("{n} min", { n: Math.ceil(left / 60) }) }); + } else line.textContent = t("Reading the kept index…"); + if (Date.now() - tipAt > 4500) { + tipAt = Date.now(); + tipI = (tipI + 1) % SESS_TIPS.length; + tip.classList.remove("in"); + void tip.offsetWidth; + tip.textContent = t(SESS_TIPS[tipI]); + tip.classList.add("in"); + } + if (reduced) paint(0); + }; + + // the drawing: each dot has its turn, mostly left to right, a little + // scattered, so the edge of what is read is ragged like rain landing + const ctx = cv.getContext("2d"); + const GAP = 14; + let W = 0, H = 0, dpr = 1, dots = [], ink = "#1c1c21", accent = "#4f46e5", frame = 0; + const colours = () => { + const c = getComputedStyle(hero); + ink = c.getPropertyValue("--fg").trim() || ink; + accent = c.getPropertyValue("--accent").trim() || accent; + }; + const size = () => { + dpr = devicePixelRatio || 1; + const r = cv.getBoundingClientRect(); + if (!r.width || !r.height) return false; + if (r.width !== W || r.height !== H) { + W = r.width; H = r.height; + cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr); + const cols = Math.max(1, Math.floor((W - 4) / GAP)), rows = Math.max(1, Math.floor((H - 4) / GAP)); + const ox = (W - (cols - 1) * GAP) / 2, oy = (H - (rows - 1) * GAP) / 2; + dots = []; + for (let j = 0; j < rows; j++) for (let i = 0; i < cols; i++) { + const seed = Math.random(); + dots.push({ x: ox + i * GAP, y: oy + j * GAP, nx: cols > 1 ? i / (cols - 1) : 0, ny: rows > 1 ? j / (rows - 1) : 0, seed, turn: (cols > 1 ? i / (cols - 1) : 0) * 0.86 + seed * 0.14 }); + } + } + return true; + }; + function paint(now) { + if (!size()) return; + if (frame++ % 30 === 0) colours(); + const T = now / 1000; + ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + ctx.clearRect(0, 0, W, H); + shown += (frac - shown) * (reduced ? 1 : 0.06); + // unknown: a band of light sweeps across and on again + const scan = ((T * 0.32) % 1.4) - 0.2; + // a faint glow where the reading is + const gx = (known ? shown * 0.86 + 0.07 : scan) * W; + const glow = ctx.createRadialGradient(gx, H / 2, 0, gx, H / 2, H * 0.9); + glow.addColorStop(0, hexA(accent, reduced ? 0.06 : 0.1)); + glow.addColorStop(1, hexA(accent, 0)); + ctx.fillStyle = glow; + ctx.fillRect(0, 0, W, H); + for (const d of dots) { + const wave = reduced ? 0.5 : 0.5 + 0.5 * Math.sin(d.nx * 7 + d.ny * 2.4 - T * 1.5 + d.seed * 0.8); + let a = 0.08 + 0.05 * wave, r = 1.05 + 0.2 * wave, c = ink; + if (known) { + const since = shown - d.turn; + if (since >= 0) { + // read: resting in the accent, just landed brighter and bigger + const fresh = Math.max(0, 1 - since / 0.07); + c = accent; + a = 0.4 + 0.32 * wave * (0.3 + d.seed) + 0.5 * fresh; + r = 1.25 + 0.25 * wave + 1.1 * fresh * fresh; + } else if (since > -0.035 && !reduced) { + // about to land: a flicker + const near = 1 + since / 0.035; + if (Math.sin(T * 9 + d.seed * 40) > 0.3) { c = accent; a = 0.1 + 0.35 * near; } + } + } else if (!reduced) { + const g = Math.exp(-(((d.nx - scan) / 0.07) ** 2)); + if (g > 0.02) { c = accent; a = Math.max(a, 0.9 * g * (0.55 + 0.45 * d.seed)); r += 1 * g; } + } + ctx.globalAlpha = Math.min(1, a); + ctx.fillStyle = c; + ctx.beginPath(); + ctx.arc(d.x, d.y, r, 0, Math.PI * 2); + ctx.fill(); + } + ctx.globalAlpha = 1; + num.textContent = known ? String(Math.floor(shown * 100)) : ""; + } + // it runs until the page takes it away + const loop = (now) => { + if (!hero.isConnected) return; + paint(now); + requestAnimationFrame(loop); + }; + if (!reduced) requestAnimationFrame(loop); + else requestAnimationFrame(() => paint(0)); + return hero; +} +// hexA is a #rrggbb colour at an alpha +function hexA(hex, a) { + const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim()); + if (!m) return `rgba(79,70,229,${a})`; + const n = parseInt(m[1], 16); + return `rgba(${n >> 16},${(n >> 8) & 255},${n & 255},${a})`; +} +const sessKey = (s) => s.agent + ":" + s.id; +const sessTokens = (s) => s.input + s.output; +// a session's cost: "—" when none of its models has a known price +function sessCost(s) { + if (!s.models.some((m) => m.priced && (m.input || m.output || m.cache_read || m.cache_write))) return "—"; + return "≈" + fmtCost({ cost: s.cost, unpriced: s.unpriced }); +} +// the range picker, in the page's head where the Overview's period is +function renderSessRange(loading) { + const seg = $("#sessRange"); + seg.replaceChildren(); + for (const [id, name] of SESS_RANGES) { + const b = el("button", "opt" + (id === sessRange ? " on" : ""), t(name)); + b.disabled = !!loading; + b.onclick = () => { + if (id === sessRange) return; + sessRange = id; + try { localStorage.setItem("magpie.sessRange", id); } catch {} + sessStats = null; + loadSessions().catch((e) => status(e.message, "err")); + }; + seg.append(b); + } + slide(seg, "sessRange"); +} + +// a "YYYY-MM-DD" as a local date, and back +const sessDate = (d) => { const [y, m, day] = d.split("-").map(Number); return new Date(y, m - 1, day); }; +const sessISO = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; +const sessDay = (d) => d.toLocaleDateString(intlLang(), { month: "short", day: "numeric" }); +// a length of time, as hours and minutes +function fmtDur(sec) { + const m = Math.round(sec / 60); + if (!sec) return "0"; + if (m < 1) return t("<1m"); + if (m < 60) return t("{m}m", { m }); + return t("{h}h {m}m", { h: Math.floor(m / 60), m: m % 60 }); +} + +function renderSessions() { + const view = $("#view-usage"); + view.classList.remove("loading"); + view.removeAttribute("aria-busy"); + renderSessRange(); + const all = sessions?.sessions || []; + const st = sessStats || { from: "", to: "", days: [], agents: {} }; + const rows = st.days.flatMap((d) => d.usage.map((u) => ({ ...u, date: d.date }))); + const acts = st.days.flatMap((d) => d.active.map((a) => ({ ...a, date: d.date }))); + + // one segment per agent that has sessions, or usage in the range + const agents = [...new Map([...all.map((s) => [s.agent, s.name]), ...Object.entries(st.agents || {})]).entries()]; + if (sessAgent !== "all" && !agents.some(([id]) => id === sessAgent)) sessAgent = "all"; + const seg = $("#sessAgent"); + seg.hidden = agents.length < 2; + const opts = [["all", t("All")], ...agents]; + // the same agents keep their buttons: drawn anew, a strip with more than + // fit (#929) would lose where it was scrolled to (WebKit) + const was = [...seg.querySelectorAll(":scope > .opt")]; + if (was.length !== opts.length || was.some((b, i) => b.dataset.agent !== opts[i][0] || b.textContent !== opts[i][1])) { + seg.replaceChildren(); + for (const [id, name] of opts) { + const b = el("button", "opt", name); + b.dataset.agent = id; + b.onclick = () => { sessAgent = id; renderSessions(); }; + seg.append(b); + } + } + for (const b of seg.querySelectorAll(":scope > .opt")) { + b.classList.toggle("on", b.dataset.agent === sessAgent); + b.setAttribute("aria-pressed", String(b.dataset.agent === sessAgent)); + } + // and the agent picked is brought into the strip, the page left where it is + const picked = seg.querySelector(":scope > .on"); + if (picked && seg.scrollWidth > seg.clientWidth) { + if (picked.offsetLeft < seg.scrollLeft) seg.scrollLeft = picked.offsetLeft; + else if (picked.offsetLeft + picked.offsetWidth > seg.scrollLeft + seg.clientWidth) seg.scrollLeft = picked.offsetLeft + picked.offsetWidth - seg.clientWidth; + } + slide(seg, "sessAgent"); + + // the model and folder filters offer what the range has, under the other filters + const byAgent = (x) => sessAgent === "all" || x.agent === sessAgent; + const byModel = (x) => !sessModel || x.model === sessModel; + const byFolder = (x) => !sessFolder || x.cwd === sessFolder; + const spent = (list, key) => { + const m = new Map(); + for (const r of list) if (r[key]) m.set(r[key], (m.get(r[key]) || 0) + r.input + r.output); + return [...m.entries()].sort((a, b) => b[1] - a[1]); + }; + const models = spent(rows.filter((r) => byAgent(r) && byFolder(r)), "model").map(([v, n]) => ({ v, name: v, note: t("{n} tokens", { n: fmtN(n) }) })); + const folders = spent(rows.filter((r) => byAgent(r) && byModel(r)), "cwd").map(([v, n]) => ({ v, name: baseName(v), note: v + " · " + t("{n} tokens", { n: fmtN(n) }) })); + sessPick($("#sessModel"), "All models", sessModel, models, "Model", (v) => { sessModel = v; renderSessions(); }); + sessPick($("#sessFolder"), "All folders", sessFolder, folders, "Folder", (v) => { sessFolder = v; renderSessions(); }); + + // the list: the sessions at work in the range, under every filter. Which + // ones were at work is the range's own answer (st.keys, the sessions + // stats counted), not a guess from s.last: a session's file goes on being + // written after its last call — a fork's seed, a setting — so one whose + // last line falls in the range spent nothing in it, and it was listed but + // not counted, the note beside the list saying more than the KPI above it. + const inRange = st.keys ? new Set(st.keys) : null; + const from = !inRange && sessDays() && st.from ? sessDate(st.from) : null; + const q = sessQuery.trim().toLowerCase(); + const list = all.filter((s) => byAgent(s) && (!sessFolder || s.cwd === sessFolder) && + (!sessModel || s.models.some((m) => m.model === sessModel)) && + (inRange ? inRange.has(s.agent + ":" + s.id) : !from || new Date(s.last) >= from) && + (!q || [s.title, s.cwd, s.id, s.name, ...s.models.map((m) => m.model)].some((x) => (x || "").toLowerCase().includes(q)))); + + // the range's totals, of every session under the filters + const used = rows.filter((r) => byAgent(r) && byModel(r) && byFolder(r)); + const tot = { input: 0, output: 0, cache_read: 0, cache_write: 0, cost: 0, unpriced: 0 }; + const unpriced = new Set(); + for (const r of used) { + for (const k of ["input", "output", "cache_read", "cache_write", "cost"]) tot[k] += r[k]; + if (!r.priced) unpriced.add(r.model); + } + tot.unpriced = unpriced.size; + // active time isn't told apart by model + const active = sessModel ? null : acts.filter((a) => byAgent(a) && byFolder(a)).reduce((n, a) => n + a.seconds, 0); + + const c = tot.cost ? fmtCost(tot) : ""; + const unpricedNote = tot.unpriced ? t("Not counted: {models}, with no known price", { models: sessModelNames([...unpriced]) }) : t("Estimated using effective model prices, including custom prices"); + // a session's models are counted, not its calls: the agents' files price by model + const unpricedModels = tot.unpriced ? t(tot.unpriced === 1 ? "{n} model unpriced" : "{n} models unpriced", { n: tot.unpriced }) : ""; + costHead(c, unpricedModels, unpricedNote); + + // the overview is read again for the filters as they are now; until it is + // in, the last one stands, dimmed + if (sessOverAt !== sessOverQ()) loadSessOverview(); + const ov = sessOver || {}; + const stale = sessOverAt !== sessOverQ(); + + const stats = $("#sessStats"); + stats.replaceChildren(); + const box = $("#sessList"); + box.replaceChildren(); + const chart = $("#sessChart"); + const grid = $("#sessGrid"); + const head = $("#sessListHead"); + if (!used.length && !list.length) { + stats.classList.remove("six"); + stats.classList.add("empty"); + const filtered = sessAgent !== "all" || sessModel || sessFolder || q; + stats.append(el("div", "none", !all.length && !rows.length ? t("No sessions yet. Claude Code's, Codex's, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.") : filtered ? t("No session matches.") : t("Nothing in this range."))); + if (from && all.some((s) => byAgent(s) && byFolder(s) && + (!sessModel || s.models.some((m) => m.model === sessModel)) && + (!q || [s.title, s.cwd, s.id, s.name, ...s.models.map((m) => m.model)].some((x) => (x || "").toLowerCase().includes(q))))) { + stats.firstChild.textContent = t("No sessions in this range"); + const history = el("button", "text sess-show-history", t("All sessions")); + history.onclick = () => { + sessRange = "all"; + try { localStorage.setItem("magpie.sessRange", sessRange); } catch {} + sessStats = null; + loadSessions().catch((e) => status(e.message, "err")); + }; + stats.append(history); + } + box.hidden = true; + chart.hidden = true; + grid.hidden = true; + sessDrawn = 0; + sessTotal = 0; + // the search stays where it was typed, to be cleared + head.hidden = !q; + } else { + stats.classList.remove("empty"); + stats.classList.add("six"); + const tile = (n, label, sub, title, cls) => { + const e = el("div", "kpi" + (cls ? " " + cls : "")); + if (title) e.title = title; + // a figure never wraps: a tile a line taller moves the page when a + // filter shortens it; a time's units step down, as the Health app's do + const b = el("b", ""); + if (cls?.includes("dur")) for (const part of n.split(/(\d+)/)) part && b.append(/^\d+$/.test(part) ? part : el("i", "u", part.trim())); + else b.textContent = n; + b.title = n; + e.append(b, el("span", "", label)); + if (sub) e.append(el("small", "", sub)); + stats.append(e); + }; + const days = new Set(used.map((r) => r.date)).size; + // how many sessions, and what the middle one and the one in ten spent + tile(ov.count == null ? "—" : fmtN(ov.count), t("sessions"), ov.count ? t("median {m} · p90 {p}", { m: fmtN(ov.median), p: fmtN(ov.p90) }) : "", + t("Tokens in and out per session: the middle session's, and what nine in ten stay under"), stale ? "stale" : ""); + tile(fmtN(tot.input + tot.output), t("tokens"), t("{a} in · {b} out", { a: fmtN(tot.input), b: fmtN(tot.output) })); + tile(c ? "≈" + c : "—", t("cost"), unpricedModels || t("at effective prices"), unpricedNote); + // input leaves out what was read from the cache and written to it + const prompt = tot.input + tot.cache_read + tot.cache_write; + tile(fmtN(tot.cache_read), t("cache read"), tot.cache_read && prompt ? t("hit rate {p}", { p: Math.round(100 * tot.cache_read / prompt) + "%" }) : "", tot.cache_write ? t("{n} written", { n: fmtN(tot.cache_write) }) : ""); + tile(active == null ? "—" : fmtDur(active), t("active"), active == null ? t("not kept by model") : t(days === 1 ? "on {n} day" : "on {n} days", { n: days }), + t("The time the sessions were at work: the pauses between one message and the next, each under five minutes"), "dur"); + // how many folders, and how much of it the first took + const byCwd = sessSums(used, "cwd"); + const lead = byCwd[0], spentAll = byCwd.reduce((n, f) => n + f.n, 0); + tile(String(byCwd.length), t("projects"), !lead ? "" : byCwd.length > 1 && spentAll ? t("{p} in {name}", { p: Math.round(100 * lead.n / spentAll) + "%", name: baseName(lead.v) }) : baseName(lead.v), lead?.v || ""); + + const actsIn = sessModel ? null : acts.filter((a) => byAgent(a) && byFolder(a)); + renderSessChart(chart, st, used, ov, actsIn); + grid.hidden = false; + // the folders and models to pick from, as the pickers offer them + sessBars($("#sessProjects"), "Projects", sessSums(rows.filter((r) => byAgent(r) && byModel(r)), "cwd"), sessFolder, (v) => { sessFolder = v; renderSessions(); }, baseName); + sessBars($("#sessModels"), "Models", sessSums(rows.filter((r) => byAgent(r) && byFolder(r)), "model"), sessModel, (v) => { sessModel = v; renderSessions(); }, (v) => v); + renderSessHours($("#sessHours"), actsIn); + renderSessTop(); + renderSessShape(); + renderSessTools(); + renderSessSkills(); + head.hidden = !list.length && !q; + box.hidden = !list.length && !q; + // a page of the list, not all of it: the same filters keep the pages + // opened, a changed one starts at the first (see sessListKey) + const key = [sessAgent, sessModel, sessFolder, sessRange, q].join("\0"); + if (key !== sessListKey) { sessListKey = key; sessShown = SESS_PAGE; } + const page = list.slice(0, sessShown); + sessDrawn = page.length; + sessTotal = list.length; + for (const s of page) box.append(sessionItem(s)); + if (list.length > page.length) { + const more = el("button", "text sess-page-more"); + more.textContent = t("Show {n} more", { n: Math.min(SESS_PAGE, list.length - page.length) }); + more.onclick = () => { sessShown += SESS_PAGE; renderSessions(); }; + box.append(more); + } + if (!list.length && q) box.append(el("div", "empty-state", t("No session matches."))); + } + const dirs = (sessions?.dirs || []).join(" · "); + // The list is every session the filters keep, drawn in pages, so the note + // counts that list and not every session on the computer: a search that + // matches one session says "1 session", not "1 of 2600", which read as if + // the rest were behind a "Show more" that isn't there (yetone, #1019). + // Nothing left to draw, the note is just the list's length, in words a + // reader uses: one session is a session, not "1 sessions". + const parts = [t("Totals count native sessions and gateway requests with a session ID")]; + if (sessDrawn !== null) { + parts.push(sessDrawn < sessTotal + ? t("showing {drawn} of {n}", { drawn: sessDrawn, n: sessTotal }) + : t(sessTotal === 1 ? "{n} session" : "{n} sessions", { n: sessTotal })); + } + if (dirs) parts.push(dirs); + $("#sessNote").textContent = parts.join(" · "); +} + +// sessSums adds up usage rows by one of their fields, the most tokens first +function sessSums(list, key) { + const m = new Map(); + for (const r of list) { + if (!r[key]) continue; + const s = m.get(r[key]) || { v: r[key], n: 0, cost: 0, unpriced: 0 }; + s.n += r.input + r.output; + s.cost += r.cost; + if (!r.priced) s.unpriced++; + m.set(r[key], s); + } + return [...m.values()].sort((a, b) => b.n - a.n); +} + +// sessLevels grades values 0 (none) to 4 by the quartiles of those above 0, +// as a calendar of contributions does. Under eight such values a quartile +// is one value or none, so two days 2% apart could be two shades apart and +// one twice another the same (#1921): a few are graded by their share of the +// busiest instead. +function sessLevels(values) { + const nz = values.filter((v) => v > 0).sort((a, b) => a - b); + if (!nz.length) return () => 0; + if (nz.length < 8) { + const most = nz[nz.length - 1]; + return (v) => v <= 0 ? 0 : Math.min(4, Math.max(1, Math.ceil(4 * v / most - 1e-9))); + } + const q = (p) => nz[Math.min(nz.length - 1, Math.floor(p * nz.length))]; + const [a, b, c, top] = [q(0.25), q(0.5), q(0.75), nz[nz.length - 1]]; + return (v) => v <= 0 ? 0 : v >= top ? 4 : v <= a ? 1 : v <= b ? 2 : v <= c ? 3 : 4; +} +function sessLegend() { + const l = el("span", "sess-legend"); + l.append(el("span", "", t("Less"))); + for (let i = 0; i <= 4; i++) l.append(el("i", "l" + i)); + l.append(el("span", "", t("More"))); + return l; +} +// the short names of the days of the week, Monday first +function sessWeekdays() { + const loc = intlLang(); + return Array.from({ length: 7 }, (_, i) => new Date(2024, 0, 1 + i).toLocaleDateString(loc, { weekday: "short" })); +} +function sessCardHead(title) { + const h = el("div", "sess-card-head"); + h.append(el("span", "label", t(title))); + return h; +} +function sessSegs(opts, cur, choose) { + const seg = el("div", "segs"); + for (const [id, name, off] of opts) { + const b = el("button", "opt" + (id === cur ? " on" : ""), t(name)); + if (off) { b.disabled = true; b.title = off; } + b.onclick = () => { if (id !== cur) choose(id); }; + seg.append(b); + } + return seg; +} + +// renderSessChart draws the range's activity: day by day as bars up to a +// hundred days, as a calendar up to a year, week by week past that. It counts +// tokens (output on top of input, as on the Overview), output tokens alone, +// messages, sessions at work, cost or active time. +function renderSessChart(chart, st, used, ov, acts) { + const perDay = ov.days, msgs = ov.messages; + const first = sessDate(st.from), last = sessDate(st.to); + const n = Math.round((last - first) / 864e5) + 1; + chart.hidden = !(n >= 2); + if (chart.hidden) { chart.dataset.drawn = ""; return; } + const days = [], at = new Map(); + for (let i = 0, d = new Date(first); i < n; i++, d.setDate(d.getDate() + 1)) { + const x = { day: new Date(d), input: 0, output: 0, cost: 0, unpriced: 0, sessions: perDay?.length === n ? perDay[i] : 0, + messages: msgs?.length === n ? msgs[i] : 0, active: 0 }; + days.push(x); + at.set(sessISO(d), x); + } + for (const r of used) { + const x = at.get(r.date); + if (!x) continue; + x.input += r.input; x.output += r.output; x.cost += r.cost; + if (!r.priced) x.unpriced++; + } + for (const a of acts || []) { const x = at.get(a.date); if (x) x.active += a.seconds; } + const off = { sessions: perDay?.length === n ? "" : t("Still counting"), messages: msgs?.length === n ? "" : t("Still counting"), active: acts ? "" : t("not kept by model") }; + const metric = off[sessMetric] ? "tokens" : sessMetric; + const value = (x) => metric === "cost" ? x.cost : metric === "sessions" ? x.sessions : metric === "messages" ? x.messages : + metric === "active" ? x.active : metric === "output" ? x.output : x.input + x.output; + const show = (v) => metric === "cost" ? "≈" + fmtCost({ cost: v }) : metric === "active" ? fmtDur(v) : fmtN(v); + const tip = (x, when) => { + const parts = [x.input + x.output ? t("{n} tokens", { n: fmtN(x.input + x.output) }) : "", x.cost && fmtCost(x) ? "≈" + fmtCost(x) : "", + x.messages ? t(x.messages === 1 ? "{n} message" : "{n} messages", { n: fmtN(x.messages) }) : "", + x.sessions ? t(x.sessions === 1 ? "{n} session" : "{n} sessions", { n: x.sessions }) : "", x.active ? t("{d} active", { d: fmtDur(x.active) }) : ""].filter(Boolean); + return parts.length ? when + " · " + parts.join(" · ") : t("{when} · nothing", { when }); + }; + const shape = n <= 100 ? "day" : n <= 371 ? "calendar" : "week"; + // the page reads the sessions again every few seconds, and while an agent + // is at work today's numbers change each time: the same days by the same + // metric keep their bars, filled in again where they are, so the one under + // the pointer — today's, as often as not — keeps its tooltip (#309) + const drawn = [shape, metric, st.from, n, locale, ...Object.values(off).map(Boolean)].join("|"); + const same = chart.dataset.drawn === drawn; + chart.dataset.drawn = drawn; + chart.redraw = () => renderSessChart(chart, st, used, ov, acts); // the metrics kept draw what is in now + + if (same && shape === "calendar") { + const lv = sessLevels(days.map(value)); + chart.querySelectorAll(".sess-cal > i").forEach((c, i) => { + c.className = "l" + lv(value(days[i])); + c.title = tip(days[i], sessDay(days[i].day)); + }); + chart.querySelector(".sess-cal-side").replaceWith(sessCalSide(days, value, show)); + chart.fitCal = () => sessCalFit(chart, days, value, tip); + return; + } + chart.fitCal = null; + if (shape === "calendar") { + chart.replaceChildren(); + chart.classList.add("cal"); + drawHead(); + const wrap = el("div", "sess-cal-wrap"); + wrap.append(sessCalendar(days, value, tip), sessCalSide(days, value, show)); + chart.append(wrap); + chart.querySelector(".sess-chart-head").append(sessLegend()); + chart.fitCal = () => sessCalFit(chart, days, value, tip); + chart.fitCal(); + sessCalWidth.observe(chart); + return; + } + + // bars: a day each, or a week + const step = shape === "week" ? 7 : 1; + const buckets = []; + for (let i = 0; i < n; i += step) { + const b = { day: days[i].day, input: 0, output: 0, cost: 0, unpriced: 0, sessions: 0, messages: 0, active: 0 }; + for (const x of days.slice(i, i + step)) for (const k of ["input", "output", "cost", "unpriced", "sessions", "messages", "active"]) b[k] += x[k]; + buckets.push(b); + } + const peak = Math.max(metric === "cost" ? 0.001 : 1, ...buckets.map(value)); + const fill = (bar, b) => { + const [top, low] = bar.children; + if (metric === "tokens") { + top.style.height = (100 * b.output / peak).toFixed(1) + "%"; + low.style.height = (100 * b.input / peak).toFixed(1) + "%"; + } else top.style.height = (100 * value(b) / peak).toFixed(1) + "%"; + const label = sessDay(b.day); + bar.title = tip(b, step === 7 ? t("week of {label}", { label }) : label); + }; + if (same) { + chart.querySelector(".sess-chart-head .peak").textContent = show(peak); + const bars = chart.querySelectorAll(".bars > .bar"); + buckets.forEach((b, i) => fill(bars[i], b)); + return; + } + chart.replaceChildren(); + chart.classList.remove("cal"); + drawHead().append(el("span", "peak", show(peak))); + const bars = el("div", "bars"); + const labels = el("div", "labels"); + const k = buckets.length; + const every = k <= 8 ? 1 : k <= 31 ? Math.ceil(k / 6) : Math.ceil(k / 5); + buckets.forEach((b, i) => { + const bar = el("div", "bar"); + if (metric === "tokens") bar.append(el("i", "out"), el("i", "in")); + else bar.append(el("i", "out")); + fill(bar, b); + bars.append(bar); + const label = sessDay(b.day); + const end = i === k - 1 && (k - 1) % every >= every / 2; + labels.append(el("span", "", i % every === 0 || end ? label : "")); + }); + chart.append(bars, labels); + fitChartLabels(); + + function drawHead() { + const head = el("div", "sess-chart-head"); + const seg = sessSegs(SESS_METRICS.map(([id, name]) => [id, name, off[id]]), metric, (id) => { + sessMetric = id; + try { localStorage.setItem("magpie.sessMetric", id); } catch {} + chart.redraw(); + }); + head.append(el("span", "label", t(shape === "week" ? "By week" : shape === "day" ? "By day" : "Activity")), seg, el("span", "grow")); + chart.append(head); + slide(seg, "sessMetric"); + return head; + } +} + +// a week's column in the calendar, cell and gap: as wide as weeks are counted +// by, and as wide as one may grow to take what is left over +const SESS_WEEK = 20, SESS_WEEK_MAX = 24; + +// sessCalFit lays the calendar across its card (John on Discord: 这个活跃度怎么 +// 没有铺满全部宽度呢?): a range of a few months took a few hundred pixels of a +// wide card and left the rest empty. The weeks before the range come in as +// empty cells, GitHub's way, up to a year in all, and the cells grow a little +// to take what is left; a narrow card gets none and its cells shrink. +// It fits on the next frame: a calendar put again changes the card's height, +// which this would be told of in the same call, a ResizeObserver loop. +const sessCalWidth = new ResizeObserver((es) => { + for (const { target: chart } of es) { + if (!chart.fitFrame) chart.fitFrame = requestAnimationFrame(() => { chart.fitFrame = 0; chart.fitCal?.(); }); + } +}); +function sessCalFit(chart, days, value, tip) { + const wrap = chart.querySelector(".sess-cal-wrap"), cal = wrap?.querySelector(".sess-cal"); + if (!cal || !wrap.clientWidth) return; + const ws = getComputedStyle(wrap), side = wrap.querySelector(".sess-cal-side"); + const wd = Math.max(0, ...[...cal.querySelectorAll(".wd")].map((l) => l.getBoundingClientRect().width)); + const room = wrap.clientWidth - wd - (ws.flexDirection === "row" ? side.getBoundingClientRect().width + (parseFloat(ws.columnGap) || 0) : 0); + const weeks = Math.ceil(((days[0].day.getDay() + 6) % 7 + days.length) / 7); + const pad = Math.max(0, Math.min(53, Math.floor(room / SESS_WEEK)) - weeks); + if (String(pad) !== cal.dataset.pad) cal.replaceWith(sessCalendar(days, value, tip, pad)); +} + +// sessCalendar is the range as weeks of days, Monday on top, each day as +// dark as it is busy among the others, after pad empty weeks before it +function sessCalendar(days, value, tip, pad = 0) { + const lv = sessLevels(days.map(value)); + const lead = (days[0].day.getDay() + 6) % 7 + 7 * pad; + const weeks = Math.ceil((lead + days.length) / 7); + const cal = el("div", "sess-cal"); + cal.dataset.pad = pad; + cal.style.gridTemplateColumns = `auto repeat(${weeks}, minmax(0, 1fr))`; + cal.style.maxWidth = `calc(2.6em + ${weeks * (pad ? SESS_WEEK_MAX : SESS_WEEK)}px)`; + const names = sessWeekdays(); + for (const i of [0, 2, 4]) { + const l = el("span", "wd", names[i]); + l.style.gridArea = `${i + 2} / 1`; + cal.append(l); + } + const loc = intlLang(); + let month = -1, labelAt = -9; + // the days before the range, from the Monday it is laid out from: their + // months named as the range's are, the days themselves left blank + const before = Array.from({ length: pad ? lead : 0 }, (_, i) => { + const d = new Date(days[0].day); + d.setDate(d.getDate() - lead + i); + return { day: d, before: true }; + }); + [...before, ...days].forEach((x, i) => { + const k = (pad ? 0 : lead) + i, w = Math.floor(k / 7), wd = k % 7; + if ((wd === 0 || i === 0) && x.day.getMonth() !== month) { + month = x.day.getMonth(); + // a month mostly gone when the weeks before begin is left unnamed, so + // as not to crowd out the next one's name + if (w - labelAt >= 3 && !(x.before && x.day.getDate() > 14)) { + const m = el("span", "mo", x.day.toLocaleDateString(loc, month === 0 && weeks > 20 ? { month: "short", year: "numeric" } : { month: "short" })); + m.style.gridArea = `1 / ${w + 2}`; + cal.append(m); + labelAt = w; + } + } + const c = x.before ? el("s") : el("i", "l" + lv(value(x))); + c.style.gridArea = `${wd + 2} / ${w + 2}`; + if (!x.before) c.title = tip(x, sessDay(x.day)); + cal.append(c); + }); + return cal; +} + +// beside the calendar: the days at work, the longest run of them, the busiest +function sessCalSide(days, value, show) { + const side = el("div", "sess-cal-side"); + const fact = (label, v, sub) => { + const f = el("div", "fact"); + f.append(el("b", "", v), el("span", "", label)); + if (sub) f.append(el("small", "", sub)); + side.append(f); + }; + const busy = (x) => x.input + x.output || x.active || x.sessions; + let run = 0, streak = 0, best = null; + for (const x of days) { + run = busy(x) ? run + 1 : 0; + streak = Math.max(streak, run); + if (value(x) > 0 && (!best || value(x) > value(best))) best = x; + } + fact(t("days at work"), `${days.filter(busy).length} / ${days.length}`); + fact(t("longest streak"), t(streak === 1 ? "{n} day" : "{n} days", { n: streak })); + if (best) fact(t("busiest day"), sessDay(best.day), show(value(best))); + return side; +} + +// renderSessHours lays the range's active time out by day of the week and +// hour of the day, in this computer's time zone +function renderSessHours(box, acts) { + box.replaceChildren(); + const head = sessCardHead("By hour"); + const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || ""; + head.append(el("span", "grow"), el("span", "tz", tz)); + box.append(head); + if (!acts) return box.append(el("div", "sess-none", t("Active time isn't kept by model."))); + const grid = Array.from({ length: 7 }, () => new Array(24).fill(0)); + let total = 0; + for (const a of acts) { + if (!a.hours) continue; + const wd = (sessDate(a.date).getDay() + 6) % 7; + a.hours.forEach((s, h) => { grid[wd][h] += s; total += s; }); + } + if (!total) return box.append(el("div", "sess-none", t("No active time in this range."))); + const lv = sessLevels(grid.flat()); + const names = sessWeekdays(); + const hh = (h) => String(h).padStart(2, "0") + ":00"; + const map = el("div", "sess-hours"); + let best = [0, 0]; + grid.forEach((row, wd) => { + map.append(el("span", "wd", names[wd])); + row.forEach((s, h) => { + const c = el("i", "l" + lv(s)); + c.title = `${names[wd]} ${hh(h)} · ` + (s ? fmtDur(s) : t("nothing")); + if (s > grid[best[0]][best[1]]) best = [wd, h]; + map.append(c); + }); + }); + map.append(el("span", "")); + for (let h = 0; h < 24; h++) map.append(el("span", "hr", h % 6 === 0 ? String(h) : "")); + box.append(map); + const foot = el("div", "sess-card-foot"); + foot.append(el("span", "", t("Busiest at {when}", { when: `${names[best[0]]} ${hh(best[1])}` })), el("span", "grow"), sessLegend()); + box.append(foot); +} + +// renderSessTop lists the sessions that spent the most in the range, under +// the filters; a click opens one to its details, read whole from its files +function renderSessTop() { + const box = $("#sessTop"); + const ov = sessOver || {}; + box.replaceChildren(); + box.classList.toggle("stale", sessOverAt !== sessOverQ()); + const head = sessCardHead("Top sessions"); + const seg = sessSegs(SESS_TOPS, sessTopBy, (id) => { + sessTopBy = id; + try { localStorage.setItem("magpie.sessTop", id); } catch {} + renderSessTop(); + }); + head.append(el("span", "grow"), seg); + box.append(head); + slide(seg, "sessTop"); + const list = ov.top?.[sessTopBy] || []; + const body = el("div", "sess-tops"); + if (!list.length) body.append(el("div", "sess-none", ov.top ? t("Nothing in this range.") : "…")); + const icons = new Map((sessions?.sessions || []).map((s) => [s.agent, s.icon])); + const names = sessStats?.agents || {}; + for (const s of list) { + const open = sessTopOpen === s.key; + const item = el("div", "sess-item" + (open ? " open" : "")); + const r = el("div", "row sess sess-top"); + r.append(icon(icons.get(s.agent) || "generic")); + const who = el("div", "who"); + who.append(el("div", "name", s.title || t("(no prompt)"))); + const sub = el("div", "sub", [s.cwd ? baseName(s.cwd) : "", names[s.agent] || s.agent, s.models?.[0], ago(s.last)].filter(Boolean).join(" · ")); + sub.title = s.cwd || ""; + who.append(sub); + r.append(who); + const fc = fmtCost({ cost: s.cost, unpriced: !s.priced }); + const v = sessTopBy === "cost" ? (fc ? "≈" + fc : "—") : sessTopBy === "active" ? fmtDur(s.active) : fmtN(s.input + s.output); + r.append(el("div", "v", v)); + r.onclick = () => { + if (window.getSelection()?.toString()) return; + sessTopOpen = open ? "" : s.key; + const had = sessFull.get(s.key); + if (!open && (!had || had.error)) { + sessFull.set(s.key, "…"); + api("sessions/one?key=" + encodeURIComponent(s.key)).then((full) => sessFull.set(s.key, full), (e) => sessFull.set(s.key, { error: e.message })) + .then(() => { if (sessTopOpen === s.key && view === "usage" && usageTab === "sessions") renderSessTop(); }); + } + renderSessTop(); + }; + item.append(r); + if (open) { + const full = sessFull.get(s.key); + item.append(!full || full === "…" ? el("div", "sess-detail sess-wait", t("Reading the session…")) : full.error ? el("div", "sess-detail sess-wait", full.error) : sessionDetail(full)); + } + body.append(item); + } + box.append(body); +} + +// the ways a session's shape is told, and the one shown +const SESS_SHAPES = [["messages", "Messages"], ["minutes", "Length"], ["autonomy", "Tool calls"]]; +let sessShapeBy = "messages"; +try { const v = localStorage.getItem("magpie.sessShape"); if (SESS_SHAPES.some(([id]) => id === v)) sessShapeBy = v; } catch {} + +// renderSessShape counts the range's sessions by how long they ran: by +// messages, by minutes at work, or by tool calls a prompt +function renderSessShape() { + const box = $("#sessShape"); + const ov = sessOver || {}; + box.replaceChildren(); + box.classList.toggle("stale", sessOverAt !== sessOverQ()); + const sh = ov.shape?.[sessShapeBy]; + const head = sessCardHead("Session shape"); + const seg = sessSegs(SESS_SHAPES, sessShapeBy, (id) => { + sessShapeBy = id; + try { localStorage.setItem("magpie.sessShape", id); } catch {} + renderSessShape(); + }); + head.append(seg, el("span", "grow"), el("span", "tz", sh ? t(sh.total === 1 ? "{n} session" : "{n} sessions", { n: fmtN(sh.total) }) : "")); + box.append(head); + slide(seg, "sessShape"); + if (!sh?.total) return box.append(el("div", "sess-none", ov.shape ? t("Nothing in this range.") : "…")); + const label = (i) => { + const lo = sh.edges[i], hi = sh.edges[i + 1]; + if (sessShapeBy === "autonomy" && lo === 0) return "<1"; + const r = hi == null ? lo + "+" : hi - 1 === lo ? String(lo) : `${lo}–${hi - 1}`; + return sessShapeBy === "minutes" ? t("{r}m", { r }) : r; + }; + const what = { messages: "{r} messages", minutes: "{r} minutes at work", autonomy: "{r} tool calls a prompt" }[sessShapeBy]; + const peak = Math.max(1, ...sh.counts); + const bars = el("div", "sess-shape"); + sh.counts.forEach((c, i) => { + const col = el("div", "col"); + const pct = Math.round(100 * c / sh.total); + col.title = t(what, { r: label(i) }) + " · " + t(c === 1 ? "{n} session" : "{n} sessions", { n: fmtN(c) }) + ` (${pct}%)`; + // a bar as tall as its share of the busiest bin, on a baseline; an + // empty bin a stub, so no grey column reads as a bar of its own + const plot = el("div", "plot"); + const fill = el("i", c ? "" : "none"); + fill.style.height = c ? `max(4px, calc((100% - 20px) * ${(c / peak).toFixed(3)}))` : ""; + plot.append(el("b", c ? "" : "zero", fmtN(c)), fill); + // the busiest bin in full, when one is busiest + col.classList.toggle("peak", c === peak && c > 0 && sh.counts.filter((n) => n === peak).length === 1); + col.append(plot, el("span", "", label(i))); + bars.append(col); + }); + box.append(bars); + // what the two axes are, said plainly + const axis = { messages: "messages in a session, prompts and replies", minutes: "minutes a session was at work", autonomy: "tool calls the agent made on its own for each prompt" }[sessShapeBy]; + const foot = el("div", "sess-card-foot"); + foot.append(el("span", "", t("Across: {axis} · Height: sessions", { axis: t(axis) }))); + box.append(foot); +} + +// the colours of the kinds of tool, as the calls are told apart +const TOOL_CATS = { Bash: "#e0823d", Edit: "#4f8cf0", Read: "#2fb087", Write: "#9b6cf0", Grep: "#e0608f", Glob: "#d4a72c", Task: "#35a9c7", Tool: "#7c83f2", Other: "#9aa0a8" }; +const toolColor = (c) => TOOL_CATS[c] || TOOL_CATS.Other; +// a kind's name, as its tools are named, "Other" aside +const toolKind = (c) => c === "Other" ? t("Other") : c; +function toolDot(c) { + const d = el("i", "dot"); + d.style.background = toolColor(c); + return d; +} + +// renderSessTools is what the sessions called their tools for: the most +// called, by kind, and week by week +function renderSessTools() { + const box = $("#sessTools"); + const tu = sessOver?.tools; + box.replaceChildren(); + box.classList.toggle("stale", sessOverAt !== sessOverQ()); + const head = sessCardHead("Tool use"); + head.append(el("span", "grow")); + if (tu?.calls) head.append(el("span", "tz", t("{n} calls", { n: fmtN(tu.calls) }) + " · " + t(tu.sessions === 1 ? "{n} session" : "{n} sessions", { n: fmtN(tu.sessions) }))); + box.append(head); + if (!tu?.calls) return box.append(el("div", "sess-none", tu ? t("No tool calls in this range.") : "…")); + const cols = el("div", "sess-tools-cols"); + + // the most called, each with its kind's dot, calls, sessions and share + const top = el("div", "sess-bars tools"); + const peak = Math.max(1, ...tu.top.map((x) => x.calls)); + for (const x of tu.top) { + const r = el("div", "sess-bar tool"); + r.title = `${x.name} · ${toolKind(x.category)}`; + const n = el("span", "n"); + n.append(toolDot(x.category), el("span", "", x.name)); + const track = el("span", "track"); + const fill = el("i"); + fill.style.width = Math.max(1.5, 100 * x.calls / peak).toFixed(1) + "%"; + fill.style.background = toolColor(x.category); + track.append(fill); + r.append(n, track, el("span", "v", fmtN(x.calls)), el("span", "s", t(x.sessions === 1 ? "{n} session" : "{n} sessions", { n: fmtN(x.sessions) })), + el("span", "p", Math.round(100 * x.calls / tu.calls) + "%")); + top.append(r); + } + cols.append(top); + + const side = el("div", "sess-tools-side"); + // by kind: one bar of every call, and each kind's count + const mix = el("div", "sess-mix"); + const kinds = el("div", "sess-kinds"); + for (const c of tu.categories) { + const seg = el("i"); + seg.style.flexGrow = c.calls; + seg.style.background = toolColor(c.name); + seg.title = `${toolKind(c.name)} · ${t("{n} calls", { n: fmtN(c.calls) })} (${Math.round(100 * c.calls / tu.calls)}%)`; + mix.append(seg); + const k = el("span", "kind"); + k.title = seg.title; + k.append(toolDot(c.name), el("span", "", toolKind(c.name)), el("b", "", fmtN(c.calls))); + kinds.append(k); + } + side.append(mix, kinds); + + // week by week, the last sixteen, each kind stacked + const weeks = tu.weeks.slice(-16); + if (weeks.length > 1) { + side.append(el("div", "sess-sub", t("By week"))); + const order = tu.categories.map((c) => c.name); + const total = (w) => Object.values(w.calls).reduce((a, b) => a + b, 0); + const wpeak = Math.max(1, ...weeks.map(total)); + const bars = el("div", "sess-weeks"); + for (const w of weeks) { + const bar = el("div", "bar"); + const n = total(w); + bar.title = t("week of {label}", { label: sessDay(sessDate(w.start)) }) + " · " + t("{n} calls", { n: fmtN(n) }); + const stack = el("div", "stack"); + stack.style.height = (n ? Math.max(2, 100 * n / wpeak) : 0).toFixed(1) + "%"; + for (const c of order) { + if (!w.calls[c]) continue; + const part = el("i"); + part.style.flexGrow = w.calls[c]; + part.style.background = toolColor(c); + stack.append(part); + } + bar.append(stack); + bars.append(bar); + } + const labels = el("div", "sess-weeks-labels"); + labels.append(el("span", "", sessDay(sessDate(weeks[0].start))), el("span", "", sessDay(sessDate(weeks[weeks.length - 1].start)))); + side.append(bars, labels); + } + cols.append(side); + box.append(cols); +} + +// renderSessSkills lists the skills the sessions called up, the most first +function renderSessSkills() { + const box = $("#sessSkills"); + const su = sessOver?.skills; + box.replaceChildren(); + box.classList.toggle("stale", sessOverAt !== sessOverQ()); + const head = sessCardHead("Top skills"); + head.append(el("span", "grow")); + if (su?.calls) head.append(el("span", "tz", t("{n} calls", { n: fmtN(su.calls) }) + " · " + t(su.count === 1 ? "{n} skill" : "{n} skills", { n: fmtN(su.count) }))); + box.append(head); + if (!su?.calls) return box.append(el("div", "sess-none", su ? t("No skill was called up in this range.") : "…")); + const names = sessStats?.agents || {}; + const peak = Math.max(1, ...su.top.map((x) => x.calls)); + const body = el("div", "sess-skills"); + for (const x of su.top) { + const r = el("div", "sess-skill"); + const line = el("div", "line"); + const track = el("span", "track"); + const fill = el("i"); + fill.style.width = Math.max(1.5, 100 * x.calls / peak).toFixed(1) + "%"; + track.append(fill); + line.append(el("span", "n", x.name), track, el("span", "v", fmtN(x.calls))); + const agents = Object.entries(x.agents || {}).sort((a, b) => b[1] - a[1]); + const share = agents.map(([a, c]) => `${names[a] || a} ${Math.round(100 * c / x.calls)}%`).join(" · "); + const where = (x.projects || []).map((p) => baseName(p.name)).join(", "); + const sub = el("div", "sub", [t(x.sessions === 1 ? "{n} session" : "{n} sessions", { n: fmtN(x.sessions) }), + x.last ? t("last {when}", { when: sessDay(sessDate(x.last)) }) : "", share, where].filter(Boolean).join(" · ")); + sub.title = (x.projects || []).map((p) => `${p.name} · ${t("{n} calls", { n: fmtN(p.calls) })}`).join("\n"); + r.append(line, sub); + body.append(r); + } + if (su.count > su.top.length) body.append(el("div", "sess-more", t("+{n} more", { n: su.count - su.top.length }))); + box.append(body); +} + +// sessBars is a card of folders or models as bars of the tokens each took; +// a click shows that one alone, and a click on it again every one +const SESS_BARS = 6; +function sessBars(box, title, items, cur, choose, name) { + box.replaceChildren(); + box.append(sessCardHead(title)); + const body = el("div", "sess-bars"); + let shown = items.slice(0, SESS_BARS); + const picked = cur && items.find((x) => x.v === cur); + if (picked && !shown.includes(picked)) shown = [...shown.slice(0, SESS_BARS - 1), picked]; + const peak = Math.max(1, ...items.map((x) => x.n)); + for (const x of shown) { + const r = el("button", "sess-bar" + (x.v === cur ? " on" : "")); + r.type = "button"; + r.title = [name(x.v) !== x.v ? x.v : "", x.v === cur ? t("Click again to show every one") : t("Click to show only this")].filter(Boolean).join("\n"); + const track = el("span", "track"); + const fill = el("i"); + fill.style.width = Math.max(1.5, 100 * x.n / peak).toFixed(1) + "%"; + track.append(fill); + const fc = x.cost ? fmtCost(x) : ""; + r.append(el("span", "n", name(x.v)), track, el("span", "v", fmtN(x.n)), el("span", "c", fc ? "≈" + fc : "")); + r.onclick = () => choose(x.v === cur ? "" : x.v); + body.append(r); + } + if (!items.length) body.append(el("div", "sess-none", t("Nothing in this range."))); + if (items.length > shown.length) body.append(el("div", "sess-more", t("+{n} more", { n: items.length - shown.length }))); + box.append(body); +} + +// sessSpent is a session's tokens and cost, as the two right-hand columns +// of its row: the Usage page's list and the Sessions page's (#752) +function sessSpent(s) { + const tokens = sessTokens(s); + const num = el("div", "num" + (tokens ? "" : " none")); + num.append(el("b", "", tokens ? fmtN(tokens) : "—")); + if (tokens) num.append(el("small", "", t("{a} in · {b} out", { a: fmtN(s.input), b: fmtN(s.output) }) + (s.cache_read ? " · " + t("{n} cached", { n: fmtN(s.cache_read) }) : ""))); + const sc = sessCost(s); + const cost = el("div", "cost" + (sc === "—" ? " none" : ""), sc); + if (sc === "—") cost.title = t("No known price for {models}", { models: sessModelNames(s.models.map((m) => m.model)) || "—" }); + else if (s.unpriced) cost.title = t("Not counted: {models}, with no known price", { models: sessModelNames(s.models.filter((m) => !m.priced).map((m) => m.model)) }); + return [num, cost]; +} + +// A row of the Usage page's list: what the session spent. It opens on the +// Sessions page, where it is resumed, read in full and deleted (#752: the +// two lists were one done twice, each lacking half). +function sessionItem(s) { + const item = el("div", "sess-item"); + const r = el("div", "row sess sess-link"); + r.tabIndex = 0; + r.setAttribute("role", "link"); + r.title = t("Open in Sessions"); + r.append(icon(s.icon || "generic")); + const who = el("div", "who"); + who.append(el("div", "name", s.title || t("(no prompt)"))); + const sub = el("div", "sub", [s.cwd ? baseName(s.cwd) : "", sessModelsText(s), ago(s.last)].filter(Boolean).join(" · ")); + sub.title = [s.cwd, ...(s.via || []).map(viaText)].filter(Boolean).join("\n"); + if (s.wsl) sub.prepend(wslBadge(s), " "); + who.append(sub); + r.append(who, ...sessSpent(s)); + const go = el("span", "sess-go"); + go.append(svg(CHEV_R, 12, 1.6)); + r.append(go); + const open = (e) => { + if (window.getSelection()?.toString()) return; + if (featuresOff.has("sessions")) return; // Sessions is switched off: there is no page to open it on + magpie.call("sessions", "reveal", s, e); + }; + r.onclick = open; + r.onkeydown = (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); open(e); } }; + item.append(r); + return item; +} + +function sessionDetail(s) { + const d = el("div", "sess-detail"); + const line = (label, value, extra) => { + const l = el("div", "sess-line"); + l.append(el("span", "k", label)); + const v = el("span", "v", value); + l.append(v); + if (extra) l.append(extra); + d.append(l); + }; + line(t("Time"), stamp(s.start) + " – " + stamp(s.last)); + if (s.wsl) line("WSL", s.wsl); + if (s.cwd) line(t("Folder"), s.cwd); + line(t("Session ID"), s.id, copyBtn(s.id, t("Session id"))); + if (s.resume) { + const code = el("code", "", s.resume); + const l = el("div", "sess-line"); + l.append(el("span", "k", t("Resume")), code, copyBtn(s.resume, t("Resume command"))); + d.append(l); + } + sessUsageDetail(d, s, line); + if (s.path) line(t("File"), s.path); + return d; +} + +// All sessions: the Sessions page, on the agent picked here if one is +$("#sessAll").onclick = (e) => magpie.call("sessions", "reveal", sessAgent === "all" ? {} : { agent: sessAgent }, e); +$("#sessQ").oninput = (e) => { sessQuery = e.target.value; if (sessions) renderSessions(); }; +$("#sessQ").onkeydown = (e) => { if (e.key === "Escape" && e.target.value) { e.stopPropagation(); e.target.value = ""; sessQuery = ""; if (sessions) renderSessions(); } }; + +// ---------- settings ---------- +// +// Three choices (palette, language, what the tray icon opens) and the facts +// people come looking for: +// the version, where magpie keeps its files, the gateway's address. + +// The Usage page reads its numbers again while it is looked at, as often as +// the reader says — off, or every 5 s to a minute (a request through the gateway +// shows within that; the subscriptions' windows each minute at most, the vendors' +// answers being cached behind them, and the sessions each 15 s) — redrawn only +// on a change. The button beside it reads them now. +const USAGE_EVERY = [[0, "Off"], [5, "5 s"], [10, "10 s"], [30, "30 s"], [60, "1 min"]]; +let usageEvery = 5; // seconds; 0 is off +try { + const v = localStorage.getItem("magpie.usageEvery"); + if (USAGE_EVERY.some(([n]) => String(n) === v)) usageEvery = Number(v); +} catch {} +let usageLast = 0, usageReadAt = 0, sessionsAt = 0, quotasAsked = 0; + +function renderUsageEvery() { + const cur = USAGE_EVERY.find(([n]) => n === usageEvery); + const b = $("#usageEvery"); + b.replaceChildren(el("span", "", t(cur[1])), svg(CHEV, 11, 1.6)); + b.title = t("Refresh every"); + b.onclick = (e) => { + e.stopPropagation(); + if (b.classList.contains("open")) return closeProtoMenu(); + openProtoMenu(b, USAGE_EVERY.map(([n, name]) => ({ v: String(n), name: t(name), note: "" })), String(usageEvery), (v) => { + usageEvery = Number(v); + try { localStorage.setItem("magpie.usageEvery", v); } catch {} + usageLast = performance.now(); + renderUsageEvery(); + }, "Refresh every", "sess-menu"); + }; + const r = $("#usageReload"); + // on the Overview it reads the allowances again too (#486: they had a + // Refresh of their own beside it) + const what = usageTab === "usage" ? t("Refresh now, the allowances too; a Claude account's is read by running Claude Code's own /usage") : t("Refresh now"); + r.title = usageReadAt ? what + " · " + t("Updated {time}", { time: new Date(usageReadAt).toLocaleTimeString(intlLang(), { hour12: false }) }) : what; + r.setAttribute("aria-label", t("Refresh now")); + r.onclick = async () => { + r.classList.add("busy"); + try { await refreshUsage(true); } finally { r.classList.remove("busy"); r.blur(); } + }; +} + +// refreshUsage reads what the tab shown draws; now is the reader asking, which +// reads the page it is on too, and the sessions and the allowances. +// A read that outlives its interval must not have another started behind it: +// one is in flight at a time, and a read asked for while one is (the timer, or +// the reader's button, which may not be swallowed) is served when it is done, +// the reader's own if either asked for it. The promise covers that second read +// too, so the button turns while the reader's own is still to come. +let usageFlight = null, usageQueued = false, usageQueuedNow = false; +// usageDrawn: the tab shown has its figures on the page already, which a +// quiet read (refreshUsage) only replaces when they changed +function usageDrawn() { + if (usageTab === "sessions") return !!(sessions && sessStats); + if (usageTab === "requests") return !!ledger; + if (usageTab === "context") return true; // loadContext keeps what it drew when nothing changed + return !!usage && !$("#view-usage").classList.contains("loading"); +} +function refreshUsage(now = false) { + usageLast = performance.now(); + if (usageFlight) { + usageQueued = true; + usageQueuedNow = usageQueuedNow || now; + return usageFlight; // this promise includes the queued read + } + const run = async (want) => { + try { + if (usageTab === "sessions") { + if (sessions && (want || performance.now() - sessionsAt > 15e3)) { sessionsAt = performance.now(); await loadSessions(); } + } else if (usageTab === "requests") { + // the newest page takes the requests as they come; an older one stays put + if (ledger && (want || !ledOffset)) await loadLedger(true); + } else if (usageTab === "context") { + await window.loadContext?.(); + } else { + // the reader asking reads the allowances afresh, a Claude account's by + // running Claude Code's own /usage (the backend runs it at most once in 30s) + let q = null; + if (want) { quotasAsked = performance.now(); q = loadQuotas(true); } + else if (usage && performance.now() - quotasAsked > 60e3) { quotasAsked = performance.now(); loadQuotas(); } + if (usage) { + const p = period, read = ++usageRead; + const u = await api("usage?period=" + encodeURIComponent(p)); + if (read === usageRead && view === "usage" && usageTab === "usage" && p === period) { + if (JSON.stringify(u) !== JSON.stringify(usage)) { usage = u; renderUsage(); } + // this read claimed the newest one: a pick it superseded had put the + // skeleton up, and the figures on hand are what ends it + else if ($("#view-usage").classList.contains("loading")) renderUsage(); + } + } + await q; + } + usageReadAt = Date.now(); + renderUsageEvery(); + } catch {} + }; + const flight = Promise.resolve().then(() => run(now)).then(() => { + if (usageFlight !== flight) return; + usageFlight = null; + if (!usageQueued) return; + const want = usageQueuedNow; + usageQueued = usageQueuedNow = false; + // one more read, the reader's own if either asked for it + return refreshUsage(want); + }); + usageFlight = flight; + return flight; +} +renderUsageEvery(); +setInterval(() => { + if (!usageEvery || view !== "usage" || document.hidden || document.querySelector(".pop:not([hidden])")) return; + if (performance.now() - usageLast >= usageEvery * 1000) refreshUsage(); +}, 1000); +// opened from the tray panel's Usage tab: on the Requests of one provider or agent +if (mode === "window" && params.get("view") === "usage") { + // An explicit destination takes precedence over the remembered tab. + const tab = params.get("tab"); + if (tab === "requests" || tab === "usage") usageTab = tab; + // a total in the menu bar opens the Overview at its period + const per = params.get("period"); + if (PERIODS.some(([id]) => id === per)) period = per; + quotaFocus = usageTab === "usage" ? (params.get("card") || params.get("provider") || "") : ""; + quotaFocusUntil = performance.now() + 5000; + ledProvider = params.get("provider") || ""; + ledAgent = params.get("agent") || ""; + ledPurpose = params.get("purpose") || ""; + ledComputer = params.get("computer") || ""; + const v = params.get("via") || ""; + ledVia = v === "through" || v === "direct" || v === "reported" ? v : ""; + const u = new URL(location.href); + for (const k of ["tab", "provider", "agent", "computer", "card", "purpose", "via", "period"]) u.searchParams.delete(k); + history.replaceState(null, "", u); +} diff --git a/internal/gui/assets/start.js b/internal/gui/assets/start.js new file mode 100644 index 000000000..fda53be2c --- /dev/null +++ b/internal/gui/assets/start.js @@ -0,0 +1,25 @@ +// The window's start, loaded last: app.js, the plugins' pages and the +// scripts after app.js are all there, so the first page shown has its +// code (the Usage page's is a plugin's, run after app.js). +// the plugins' pages wired up (kernel.js), before the first is shown +magpie.start(); +navHides(); // the pages built-in plugins switched off have, from boot.js +// The window opens on the page the reader last left, as a Mac app comes back +// as it was (molvqingtai, lc on Discord): a page asked for (?view=, a link +// from the tray or a reload) first, then the one kept; a page gateway mode +// leaves out, or one there is no longer, gives way to the first page. +// the pages the window can open on besides the first (Agents) +const OPEN_VIEWS = ["providers", "plugins", "settings", ...magpie.pages()]; +function keptView() { + const asked = params.get("view"); + if (asked === "agents" || OPEN_VIEWS.includes(asked)) return asked; + let v = ""; + try { v = localStorage.getItem("magpie.lastView") || ""; } catch { /* none kept */ } + return OPEN_VIEWS.includes(v) ? v : ""; // one gateway mode leaves out, show() makes Providers +} +const firstView = mode === "window" ? keptView() : ""; +if (OPEN_VIEWS.includes(firstView)) show(firstView); +else if (mode === "window" && !gatewayMode && !sideNav()) slide($("#nav"), "nav"); +// in gateway mode the first page is Providers, Agents' tab gone +if (gatewayMode) setGatewayMode(true); +load(); diff --git a/internal/gui/builtins_test.go b/internal/gui/builtins_test.go index 9cba4a6bc..776c6f7fb 100644 --- a/internal/gui/builtins_test.go +++ b/internal/gui/builtins_test.go @@ -44,12 +44,12 @@ func TestBuiltinSwitch(t *testing.T) { if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { t.Fatal(err) } - if len(out) != 7 { + if len(out) != 8 { t.Fatalf("the built-ins: %+v", out) } for _, b := range out { - // the Gateway and Routing pages are essential: on in every preset - if b.On != (b.ID == "library" || b.ID == "gateway" || b.ID == "routing") || b.On != (b.State == pluginrt.Active) { + // the Gateway, Routing and Usage pages are essential: on in every preset + if b.On != (b.ID == "library" || b.ID == "gateway" || b.ID == "routing" || b.ID == "usage") || b.On != (b.State == pluginrt.Active) { t.Fatalf("after library on: %+v", out) } } @@ -194,9 +194,9 @@ func TestBuiltinClientsLoaded(t *testing.T) { } return i } - kernel, app := at("kernel.js"), at("app.js") - if kernel > app { - t.Fatal("kernel.js after app.js") + kernel, app, start := at("kernel.js"), at("app.js"), at("start.js") + if kernel > app || app > start { + t.Fatal("kernel.js, app.js and start.js out of order") } n := 0 for _, m := range pluginrt.Registered() { @@ -211,6 +211,12 @@ func TestBuiltinClientsLoaded(t *testing.T) { if i := at(name); i > strings.Index(src, "") { t.Errorf("%s isn't in the head", name) } + } else if c == "page.js" { + // a page's code that runs on app.js's helpers: after app.js, + // before start.js shows the first page + if i := at(name); i < app || i > start { + t.Errorf("%s isn't between app.js and start.js", name) + } } else if i := at(name); i < kernel || i > app { t.Errorf("%s isn't between kernel.js and app.js", name) } diff --git a/internal/gui/tests/builtins.test.cjs b/internal/gui/tests/builtins.test.cjs index 7b2056e40..82f21f641 100644 --- a/internal/gui/tests/builtins.test.cjs +++ b/internal/gui/tests/builtins.test.cjs @@ -25,11 +25,12 @@ const PLUGINS = [ { id: "otel", name: "Observability", sub: "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse", one: "Sending to a collector", many: "Sending to a collector" }, { id: "routing", name: "Routing", sub: "Each request as the gateway routes it, the accounts it weighed and what each answered, and your routing groups", one: "1 group in use", many: "{n} groups in use" }, { id: "sessions", name: "Sessions", sub: "Your agents' past conversations: read, search, resume and export them", one: "Recording gateway conversations", many: "Recording gateway conversations" }, + { id: "usage", name: "Usage", sub: "Your allowances, what was spent and on what, each request, and what filled the context window" }, { id: "warmups", name: "Warm-up and check-in", sub: "Start a subscription's usage window at a time you pick, and claim vendors' daily check-in credits", one: "1 warm-up or check-in on", many: "{n} warm-ups and check-ins on" }, ]; -// a new install's (the Essentials preset): all off but the Gateway page, -// which is essential, and two routing groups the user made -const START = { gateway: [true, 0], groups: [false, 2], library: [false, 0], otel: [false, 0], routing: [true, 0], sessions: [false, 0], warmups: [false, 0] }; +// a new install's (the Essentials preset): all off but the Gateway, Routing +// and Usage pages, which are essential, and two routing groups the user made +const START = { gateway: [true, 0], groups: [false, 2], library: [false, 0], otel: [false, 0], routing: [true, 0], sessions: [false, 0], usage: [true, 0], warmups: [false, 0] }; // the Gateway page's settings, as pluginrt.SchemaOf makes them const GATEWAY_SCHEMA = { @@ -161,7 +162,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual([gw.on, gw.disabled], ["true", false], `${where}: the Gateway page, on`); const rt = rows.find((r) => r.id === "routing"); assert.deepEqual([rt.on, rt.disabled], ["true", false], `${where}: the Routing page, on`); - for (const r of rows.filter((r) => !["groups", "gateway", "routing"].includes(r.id))) assert.deepEqual([r.on, r.disabled, r.why], ["false", false, ""], `${where}: ${r.id}`); + const us = rows.find((r) => r.id === "usage"); + assert.deepEqual([us.on, us.disabled], ["true", false], `${where}: the Usage page, on`); + for (const r of rows.filter((r) => !["groups", "gateway", "routing", "usage"].includes(r.id))) assert.deepEqual([r.on, r.disabled, r.why], ["false", false, ""], `${where}: ${r.id}`); await page.locator('#builtinList [data-id="groups"] [role="switch"]').click({ force: true }); await page.waitForTimeout(100); assert.deepEqual(posts, [], `${where}: a locked switch posts nothing`); @@ -199,9 +202,18 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(posts.at(-1), ["routing", false], where); if (width >= 800) assert.deepEqual(await tabs(page), ["agents", "library", ...KEPT.slice(1).filter((k) => k !== "routing")], `${where}: Routing gone`); assert.deepEqual(await viewShown(page), ["view-plugins"], `${where}: Plugins stays`); + // and Usage: its tab goes + await page.locator('#builtinList [data-id="usage"] [role="switch"]').click(); + await page.waitForSelector('#builtinList [data-id="usage"] [aria-checked="false"]'); + assert.deepEqual(posts.at(-1), ["usage", false], where); + if (width >= 800) assert.deepEqual(await tabs(page), ["agents", "library", ...KEPT.slice(1).filter((k) => k !== "routing" && k !== "usage")], `${where}: Usage gone`); + assert.deepEqual(await viewShown(page), ["view-plugins"], `${where}: Plugins stays`); // Discover brings the search back await pluginTabs(page, side).nth(1).click(); assert.ok(await page.locator("#view-plugins .pm-find").isVisible(), `${where}: search on Discover`); + // a way to Usage left somewhere (the tray's Open Usage) gives way to Agents + await page.evaluate(() => show("usage")); + assert.deepEqual(await viewShown(page), ["view-agents"], `${where}: no Usage page with it off`); assert.deepEqual(errors, [], where); await context.close(); } diff --git a/internal/gui/tests/context-window.test.cjs b/internal/gui/tests/context-window.test.cjs index 68622464b..a9885bbc0 100644 --- a/internal/gui/tests/context-window.test.cjs +++ b/internal/gui/tests/context-window.test.cjs @@ -183,29 +183,29 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", } } -// context.js comes after app.js, which shows the page and reads the state -// before it is there: the state answered first, the tab still loads at once -// rather than at the refresh's first tick, five seconds on +// context.js once came after the script that shows the page and reads the +// state, so a state answered first left the tab empty until the refresh's +// first tick. start.js, which does both, now comes after it: a slow context.js +// holds the first read back, and the tab loads as soon as it is in for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { - test(`${engine}: the Context tab loads when context.js arrives after the state`, async (t) => { + test(`${engine}: the Context tab loads at once though context.js is slow`, async (t) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); const page = await (await browser.newContext({ viewport: { width: 1100, height: 900 } })).newPage(); - const errors = [], asked = []; + const errors = [], asked = [], order = []; page.on("pageerror", (e) => errors.push(e.message)); const base = serve("en", asked); - let answered; - const stateDone = new Promise((res) => { answered = res; }); await page.route("**/*", async (r) => { const p = new URL(r.request().url()).pathname; - if (p === "/context.js") await stateDone.then(() => new Promise((res) => setTimeout(res, 150))); + if (p === "/context.js") await new Promise((res) => setTimeout(res, 1000)); + if (p === "/context.js" || p === "/api/state") order.push(p); await base(r); - if (p === "/api/state") answered(); }); await page.addInitScript(() => { try { localStorage.clear(); localStorage.setItem("magpie.usageTab", "context"); } catch {} }); await page.goto("http://magpie.test/?view=usage"); await page.locator(".ctx-agent", { hasText: "Codex" }).waitFor({ timeout: 2500 }); assert.equal(asked[0], "7"); + assert.deepEqual(order.slice(0, 2), ["/context.js", "/api/state"], "the state is read once context.js is in"); assert.doesNotMatch(await page.locator("#status").innerText(), /loadContext|not a function/); assert.deepEqual(errors, []); }); diff --git a/internal/gui/tests/quota-refresh-order.test.cjs b/internal/gui/tests/quota-refresh-order.test.cjs index b5e6ec7ed..7d7f5c041 100644 --- a/internal/gui/tests/quota-refresh-order.test.cjs +++ b/internal/gui/tests/quota-refresh-order.test.cjs @@ -30,7 +30,7 @@ function page() { if (path.includes("history")) return Promise.resolve([]); return new Promise((resolve, reject) => requests.push({ path, resolve, reject })); } - ${section("let quotasLoading =", "// the period picker, in the page's head")} + ${section("let quotasLoading =", "// A period of picked days is")} ${section("const quotaRefreshing =", "// familyQuota:")} globalThis.p = { requests, errors, diff --git a/internal/gui/tests/usage-stale-answer.test.cjs b/internal/gui/tests/usage-stale-answer.test.cjs index 6ba016e0d..ea17548d5 100644 --- a/internal/gui/tests/usage-stale-answer.test.cjs +++ b/internal/gui/tests/usage-stale-answer.test.cjs @@ -17,9 +17,12 @@ const vm = require("node:vm"); const { test } = require("node:test"); // Another revision of app.js can be selected with MAGPIE_APP_JS to check -// the same behavior cases against the implementation before the fix. +// the same behavior cases against the implementation before the fix. The +// Usage page's code is the Usage plugin's page.js, beside app.js's +// allowances (quotasOpened). const APP = process.env.MAGPIE_APP_JS || path.resolve(__dirname, "../assets/app.js"); -const source = fs.readFileSync(APP, "utf8").replace(/\r\n/g, "\n"); +const PAGE = path.resolve(__dirname, "../assets/plugins/usage/page.js"); +const source = [APP, PAGE].filter((f) => fs.existsSync(f)).map((f) => fs.readFileSync(f, "utf8")).join("\n").replace(/\r\n/g, "\n"); // lift a top-level function out of app.js whole: from its `function` line to // the `}` at the left margin that closes it diff --git a/plugins/all/all.go b/plugins/all/all.go index c04dcc699..b2801a8b1 100644 --- a/plugins/all/all.go +++ b/plugins/all/all.go @@ -9,5 +9,6 @@ import ( _ "github.com/yetone/magpie/plugins/otel" _ "github.com/yetone/magpie/plugins/routing" _ "github.com/yetone/magpie/plugins/sessions" + _ "github.com/yetone/magpie/plugins/usage" _ "github.com/yetone/magpie/plugins/warmups" ) diff --git a/plugins/usage/usage.go b/plugins/usage/usage.go new file mode 100644 index 000000000..9b20338eb --- /dev/null +++ b/plugins/usage/usage.go @@ -0,0 +1,16 @@ +// Package usage is the Usage page: the allowances, what was spent and on +// what, the sessions, each request, and what filled the context window. +// Off, the page leaves the window; the gateway still counts what it +// passes on, and the tray panel's Usage tab still shows the allowances. +package usage + +import "github.com/yetone/magpie/internal/pluginrt" + +func init() { + pluginrt.Register(pluginrt.Manifest{ + ID: "usage", API: "^1", Requires: []string{"window"}, Essential: true, + Name: "Usage", Sub: "Your allowances, what was spent and on what, each request, and what filled the context window", + Parts: []pluginrt.Part{{Slot: "nav.page", Key: "usage"}}, + Client: []string{"i18n.js", "client.js", "page.js"}, + }) +}