diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 0123ccfd0..b1cce795f 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -392,8 +392,16 @@ at the value its row shows) and a row per agent. `magpie sessions read [on|off all|…]` shows and changes the same choice from the CLI (`sessionReadsTo`); while it is not asked, `magpie sessions` says so on stderr and the TUI's empty Sessions page -says how (`sessNothing`). Tests: `TestSessionsRead`, -`TestSessionsNotAskedSaysHow`. +says how (`sessNothing`). With no provider set up, Claude Code's and Codex's sessions, and each +call's tokens and duration, need only this consent: the session files are +the source (`/api/usage/requests` rows with `source: "log"`, the speed a +call's tokens over its time gives, shown as a floor). An empty Usage +Overview or Requests page says so while `asked` is false and offers the +agents found with one button (`readsNote` in the usage plugin's +`page.js`; simonzyzy on X), and the Sessions page says the live output +speed curve is measured only on requests through the gateway +(`sm-speed-note`). Tests: `TestSessionsRead`, +`TestSessionsNotAskedSaysHow`, `usage-reads-note.test.cjs`. In gateway mode (`magpie web`'s page, [`gatewaymode.go`](../../internal/gui/gatewaymode.go)) no agent's own session files are read, whatever `SessionReads` says diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 6b02343bc..368d1848d 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1631,6 +1631,8 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske .led-hscroll::-webkit-scrollbar-thumb { background: var(--faint); border: 2px solid transparent; border-radius: 10px; background-clip: padding-box; } .led-hscroll::-webkit-scrollbar-thumb:hover { background-color: var(--muted); } .led-hscroll::-webkit-scrollbar-button, .led-hscroll::-webkit-scrollbar-corner { display: none; } +.reads-note { margin-top: 12px; display: flex; flex-direction: column; align-items: center; gap: 8px; } +.reads-note p { margin: 0; } .led-none { padding: 18px 16px; color: var(--muted); text-align: center; line-height: 1.5; } .led-sk { padding: 11px 14px; } .led-sk + .led-sk { border-top: 1px solid var(--line-2); } diff --git a/internal/gui/assets/plugins/sessions/client.js b/internal/gui/assets/plugins/sessions/client.js index a92125b05..0de6f0638 100644 --- a/internal/gui/assets/plugins/sessions/client.js +++ b/internal/gui/assets/plugins/sessions/client.js @@ -589,6 +589,13 @@ magpie.plugin("sessions", (ctx) => { ? "These {agent} sessions were seen only through magpie's gateway: {agent}'s own files of them aren't on this computer (it may run on another one, in a container or with another config folder), so they can't be resumed here. Delete takes one off this list and moves any conversation magpie recorded of it to its trash; Usage keeps what it spent." : "Sessions under \"Seen through the gateway\" have no {agent} files on this computer, so they can't be resumed here. Delete takes one off this list and moves any conversation magpie recorded of it to its trash; Usage keeps what it spent.", { agent: a.name }))); } + // output speed is measured as the reply streams through the gateway; a + // session file has no per-token times, so with none of the rows measured + // the page says where the speed is and where the files' own figures are + // (simonzyzy on X: sessions with no provider set up) + if (!data.reads?.gateway && data.sessions.length && !data.sessions.some((s) => speedOf(s))) { + box.append(el("p", "usage-note sm-note sm-speed-note", t("Live output speed is measured on requests that go through magpie's gateway. For agents that don't, each call's tokens and time are in Usage › Requests, read from their session files."))); + } const prov = providerBar(); if (prov) box.append(prov); box.append(selectBar(), el("div", "sm-tree")); diff --git a/internal/gui/assets/plugins/sessions/i18n.js b/internal/gui/assets/plugins/sessions/i18n.js index c8540244f..3d17f9c0d 100644 --- a/internal/gui/assets/plugins/sessions/i18n.js +++ b/internal/gui/assets/plugins/sessions/i18n.js @@ -2,6 +2,7 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "Live output speed is measured on requests that go through magpie's gateway. For agents that don't, each call's tokens and time are in Usage › Requests, read from their session files.": "实时输出速度是在请求经过 magpie 网关时测得的。没有经过网关的 Agent,每次调用的 token 数和耗时可在「用量 › 请求」查看,数据读自它们的会话文件。", "Avg {n} tok/s": "平均 {n} token/秒", "Tool {n}s": "工具 {n} 秒", "Round average": "本轮平均", @@ -97,6 +98,7 @@ magpie.strings({ "Searched what was said in the latest {n} of {total} sessions.": "已搜索最近 {n} 个会话的对话内容(共 {total} 个)。", }, "zh-TW": { + "Live output speed is measured on requests that go through magpie's gateway. For agents that don't, each call's tokens and time are in Usage › Requests, read from their session files.": "即時輸出速度是在請求經過 magpie 閘道時量測的。沒有經過閘道的 Agent,每次呼叫的 token 數和耗時可在「用量 › 請求」查看,資料讀自它們的會話檔案。", "Avg {n} tok/s": "平均 {n} token/秒", "Tool {n}s": "工具 {n} 秒", "Round average": "本輪平均", @@ -192,6 +194,7 @@ magpie.strings({ "Searched what was said in the latest {n} of {total} sessions.": "已搜尋最近 {n} 個會話的對話內容(共 {total} 個)。", }, ja: { + "Live output speed is measured on requests that go through magpie's gateway. For agents that don't, each call's tokens and time are in Usage › Requests, read from their session files.": "リアルタイムの出力速度は、リクエストが magpie のゲートウェイを通るときに計測されます。通らないエージェントについては、各呼び出しのトークン数と所要時間をセッションファイルから読み取り、「使用量 › リクエスト」で確認できます。", "Avg {n} tok/s": "平均 {n} トークン/秒", "Tool {n}s": "ツール {n} 秒", "Round average": "このターンの平均", @@ -287,6 +290,7 @@ magpie.strings({ "Searched what was said in the latest {n} of {total} sessions.": "最新 {n} 件の会話の内容を検索しました(全 {total} 件)。", }, de: { + "Live output speed is measured on requests that go through magpie's gateway. For agents that don't, each call's tokens and time are in Usage › Requests, read from their session files.": "Die Live-Ausgabegeschwindigkeit wird bei Anfragen gemessen, die über das magpie-Gateway laufen. Bei Agenten, die das nicht tun, stehen Tokens und Dauer jedes Aufrufs unter Nutzung › Anfragen, gelesen aus ihren Sitzungsdateien.", "Avg {n} tok/s": "Ø {n} Token/s", "Tool {n}s": "Tool {n} s", "Round average": "Ø dieser Runde", diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index c1c73d2de..6b46227cb 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -212,7 +212,9 @@ magpie.strings({ "No calls in the last 24 hours.": "最近 24 小时没有调用。", "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 使用目录中的模型;每次经过网关的调用都会计入这里。", + "Calls through the gateway and the calls Claude Code's and Codex's own session files record are counted here, with no provider set up.": "不设置任何提供商也行:经过网关的调用,以及 Claude Code 和 Codex 自己会话文件里记录的调用,都会计入这里。", + "magpie reads no agent's session files until you allow it, so {names} calls aren't counted here yet.": "magpie 在你允许之前不会读取任何 Agent 的会话文件,所以 {names} 的调用还没有计入这里。", + "Count {names}": "统计 {names}", "inside output": "计入输出", "{when} · {tokens} tokens · {n} call": "{when} · {tokens} token · {n} 次调用", "{when} · {tokens} tokens · {n} calls": "{when} · {tokens} token · {n} 次调用", @@ -468,7 +470,9 @@ magpie.strings({ "No calls in the last 24 hours.": "最近 24 小時沒有呼叫。", "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 使用目錄中的模型;每次經過閘道的呼叫都會計入這裡。", + "Calls through the gateway and the calls Claude Code's and Codex's own session files record are counted here, with no provider set up.": "不設定任何供應商也行:經過閘道的呼叫,以及 Claude Code 和 Codex 自己會話檔案裡記錄的呼叫,都會計入這裡。", + "magpie reads no agent's session files until you allow it, so {names} calls aren't counted here yet.": "magpie 在你允許之前不會讀取任何 Agent 的會話檔案,所以 {names} 的呼叫還沒有計入這裡。", + "Count {names}": "統計 {names}", "inside output": "計入輸出", "{when} · {tokens} tokens · {n} call": "{when} · {tokens} token · {n} 次呼叫", "{when} · {tokens} tokens · {n} calls": "{when} · {tokens} token · {n} 次呼叫", @@ -724,7 +728,9 @@ magpie.strings({ "No calls in the last 24 hours.": "過去 24 時間の呼び出しはありません。", "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.": "エージェントにカタログのモデルを指定して使うと、ゲートウェイ経由のすべての呼び出しがここに集計されます。", + "Calls through the gateway and the calls Claude Code's and Codex's own session files record are counted here, with no provider set up.": "プロバイダーを設定しなくても、ゲートウェイ経由の呼び出しと、Claude Code や Codex 自身のセッションファイルに記録された呼び出しがここに集計されます。", + "magpie reads no agent's session files until you allow it, so {names} calls aren't counted here yet.": "magpie は許可するまでエージェントのセッションファイルを読まないため、{names} の呼び出しはまだ集計されていません。", + "Count {names}": "{names} を集計する", "inside output": "出力に含む", "{when} · {tokens} tokens · {n} call": "{when} · {tokens} トークン · {n} 回の呼び出し", "{when} · {tokens} tokens · {n} calls": "{when} · {tokens} トークン · {n} 回の呼び出し", @@ -980,7 +986,9 @@ magpie.strings({ "No calls in the last 24 hours.": "Keine Aufrufe in den letzten 24 Stunden.", "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.", + "Calls through the gateway and the calls Claude Code's and Codex's own session files record are counted here, with no provider set up.": "Auch ohne eingerichteten Anbieter werden hier die Aufrufe über das Gateway und die in den Sitzungsdateien von Claude Code und Codex selbst verzeichneten Aufrufe gezählt.", + "magpie reads no agent's session files until you allow it, so {names} calls aren't counted here yet.": "magpie liest keine Sitzungsdateien von Agenten, bis Sie es erlauben; deshalb sind die Aufrufe von {names} hier noch nicht gezählt.", + "Count {names}": "{names} zählen", "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", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index b4304d1f8..1156b8cbb 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -317,6 +317,33 @@ function typedTime(v, end) { const m = /^([01]?\d|2[0-3]):?([0-5]\d)$/.exec(v); return m ? m[1].padStart(2, "0") + ":" + m[2] : null; } +// readsNote: on an empty page, whether magpie is not yet allowed to read the +// agents' session files, the only reason Claude Code's and Codex's own calls +// (tokens, time, speed) are missing with no provider set up (simonzyzy on X). +// It asks once what the Sessions page's consent knows, and says so with the +// one button that grants it for the agents found. +async function readsNote(host) { + let r; + try { r = await api("sessions/reads"); } catch { return; } + if (!r || r.asked || r.gateway || !r.found?.length || !host.isConnected) return; + const box = el("div", "reads-note"); + const names = r.found.map((x) => x.name).join(t(", ")); + box.append(el("p", "", t("magpie reads no agent's session files until you allow it, so {names} calls aren't counted here yet.", { names }))); + const go = el("button", "text primary", t("Count {names}", { names })); + go.type = "button"; + go.onclick = async () => { + go.disabled = true; + const agents = {}; + for (const x of r.found) agents[x.agent] = true; + try { + await api("sessions/reads", { all: false, agents }); + await loadUsage(); + } catch (e) { status(e.message, "err"); go.disabled = false; } + }; + box.append(go); + host.append(box); +} + // 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."; @@ -747,7 +774,8 @@ function renderUsage() { 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."))); + stats.append(el("div", "none", t(none) + " " + t("Calls through the gateway and the calls Claude Code's and Codex's own session files record are counted here, with no provider set up."))); + readsNote(stats); $("#usageNote").textContent = ""; $("#usageClear").hidden = true; return; @@ -2880,6 +2908,7 @@ function renderLedger() { 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))); + if (!filtered) readsNote(wrap.firstChild); ledFit(); ledHScroll(); pager.hidden = true; diff --git a/internal/gui/tests/usage-reads-note.test.cjs b/internal/gui/tests/usage-reads-note.test.cjs new file mode 100644 index 000000000..d3d8dfdf4 --- /dev/null +++ b/internal/gui/tests/usage-reads-note.test.cjs @@ -0,0 +1,116 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// simonzyzy on X: with no provider set up, Claude Code's and Codex's own +// sessions, tokens and speed seemed impossible. magpie reads no agent's +// session files until they are allowed (sessions/reads asked false), and an +// empty Usage page only told people to route an agent through the gateway. +// Now the Overview and the Requests page say the files aren't read yet and +// offer the one button that allows the agents found; once allowed (asked +// true) the note is gone. Chromium and WebKit, every language; API faked. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const found = () => [ + { agent: "claude", name: "Claude Code", icon: "claudecode-color", on: false }, + { agent: "codex", name: "Codex", icon: "codex-color", on: false }, +]; +const empty = { calls: 0, errors: 0, input: 0, output: 0, cache_read: 0, cache_write: 0, reasoning: 0, cost: 0, unpriced: 0, path: "/test/usage.jsonl", bucket: "day", series: [], agents: [], models: [] }; + +function serve(lang, store, posts) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [], models: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, calls: [], groups: [] } }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/sessions/reads") { + if (req.method() === "POST") { posts.push(req.postDataJSON()); store.asked = true; } + return json({ asked: store.asked, all: false, found: found() }); + } + if (url.pathname === "/api/speeds") return json([]); + if (url.pathname === "/api/sessions/manage") { + const at = new Date(Date.now() - 300e3).toISOString(); + return json({ agents: [{ agent: "claude", count: 1, deletable: true, name: "Claude Code", icon: "claudecode-color" }], agent: "claude", sessions: [{ agent: "claude", id: "c-1", cwd: "/work/app", title: "a chat", start: at, last: at, models: [], resume: "", path: "/x/c", size: 10, messages: 2, files: 1, deletable: true }], terminal: false, trash: [], trashDir: "", reads: { asked: true, all: true, found: found() } }); + } + if (url.pathname === "/api/usage/requests") return json({ ...empty, rows: [], offset: 0, total: 0, by: { provider: [], agent: [], model: [] } }); + if (url.pathname === "/api/usage") return json(empty); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] }); + if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} }); + if (url.pathname.startsWith("/api/window/")) return route.fulfill({ status: 204 }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404 }); } + }; +} + +const ASK = "magpie reads no agent's session files until you allow it, so {names} calls aren't counted here yet."; +const LANGS = [["en", 900], ["zh", 420], ["zh-TW", 420], ["ja", 420], ["de", 390]]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const [lang, width] of LANGS) { + test(`${engine} ${lang} ${width}px: an empty Usage page says session files aren't read yet, and allows them`, 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, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(8000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const store = { asked: false }, posts = []; + await page.route("**/*", serve(lang, store, posts)); + await page.goto("http://magpie.test/?view=usage"); + const names = "Claude Code, Codex"; + const ask = await page.evaluate(([s, n]) => t(s, { names: n }), [ASK, names.replace(", ", await page.evaluate(() => t(", ")))]); + if (lang !== "en") assert.notEqual(ask, ASK.replace("{names}", names), "translated"); + // the Overview + const note = page.locator("#stats .reads-note"); + await note.waitFor(); + assert.equal(await note.locator("p").textContent(), ask); + // not worded as if a provider were needed + assert.ok(!/catalog model/i.test(await page.locator("#stats").textContent())); + const over = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth); + assert.equal(over, false, "no sideways scroll"); + // the Requests tab says the same + await page.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click(); + await page.locator("#ledWrap .reads-note").waitFor(); + assert.equal(await page.locator("#ledWrap .reads-note p").textContent(), ask); + assert.equal(posts.length, 0, "nothing allowed before the button"); + await page.locator("#ledWrap .reads-note button").click(); + await page.locator("#ledWrap .reads-note").waitFor({ state: "detached" }); + assert.deepEqual(posts, [{ all: false, agents: { claude: true, codex: true } }]); + assert.deepEqual(errors, []); + }); + } +} + +const SPEED = "Live output speed is measured on requests that go through magpie's gateway. For agents that don't, each call's tokens and time are in Usage › Requests, read from their session files."; +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const [lang, width] of LANGS) { + test(`${engine} ${lang} ${width}px: Sessions say where the output speed is when none was measured`, 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, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(8000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, { asked: true }, [])); + await page.goto("http://magpie.test/?view=sessions"); + const note = page.locator("#view-sessions .sm-speed-note"); + await note.waitFor(); + const want = await page.evaluate((s) => t(s), SPEED); + if (lang !== "en") assert.notEqual(want, SPEED, "translated"); + assert.equal(await note.textContent(), want); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth), false); + assert.deepEqual(errors, []); + }); + } +}