From e6bf4adf1f3f87001335828ca52f7985e6b3eeb7 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 12 Nov 2026 01:57:05 +0800 Subject: [PATCH] usage: Claude Code's helper requests are labelled, the largest cache write is one click away (recih on X, #6199) Claude Code's AgentSummary and its auto mode classifier name themselves nowhere in the request, so there is no client marker to read. The gateway tells them by their content (inferredKind: a claude-cli/ request on the Messages API; the classifier by autoModeClassifierAsk, the summary by its last user text "Describe your ... in 3-5 words") and records them as agent_summary_inferred and auto_mode_check_inferred. The purpose catalog names them "Progress summary (inferred)" and "Auto mode check (inferred)" and puts each with its plain kind's purpose, so the existing Purpose filter lists both; nothing known and nothing inferred share a name. A tool that printed the same words, a chat, and another agent's request stay unmarked. A requests page now also holds BigWrite, the gateway-served row that wrote the most to the cache (cells, page-v1.json and pageFromLedger all carry it; rows from session files have no request to open). The Requests line shows it as "109K largest write", a button that opens that request through openUsageRoute. settledCountVersion is raised to 3, which keys the cached pages. Not done: the per-request branch recovery result asked for in #6199. No structured field holds it. Run on mote (load 21-24 of 18 cores, mica was higher): go test ./internal/usage ./internal/usageapi, the gateway and gui purpose tests, go vet for darwin, linux (nogui) and windows, gofmt; the GUI files usage-big-write (new), purpose-filter, routing-kind, i18n-keys and usage-ledger in chromium and webkit. Broken by hand: inferredKind returning "" turns TestClaudeHelperRequestsAreLabelled red; the larger-than test of BigWrite.add turned round turns TestRequestPageBigWrite red on both paths; the jump off turns usage-big-write red. Not tried: a real Claude Code session against a live subscription, Linux WebKitGTK. --- docs/subsystems/gateway-sessions.md | 21 ++++++ internal/gateway/gateway.go | 5 ++ internal/gateway/helper_kind_test.go | 51 ++++++++++++++ internal/gateway/observe.go | 45 ++++++++++++ internal/gui/assets/i18n.js | 16 +++++ internal/gui/assets/plugins/usage/i18n.js | 4 ++ internal/gui/assets/plugins/usage/page.js | 7 ++ internal/gui/assets/purposes.js | 2 +- internal/gui/tests/usage-big-write.test.cjs | 76 +++++++++++++++++++++ internal/usage/big_write.go | 33 +++++++++ internal/usage/big_write_test.go | 62 +++++++++++++++++ internal/usage/heat_disk.go | 2 +- internal/usage/page_split.go | 11 ++- internal/usage/purpose.go | 19 ++++++ internal/usage/request_cells.go | 4 ++ internal/usage/request_page.go | 5 ++ internal/usageapi/usageapi.go | 4 ++ 17 files changed, 362 insertions(+), 5 deletions(-) create mode 100644 internal/gateway/helper_kind_test.go create mode 100644 internal/gui/tests/usage-big-write.test.cjs create mode 100644 internal/usage/big_write.go create mode 100644 internal/usage/big_write_test.go diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index da4592203..067ae3885 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -989,6 +989,27 @@ arguments are never kept, not even masked. Failed. The Purpose filter names `kind:mcp` "MCP tool" (`purposeKinds`, `purposes.js`). +### Claude Code's helper requests and the largest cache write + +Claude Code's AgentSummary ("Describe your most recent action in 3-5 +words.") and its auto mode classifier name themselves nowhere in the +request, so `inferredKind` (observe.go) tells them by their content, for +a `claude-cli/` request on the Messages API only, and the ledger row's +Kind is `agent_summary_inferred` or `auto_mode_check_inferred` +(`usage.InferredSuffix`). The name says "(inferred)"; both spellings share +the plain kind's purpose, which a client marker would use. Anything else +stays unmarked. + +A requests page also holds `BigWrite` (big_write.go): the gateway-served +row that wrote the most to the cache, kept per chunk (`chunkPart.big`) and +merged as the cells are. Rows read from session files have no request to +open and are left out. The Requests line shows it as a button that opens +that request (`openUsageRoute`). The counting is keyed by +`settledCountVersion`. `TestRequestPageBigWrite`, +`TestClaudeHelperRequestsAreLabelled` and `usage-big-write.test.cjs` +cover it. The per-request branch recovery result asked for in #6199 is not +recorded: no structured field holds it. + `TestMCPToolCallIsARequestRow`, `TestMCPHubCallIsARequestRow`, `TestMCPCalledFromStdioIsARow` and the others in `mcp_calls_test.go`, `TestToolCallsAreReported` (imagemcp), `TestMCPCallRowsListedNotCounted` diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index a6ab60891..607f8c2b6 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2428,6 +2428,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if call.Kind == "" && factsOf(from, plain).compact { call.Kind = KindCompact } + // Claude Code's auto mode classifier and AgentSummary name themselves + // nowhere: told by their content, recorded as inferred + if call.Kind == "" { + call.Kind = inferredKind(r.Header, from, body) + } // the reply counted as it reaches the agent, for the Routing page // while it is out (#4951); learned from once it ends capture.live = liveBegin(inflightOf(r.Context()), call.Model, from) diff --git a/internal/gateway/helper_kind_test.go b/internal/gateway/helper_kind_test.go new file mode 100644 index 000000000..f42eebf2c --- /dev/null +++ b/internal/gateway/helper_kind_test.go @@ -0,0 +1,51 @@ +package gateway + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/usage" +) + +// recih on X (#6199): Claude Code's AgentSummary and auto mode classifier +// name themselves nowhere in the request, so the Usage page could not say +// what a request was for. They are told by their content and recorded as +// inferred, which the name says; any other request stays unmarked. +func TestClaudeHelperRequestsAreLabelled(t *testing.T) { + summary := `{"model":"m1","max_tokens":64,"messages":[` + + `{"role":"user","content":"start the task"},` + + `{"role":"assistant","content":[{"type":"tool_use","id":"c1","name":"Bash","input":{"command":"ls"}}]},` + + `{"role":"user","content":[{"type":"tool_result","tool_use_id":"c1","content":"a"},{"type":"text","text":"Describe your most recent action in 3-5 words. Do not use tools."}]}]}` + // a tool that printed the same words, and a chat that ends in them + printed := strings.Replace(summary, `"content":"a"`, `"content":"Describe your most recent action in 3-5 words."`, 1) + printed = strings.Replace(printed, `,{"type":"text","text":"Describe your most recent action in 3-5 words. Do not use tools."}`, "", 1) + chat := `{"model":"m1","max_tokens":4096,"messages":[{"role":"user","content":"write 3-5 words about the sea"}]}` + for _, tc := range []struct{ name, body, ua, want string }{ + {"summary", summary, "claude-cli/2.1.310 (external, cli)", "agent_summary_inferred"}, + {"classifier", autoModeAsk("m1"), "claude-cli/2.1.310 (external, cli)", "auto_mode_check_inferred"}, + {"printed by a tool", printed, "claude-cli/2.1.310 (external, cli)", ""}, + {"a chat", chat, "claude-cli/2.1.310 (external, cli)", ""}, + {"another agent's summary", summary, "curl/8", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + dshSetup(t) + s := New() + req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(tc.body)) + req.Header.Set("User-Agent", tc.ua) + req.Header.Set("anthropic-version", "2023-06-01") + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body.String()) + } + if got := lastRoute(s).Kind; got != tc.want { + t.Logf("agent %q from %v", lastRoute(s).Agent, "?") + t.Fatalf("kind %q, want %q", got, tc.want) + } + if tc.want != "" && usage.PurposeOf(tc.want) != "kind:"+strings.TrimSuffix(tc.want, usage.InferredSuffix) { + t.Fatalf("purpose %q", usage.PurposeOf(tc.want)) + } + }) + } +} diff --git a/internal/gateway/observe.go b/internal/gateway/observe.go index d6b5fd1d3..9052eb091 100644 --- a/internal/gateway/observe.go +++ b/internal/gateway/observe.go @@ -1,11 +1,14 @@ package gateway import ( + "bytes" "context" "net/http" + "strings" "time" "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/usage" ) @@ -64,6 +67,48 @@ func observedKind(agent, kind string, body []byte) string { return kind } +// inferredKind is the kind of Claude Code's helper requests it names +// nowhere in the request: its auto mode classifier and its AgentSummary, +// told by their content. They are recorded as inferred +// (usage.InferredSuffix), never as the client's word; "" for any other. +func inferredKind(in http.Header, from provider.Protocol, body []byte) string { + if !fromClaudeCode(in) || from != provider.Anthropic { + return "" + } + switch { + case autoModeClassifierAsk(body): + return usage.KindAutoMode + usage.InferredSuffix + case agentSummaryAsk(body): + return usage.KindAgentSummary + usage.InferredSuffix + } + return "" +} + +// agentSummaryAsk reports whether body, a Messages API request, is Claude +// Code's AgentSummary: the sub-agent's conversation with a last user +// message that ends in the ask for a few words of progress ("Describe +// your most recent action in 3-5 words."). The bytes are looked at first: +// every request passes here. +func agentSummaryAsk(body []byte) bool { + if !bytes.Contains(body, []byte("3-5 words")) { + return false + } + req, err := parseAnthropic(body) + if err != nil || len(req.Messages) == 0 { + return false + } + last := req.Messages[len(req.Messages)-1] + if last.Role != "user" || len(last.Parts) == 0 { + return false + } + p := last.Parts[len(last.Parts)-1] + if p.Kind != Text { + return false + } + ask := strings.TrimSpace(p.Text) + return strings.HasPrefix(ask, "Describe your ") && strings.Contains(ask, " in 3-5 words") +} + func (o *observed) end(call Call, millis int64) { if o == nil { return diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 85653f6c8..a3d846817 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4254,6 +4254,10 @@ const I18N = { "Compaction": "压缩", "Memory": "记忆", "Title": "标题", + "Progress summary": "进度摘要", + "Progress summary (inferred)": "进度摘要(推断)", + "Auto mode check": "自动模式检查", + "Auto mode check (inferred)": "自动模式检查(推断)", "Description": "描述", "Subagent": "子代理", "subagent model": "子代理模型", @@ -9328,6 +9332,10 @@ const I18N = { "Compaction": "壓縮", "Memory": "記憶", "Title": "標題", + "Progress summary": "進度摘要", + "Progress summary (inferred)": "進度摘要(推斷)", + "Auto mode check": "自動模式檢查", + "Auto mode check (inferred)": "自動模式檢查(推斷)", "Subagent": "子代理", "subagent model": "子代理模型", "the lead's pick, else same as model": "由主代理自選,未指定時同主模型", @@ -14421,6 +14429,10 @@ const I18N = { "Compaction": "コンパクション", "Memory": "メモリ", "Title": "タイトル", + "Progress summary": "進捗の要約", + "Progress summary (inferred)": "進捗の要約(推定)", + "Auto mode check": "自動モードの確認", + "Auto mode check (inferred)": "自動モードの確認(推定)", "Description": "説明", "Subagent": "サブエージェント", "subagent model": "サブエージェントのモデル", @@ -19522,6 +19534,10 @@ const I18N = { "Compaction": "Kompaktierung", "Memory": "Memory", "Title": "Titel", + "Progress summary": "Fortschrittszusammenfassung", + "Progress summary (inferred)": "Fortschrittszusammenfassung (abgeleitet)", + "Auto mode check": "Auto-Modus-Prüfung", + "Auto mode check (inferred)": "Auto-Modus-Prüfung (abgeleitet)", "Description": "Beschreibung", "Subagent": "Subagent", "subagent model": "Modell der Subagenten", diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index 6b46227cb..d81065414 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -91,6 +91,7 @@ magpie.strings({ "All agents": "全部 Agent", "{n} out": "输出 {n}", "{n} cache write": "缓存写入 {n}", + "{n} largest 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。", @@ -349,6 +350,7 @@ magpie.strings({ "All agents": "全部 Agent", "{n} out": "輸出 {n}", "{n} cache write": "快取寫入 {n}", + "{n} largest 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。", @@ -607,6 +609,7 @@ magpie.strings({ "All agents": "すべてのエージェント", "{n} out": "出力 {n}", "{n} cache write": "キャッシュ書き込み {n}", + "{n} largest 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 を経由せず、直接ベンダーに送られました。", @@ -865,6 +868,7 @@ magpie.strings({ "All agents": "Alle Agenten", "{n} out": "{n} aus", "{n} cache write": "{n} Cache-Schreiben", + "{n} largest write": "Größter Cache-Schreibvorgang {n}", "{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.", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index 1156b8cbb..4d750a28b 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -2829,6 +2829,13 @@ function renderLedger() { if (l.canceled) say("{n} canceled", l.canceled); } $("#ledSum").textContent = sum.join(" · "); + // the request that wrote the most to the cache, one click from its detail (recih on X, #6199) + const big = l.big_write; + if (l.total && big?.route) { + const jump = el("button", "text", t("{n} largest write", { n: fmtN(big.n) })); + jump.onclick = () => window.openUsageRoute({ id: big.route, time: big.at, model: big.model }); + $("#ledSum").append(" · ", jump); + } $("#ledSum").title = sum.join() == exact.join() ? "" : exact.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' diff --git a/internal/gui/assets/purposes.js b/internal/gui/assets/purposes.js index c98a4f76b..e1cc0131c 100644 --- a/internal/gui/assets/purposes.js +++ b/internal/gui/assets/purposes.js @@ -1,2 +1,2 @@ // Code generated by go generate ./internal/usage; DO NOT EDIT. -const REQUEST_KINDS = {"agent_job":{"purpose":"kind:collab_spawn","name":"Subagent"},"ambient_suggestion_safety":{"purpose":"kind:ambient_suggestions","name":"Suggestions"},"ambient_suggestions":{"purpose":"kind:ambient_suggestions","name":"Suggestions"},"api_detect":{"purpose":"kind:api_detect","name":"Detect APIs"},"auto_review":{"purpose":"kind:guardian","name":"Approval check"},"cache_keepalive":{"purpose":"kind:cache_keepalive","name":"Cache keep-alive"},"collab_spawn":{"purpose":"kind:collab_spawn","name":"Subagent"},"compact":{"purpose":"kind:compact","name":"Compaction"},"composer_predictions":{"purpose":"kind:composer_predictions","name":"Prediction"},"connection_check":{"purpose":"kind:connection_check","name":"Connection check"},"guardian":{"purpose":"kind:guardian","name":"Approval check"},"guardian_review":{"purpose":"kind:guardian","name":"Approval check"},"luna_reserve":{"purpose":"kind:luna_reserve","name":"Luna Reserve"},"mcp":{"purpose":"kind:mcp","name":"MCP tool"},"memgen":{"purpose":"kind:memory_consolidation","name":"Memory"},"memory":{"purpose":"kind:memory_consolidation","name":"Memory"},"memory_consolidation":{"purpose":"kind:memory_consolidation","name":"Memory"},"model_list":{"purpose":"kind:model_list","name":"Model list"},"provider_test":{"purpose":"kind:provider_test","name":"Test"},"review":{"purpose":"kind:review","name":"Review"},"routing":{"purpose":"kind:routing","name":"Routing classifier"},"thread_description":{"purpose":"kind:thread_description","name":"Description"},"thread_spawn":{"purpose":"kind:collab_spawn","name":"Subagent"},"thread_title":{"purpose":"kind:thread_title","name":"Title"},"thread_title_reconsideration":{"purpose":"kind:thread_title","name":"Title"},"title":{"purpose":"kind:thread_title","name":"Title"},"title_generation":{"purpose":"kind:thread_title","name":"Title"},"vision":{"purpose":"kind:vision","name":"Image description"},"web_search":{"purpose":"kind:web_search","name":"Web search"}}; +const REQUEST_KINDS = {"agent_job":{"purpose":"kind:collab_spawn","name":"Subagent"},"agent_summary":{"purpose":"kind:agent_summary","name":"Progress summary"},"agent_summary_inferred":{"purpose":"kind:agent_summary","name":"Progress summary (inferred)"},"ambient_suggestion_safety":{"purpose":"kind:ambient_suggestions","name":"Suggestions"},"ambient_suggestions":{"purpose":"kind:ambient_suggestions","name":"Suggestions"},"api_detect":{"purpose":"kind:api_detect","name":"Detect APIs"},"auto_mode_check":{"purpose":"kind:auto_mode_check","name":"Auto mode check"},"auto_mode_check_inferred":{"purpose":"kind:auto_mode_check","name":"Auto mode check (inferred)"},"auto_review":{"purpose":"kind:guardian","name":"Approval check"},"cache_keepalive":{"purpose":"kind:cache_keepalive","name":"Cache keep-alive"},"collab_spawn":{"purpose":"kind:collab_spawn","name":"Subagent"},"compact":{"purpose":"kind:compact","name":"Compaction"},"composer_predictions":{"purpose":"kind:composer_predictions","name":"Prediction"},"connection_check":{"purpose":"kind:connection_check","name":"Connection check"},"guardian":{"purpose":"kind:guardian","name":"Approval check"},"guardian_review":{"purpose":"kind:guardian","name":"Approval check"},"luna_reserve":{"purpose":"kind:luna_reserve","name":"Luna Reserve"},"mcp":{"purpose":"kind:mcp","name":"MCP tool"},"memgen":{"purpose":"kind:memory_consolidation","name":"Memory"},"memory":{"purpose":"kind:memory_consolidation","name":"Memory"},"memory_consolidation":{"purpose":"kind:memory_consolidation","name":"Memory"},"model_list":{"purpose":"kind:model_list","name":"Model list"},"provider_test":{"purpose":"kind:provider_test","name":"Test"},"review":{"purpose":"kind:review","name":"Review"},"routing":{"purpose":"kind:routing","name":"Routing classifier"},"thread_description":{"purpose":"kind:thread_description","name":"Description"},"thread_spawn":{"purpose":"kind:collab_spawn","name":"Subagent"},"thread_title":{"purpose":"kind:thread_title","name":"Title"},"thread_title_reconsideration":{"purpose":"kind:thread_title","name":"Title"},"title":{"purpose":"kind:thread_title","name":"Title"},"title_generation":{"purpose":"kind:thread_title","name":"Title"},"vision":{"purpose":"kind:vision","name":"Image description"},"web_search":{"purpose":"kind:web_search","name":"Web search"}}; diff --git a/internal/gui/tests/usage-big-write.test.cjs b/internal/gui/tests/usage-big-write.test.cjs new file mode 100644 index 000000000..9b151f100 --- /dev/null +++ b/internal/gui/tests/usage-big-write.test.cjs @@ -0,0 +1,76 @@ +// The Usage page's Requests line names the largest cache write, one click +// from its request, and says Claude Code's helper requests by their purpose, +// "(inferred)" where the gateway read it from the body (recih on X, #6199). +// Run as described in README.md; no local accounts or providers are used. +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 = process.env.ASSET_DIR || path.resolve(__dirname, "../assets"); +const now = new Date(); +const rows = [ + { route_id: 12, kind: "agent_summary_inferred", cache_write: 108546, cache_read: 11541 }, + { route_id: 11, kind: "", cache_write: 900, cache_read: 50000 }, + { route_id: 10, kind: "auto_mode_check_inferred", cache_write: 40, cache_read: 0 }, +].map((r, i) => ({ ...r, t: new Date(now - i * 1000).toISOString(), agent: "claude", agentName: "Claude Code", icon: "claude-color", + provider: "anthropic", providerName: "Anthropic", model: "example-model", req: "example-model", served: "example-model", + in: 10, out: 2, ms: 200, status: 200, cost: 0.01, priced: true })); +function ledger(q) { + const filtered = q.get("route") ? rows.filter((r) => r.route_id === +q.get("route")) : rows; + const sum = (k) => filtered.reduce((n, r) => n + r[k], 0); + return { rows: filtered, offset: 0, total: filtered.length, calls: filtered.length, errors: 0, + input: sum("in"), output: sum("out"), cache_read: sum("cache_read"), cache_write: sum("cache_write"), cost: 0.03, unpriced: 0, + big_write: { n: 108546, route: 12, at: rows[0].t, model: "example-model" }, + agents: [{ id: "claude", name: "Claude Code", icon: "claude-color" }], purposes: ["kind:agent_summary", "kind:auto_mode_check", "unmarked"] }; +} +function server(lang, asked) { + 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:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window={};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], models: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/usage/requests") { asked.push(url.searchParams); return json(ledger(url.searchParams)); } + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} +const words = { + en: { big: "109K largest write", summary: "Progress summary (inferred)", classifier: "Auto mode check (inferred)" }, + zh: { big: "最大写入 109K", summary: "进度摘要(推断)", classifier: "自动模式检查(推断)" }, +}; +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + test(`${engine} ${lang}: the largest cache write opens its request, helper requests are named`, 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: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(7000); + page.setDefaultNavigationTimeout(60000); + const errors = [], asked = []; + page.on("pageerror", (e) => { if (!/^ResizeObserver loop completed with undelivered notifications/.test(e.message)) errors.push(e.message); }); + await page.route("**/*", server(lang, asked)); + await page.goto("http://magpie.test/?view=usage&tab=requests"); + await page.waitForFunction(() => document.querySelectorAll("#ledWrap tbody tr.led-row").length === 3); + const jump = page.locator("#ledSum button"); + await jump.waitFor({ state: "visible" }); + assert.equal(await jump.count(), 1); + assert.equal(await jump.textContent(), words[lang].big); + assert.equal(await page.evaluate(() => window.kindName("agent_summary_inferred")), words[lang].summary); + assert.equal(await page.evaluate(() => window.kindName("auto_mode_check_inferred")), words[lang].classifier); + // both spellings are one purpose, the plain kind's + assert.equal(await page.evaluate(() => purposeOf("agent_summary_inferred")), "kind:agent_summary"); + await jump.click(); + await page.locator("#ledRoute").waitFor({ state: "visible" }); + await page.waitForFunction(() => document.querySelectorAll("#ledWrap tbody tr.led-row").length === 1); + assert.equal(asked.at(-1).get("route"), "12"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/usage/big_write.go b/internal/usage/big_write.go new file mode 100644 index 000000000..ca7b388e2 --- /dev/null +++ b/internal/usage/big_write.go @@ -0,0 +1,33 @@ +package usage + +import "time" + +// BigWrite is the request that wrote the most to the cache among a page's +// counted rows that the gateway served (RouteID is the request the Routing +// page keeps; a call read from an agent's own session file has none, so +// there is no request to jump to). A page's totals hide one request +// that rewrote a long conversation behind many that only read it +// (recih on X, #6199). +type BigWrite struct { + N int `json:"n,omitempty"` + RouteID int64 `json:"route,omitempty"` + At time.Time `json:"at,omitzero"` + Model string `json:"model,omitempty"` +} + +// add counts r, a counted row the filter keeps. +func (b *BigWrite) add(r *Row) { + if r.RouteID == 0 || r.CacheWrite <= 0 { + return + } + if r.CacheWrite > b.N || r.CacheWrite == b.N && r.Time.After(b.At) { + *b = BigWrite{N: r.CacheWrite, RouteID: r.RouteID, At: r.Time, Model: r.Model} + } +} + +// merge keeps the larger of b and o. +func (b *BigWrite) merge(o BigWrite) { + if o.N > b.N || o.N == b.N && o.N > 0 && o.At.After(b.At) { + *b = o + } +} diff --git a/internal/usage/big_write_test.go b/internal/usage/big_write_test.go new file mode 100644 index 000000000..7f8cd575e --- /dev/null +++ b/internal/usage/big_write_test.go @@ -0,0 +1,62 @@ +package usage + +import ( + "testing" + "time" + + "github.com/yetone/magpie/internal/sessions" +) + +// recih on X (#6199): a page's cache totals hide one request that wrote a +// whole conversation again behind many that read it. The page names the +// largest write, and the request to jump to, on both paths that build it. +func TestRequestPageBigWrite(t *testing.T) { + pageHome(t) + now := time.Now() + at := now.Add(-time.Hour) + recs := []Record{ + {Time: at, Agent: "claude", Provider: "p", Model: "m", RouteID: 11, CacheWrite: 900, CacheRead: 50000, Status: 200}, + {Time: at.Add(time.Minute), Agent: "claude", Provider: "p", Model: "m", RouteID: 12, CacheWrite: 108546, CacheRead: 11541, Output: 197, Status: 200, Kind: KindAgentSummary + InferredSuffix}, + {Time: at.Add(2 * time.Minute), Agent: "claude", Provider: "p", Model: "m", RouteID: 13, CacheWrite: 400, Status: 200}, + // turned away: counted nowhere + {Time: at.Add(3 * time.Minute), Agent: "claude", Provider: "p", Model: "m", RouteID: 14, CacheWrite: 999999, Rejected: true, Status: 400}, + } + // a call read from a session file has no request to jump to + logs := []sessions.Call{{Time: at.Add(4 * time.Minute), Agent: "dsh", Session: "s", Model: "d", Tokens: sessions.Tokens{CacheWrite: 5000000}}} + gateway := &rowChunk{} + for i, r := range recs { + r.Agent = AgentOf(r.Agent) + gateway.add(Row{Record: r}, "", int64(i), false) + } + local := &rowChunk{} + for i, c := range logs { + local.add(Row{Record: logRecord(c), Source: "log"}, "", int64(i), false) + } + rows, sum, agents, providers := ledgerWith(Period(All).Since(now), Filter{}, recs, logs) + all := Ledgered{rows, sum, agents, providers} + want := BigWrite{N: 108546, RouteID: 12, At: recs[1].Time, Model: "m"} + for name, page := range map[string]RequestPage{ + "streamed": buildRequestPage(All, Filter{}, 0, 100, gateway, []*rowChunk{local}), + "ledger": pageFromLedger(All, Filter{}, 0, 100, all), + } { + if page.Big.N != want.N || page.Big.RouteID != want.RouteID || page.Big.Model != want.Model { + t.Errorf("%s: largest write %+v, want %+v", name, page.Big, want) + } + } + // the filter narrows it to the rows it keeps + page := buildRequestPage(All, Filter{Query: "no such request"}, 0, 100, gateway, []*rowChunk{local}) + if page.Big != (BigWrite{}) { + t.Errorf("no rows kept, largest write %+v", page.Big) + } +} + +func TestInferredKindsShareThePurposeOfTheirKind(t *testing.T) { + for _, kind := range []string{KindAgentSummary, KindAutoMode} { + if PurposeOf(kind+InferredSuffix) != PurposeOf(kind) || PurposeOf(kind) != "kind:"+kind { + t.Errorf("%s: purposes %q, %q", kind, PurposeOf(kind), PurposeOf(kind+InferredSuffix)) + } + if purposeKinds[kind+InferredSuffix].Name != purposeKinds[kind].Name+" (inferred)" { + t.Errorf("%s: inferred name %q", kind, purposeKinds[kind+InferredSuffix].Name) + } + } +} diff --git a/internal/usage/heat_disk.go b/internal/usage/heat_disk.go index aff86c0f5..413cfe186 100644 --- a/internal/usage/heat_disk.go +++ b/internal/usage/heat_disk.go @@ -34,7 +34,7 @@ import ( // history again on its first start, the cold start's peak (#2278). Raise // it with any change to what a row counts as; TestSettledCountedAsVersioned // fails until it is raised. -const settledCountVersion = "2" +const settledCountVersion = "3" func heatDiskPath() string { return filepath.Join(filepath.Dir(sessions.CachePath()), "heat-v1.json") diff --git a/internal/usage/page_split.go b/internal/usage/page_split.go index 882c0cd84..38f1eb57d 100644 --- a/internal/usage/page_split.go +++ b/internal/usage/page_split.go @@ -218,7 +218,8 @@ func effortKeyOf(f Filter, k string) string { // addCells is the cells of a and of b, the later, as one part: a cell of // the same names, bits and bucket added up, in the order of their last. func addCells(a, b *chunkPart) *chunkPart { - out := &chunkPart{kept: a.kept + b.kept, first: a.first} + out := &chunkPart{kept: a.kept + b.kept, first: a.first, big: a.big} + out.big.merge(b.big) if a.speeds != nil || b.speeds != nil { out.speeds = speedRank{} out.speeds.merge(a.speeds) @@ -265,6 +266,7 @@ func (ps *pairedRows) cellsBefore(pass *cellPass, cut time.Time) *chunkPart { for _, c := range ps.all { part := pass.part(&before, &rows, c, &r) out.kept += part.kept + out.big.merge(part.big) if part.speeds != nil { if out.speeds == nil { out.speeds = speedRank{} @@ -336,6 +338,9 @@ type pageDiskEntry struct { Cells []pageDiskCell `json:"cells"` // Speeds are the model speed ranking's counts (speed_rank.go) Speeds speedRank `json:"speeds,omitempty"` + // Big is the largest cache write (BigWrite); settledCountVersion 3 + // keys the entries that hold one + Big BigWrite `json:"big,omitzero"` } // pageDiskPages bounds the pages the file holds, the last written or read @@ -369,7 +374,7 @@ func pageDiskRead(key string) (*chunkPart, int, bool) { // pageDiskPart is e's cells as one part. func pageDiskPart(e pageDiskEntry) *chunkPart { - part := &chunkPart{kept: e.Kept, cells: make([]pageCell, len(e.Cells)), speeds: e.Speeds} + part := &chunkPart{kept: e.Kept, cells: make([]pageCell, len(e.Cells)), speeds: e.Speeds, big: e.Big} if !e.First.IsZero() { part.first = e.First.In(time.Local) } @@ -386,7 +391,7 @@ func pageDiskPart(e pageDiskEntry) *chunkPart { // pageDiskWrite keeps part, a page's cells before cut from since, under // key with the pages written last, through a file renamed over the last. func pageDiskWrite(key string, cut, since time.Time, part *chunkPart) error { - e := pageDiskEntry{Key: key, Cut: cut, Since: since, At: time.Now(), Kept: part.kept, First: part.first, Cells: make([]pageDiskCell, len(part.cells)), Speeds: part.speeds} + e := pageDiskEntry{Key: key, Cut: cut, Since: since, At: time.Now(), Kept: part.kept, First: part.first, Cells: make([]pageDiskCell, len(part.cells)), Speeds: part.speeds, Big: part.big} for i := range part.cells { c := &part.cells[i] e.Cells[i] = pageDiskCell{ diff --git a/internal/usage/purpose.go b/internal/usage/purpose.go index 9993175d7..69836a4e8 100644 --- a/internal/usage/purpose.go +++ b/internal/usage/purpose.go @@ -36,9 +36,28 @@ var purposeKinds = func() map[string]PurposeKind { add("Model list", "model_list") // probelog.KindList add("MCP tool", KindMCP) // an MCP tool call (SourceMCP) add("Cache keep-alive", KindKeepalive) // a plugin's own ping (plugin_calls.go) + // Claude Code names neither of these requests, so the gateway tells them + // by their content: the *_inferred kinds. They share the purpose of the + // plain kind (a client's own marker, were one sent), and say in their + // name that magpie read it from the body, not that the client said so. + pair := func(name, kind string) { + out[kind] = PurposeKind{"kind:" + kind, name} + out[kind+InferredSuffix] = PurposeKind{"kind:" + kind, name + " (inferred)"} + } + pair("Progress summary", KindAgentSummary) // Claude Code's AgentSummary + pair("Auto mode check", KindAutoMode) // Claude Code's auto mode classifier return out }() +// KindAgentSummary and KindAutoMode are the kinds of Claude Code's +// sub-agent progress summary and its auto mode classifier; InferredSuffix +// follows one that was told by the request's content. +const ( + KindAgentSummary = "agent_summary" + KindAutoMode = "auto_mode_check" + InferredSuffix = "_inferred" +) + // PurposeKinds returns a copy of the catalog used to generate the UI's catalog. // Add aliases here, then run go generate ./internal/usage from the repo root. func PurposeKinds() map[string]PurposeKind { return maps.Clone(purposeKinds) } diff --git a/internal/usage/request_cells.go b/internal/usage/request_cells.go index bab43fe5b..84e2145cf 100644 --- a/internal/usage/request_cells.go +++ b/internal/usage/request_cells.go @@ -91,6 +91,9 @@ type chunkPart struct { // speeds are the counted requests of the rows the filter keeps, by // model (speed_rank.go) speeds speedRank + // big is the request of the rows the filter keeps that wrote the most + // to the cache (BigWrite) + big BigWrite // newest is the chunk's newest rows a page read of it (newest) newest atomic.Pointer[chunkNewest] } @@ -237,6 +240,7 @@ func (pass *cellPass) part(ps *pairedRows, rows *chunkRows, c *rowChunk, r *Row) part.speeds = speedRank{} } part.speeds.add(r) + part.big.add(r) } } }) diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index 61e53ff0d..f8bf741cf 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -67,6 +67,9 @@ type RequestPage struct { // Heat is the rows by day, as the chart's filter keeps them: only for // the heatmap's own period (HeatmapOf) Heat *Heatmap + // Big is the request that wrote the most to the cache, of the rows the + // filter keeps + Big BigWrite } type packedRow struct { @@ -2573,6 +2576,7 @@ func buildRequestBlocksIn(p Period, f Filter, offset, limit int, now time.Time, } for _, part := range parts { speeds.merge(part.speeds) + out.Big.merge(part.big) if !part.first.IsZero() && (first.IsZero() || part.first.Before(first)) { first = part.first } @@ -2810,6 +2814,7 @@ func pageFromLedgerAt(p Period, f Filter, offset, limit int, all Ledgered, now t for _, r := range l.Rows { if !r.IsRejected() && !r.IsProbe() { speeds.add(&r) + out.Big.add(&r) } } out.Speeds = speeds.result() diff --git a/internal/usageapi/usageapi.go b/internal/usageapi/usageapi.go index 2f4b09103..30a6986a0 100644 --- a/internal/usageapi/usageapi.go +++ b/internal/usageapi/usageapi.go @@ -303,6 +303,9 @@ type Ledger struct { Speeds []ModelSpeed `json:"speeds"` // SpeedMin is the fewest output tokens a request wrote to count in it SpeedMin int `json:"speed_min"` + // BigWrite: the request that wrote the most to the cache, of the rows + // the filter keeps + BigWrite usage.BigWrite `json:"big_write"` } // Share is a usage.Share with the name and logo the page shows it by. @@ -367,6 +370,7 @@ func LedgerPage(p usage.Period, f usage.Filter, offset, limit int) Ledger { out.Through, out.Direct, out.Reported = l.Through, l.Direct, l.Reported out.Bucket, out.Series = l.Bucket, l.Series out.Purposes = l.Purposes + out.BigWrite = l.Big out.Day = f.Day out.CallerKeys = inKeyOrder(callerGroups(usage.Summary{CallerKeys: l.CallerKeys})) callerLabels := map[string]string{}