diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index be5de042c..fbbe96db8 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -717,6 +717,15 @@ arguments are never kept, not even masked. `TestToolCallsAreReported` (imagemcp), `TestMCPCallRowsListedNotCounted` (usage) and `usage-ledger-mcp.test.cjs` cover it. +A request a provider plugin sends its vendor by itself (Devin's cache +keep-alive ping, plugins#592) never passes the gateway. The plugin +reports it through `input.magpie.usage` and `usage.pluginCall` writes it +as a row of agent `magpie` with the plugin's kind (`cache_keepalive`, +"Cache keep-alive" in `purposeKinds`). Unlike a probe it is counted: +priced and in every total (see +[provider-plugins.md](provider-plugins.md#a-request-a-plugin-sends-by-itself)). +`TestPluginKeepaliveIsCounted`. + ### Requests magpie sends on its own The provider editor's Test, Detect APIs and per-model detection, and a diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index d6ba5a623..7683dd54e 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -76,6 +76,14 @@ The user's values are kept in `settings.PluginOptions` by the plugin's own provi The provider's editor lists them under *Plugin options* (`pluginOptionsField` in [`app.js`](../../internal/gui/assets/app.js), the values from `/api/providers`' `plugins[].options[].on`), an Off/On each beside the plugin's label and description, put in as text, in the window's language (`optionWords`: its `labels`/`descriptions`/`confirms` by the language, then by its first part, so zh-TW reads zh, else the plain one). One with `confirm` asks it before it is turned on. Changes wait for Save, which posts each changed one before the provider. While an option that says `filtersModels` is on, as saved (the list was read with it), the Models field says so under the chips (`pluginFilterNote`): "Only some models are listed: the plugin option “…” is on.", with the option's label in the window's language. Off, or with no such option, nothing is said. +A plugin's package options, the second argument its function is called with (`options` in plugins.json), are a separate thing: numbers and words, not switches. The Plugins page's Installed row has the same *Options* JSON editor for them that a middleware or gateway plugin has (`optionsEditor` in [`plugins.js`](../../internal/gui/assets/plugins.js), `POST /api/plugins/options`, which restarts the host), shown for a plugin that is neither (a provider's, an agent's) when its package suggests options (package.json `magpie.options`, `/api/plugins`' `optionsExample`, now read for every plugin, not only a middleware's) or it has some set; never while it is off (plugins#592: Devin's `cacheKeepaliveInterval` and `cacheKeepaliveMaxPings`, beside its *Cache keep-alive* switch). Its Clear asks "Saved options will be removed…", for every plugin now, not a middleware's words. The Off/On switches above don't get number fields: that would be a new option type across the host, settings and the provider editor. `TestProviderPluginOptionsExample`, `plugin-provider-options.test.cjs`. + +## A request a plugin sends by itself + +A plugin can tell magpie of a request it sent its vendor on its own, outside any request the gateway handed its `fetch` (plugins#592: Devin's cache keep-alive pings, which re-send the last turn on a timer and were invisible). It calls `input.magpie.usage(provider, {kind, model, input?, output?, cacheRead?, cacheWrite?, status?, ms?, error?, account?})`. The host ([`host.js`](../../internal/plugin/host.js) `reportUsage`) throws a TypeError for a provider that isn't a string of 1–200 characters, a call that isn't a plain object, a `kind` that doesn't match `[a-z0-9_-]{1,40}` or an empty `model`; it makes each count a whole number from 0 (what isn't a finite number is 0; `status` at most 999), caps `error` at 500 characters, and takes `account` only when it is the provider's (`devin` or `devin#…`), else the account of the request in hand (`input.magpie.account(provider)`, `keyFor`), else the provider's id. A plugin reads `input.magpie.account(provider)` while its fetch runs to name, later, the account a timer's request belongs to. It is sent as an unasked `{event:"usage", provider, account, usage}` (`dispatch` in [`host.go`](../../internal/plugin/host.go), `plugin.OnUsage`). + +[`plugin_calls.go`](../../internal/usage/plugin_calls.go) registers the one listener and appends a row: agent `magpie`, the provider as magpie names it (`provider.PluginID`), the account's display name (`provider.PluginAccountUser`), the model as both asked and served, its kind, tokens, status, time and error. It is a counted row, as the routing classifier's are, not a probe's: it is priced and in the totals, since the user who turned the keep-alive on is to see what it costs. Its kind `cache_keepalive` is in the purpose catalog as *Cache keep-alive* (`purposeKinds`, `purposes.js`), so the request log names it and can filter by it. It carries no session, so the session views don't count it as a turn. A plugin written for an older host calls `input.magpie?.usage?.(…)`; an older plugin reports nothing, as before. The ping is never routed back through the gateway, which would re-shape the body and break the cache it keeps warm. `TestPluginReportsOwnUsage`, `TestPluginKeepaliveIsCounted`. + ## A model's load A plugin can say how busy each model is (axelburks on Discord: an in-house vendor queues requests to its busy models, and a load put in the model's name changed only when the list did). It calls `input.magpie.load(provider, {"": 0 and up | null})` whenever it likes, from its own timer, as usage data refreshes; magpie never asks. The host ([`host.js`](../../internal/plugin/host.js) `reportLoad`) throws a TypeError for a provider that isn't a string of 1–200 characters or a `loads` that isn't a plain object, clamps each finite number to 0–10000 (`LOAD_MOST`, `plugin.LoadMost`: past 100 is a vendor that queues, 200 twice what it serves at once, axelburks again; 10000 is a sanity cap), sends `null` as -1 (cleared), drops every other value and an id over 200 characters, takes at most 1000, and sends what is left as an unasked `{event:"load", provider, loads}` (`dispatch` in [`host.go`](../../internal/plugin/host.go)). It returns how many it took. diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index bcca9b0e8..99098c041 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -373,7 +373,7 @@ const I18N = { "This account or key will stop being used for requests. You will need to add it again to use it.": "此账户或密钥将不再用于请求。要再次使用,需要重新添加。", "Key weight": "密钥权重", "Account weight": "账号权重", - "Saved middleware options will be removed. The plugin will run with no options.": "已保存的中间件选项将被移除。插件将不带选项运行。", + "Saved options will be removed. The plugin will run with no options.": "已保存的选项将被移除。插件将不带选项运行。", "Main navigation": "主导航", "Gateway keys": "网关密钥", "Gateway key": "网关密钥", @@ -3663,6 +3663,7 @@ const I18N = { "Suggestions": "提示词建议", "Image description": "图片描述", "MCP tool": "MCP 工具", + "Cache keep-alive": "缓存保活", "Routing classifier": "路由分类器", "Connection check": "连接检查", "magpie's own": "magpie 自身", @@ -4750,7 +4751,7 @@ const I18N = { "This account or key will stop being used for requests. You will need to add it again to use it.": "此帳戶或金鑰將不再用於請求。要再次使用,需要重新新增。", "Key weight": "金鑰權重", "Account weight": "帳號權重", - "Saved middleware options will be removed. The plugin will run with no options.": "已儲存的中介軟體選項將被移除。外掛將不帶選項執行。", + "Saved options will be removed. The plugin will run with no options.": "已儲存的選項將被移除。外掛將不帶選項執行。", "Main navigation": "主導航", "Gateway keys": "閘道金鑰", "Gateway key": "閘道金鑰", @@ -8003,6 +8004,7 @@ const I18N = { "Suggestions": "提示詞建議", "Image description": "圖片描述", "MCP tool": "MCP 工具", + "Cache keep-alive": "快取保活", "Routing classifier": "路由分類器", "Connection check": "連線檢查", "magpie's own": "magpie 自身", @@ -12360,6 +12362,7 @@ const I18N = { "Suggestions": "提案", "Image description": "画像の説明", "MCP tool": "MCP ツール", + "Cache keep-alive": "キャッシュ保持", "Routing classifier": "ルーティング分類器", "Connection check": "接続チェック", "magpie's own": "magpie 自身", @@ -12825,7 +12828,7 @@ const I18N = { "This account or key will stop being used for requests. You will need to add it again to use it.": "このアカウントまたはキーはリクエストに使用されなくなります。再び使うには追加し直してください。", "Key weight": "キーの重み", "Account weight": "アカウントの重み", - "Saved middleware options will be removed. The plugin will run with no options.": "保存したミドルウェアのオプションが削除されます。プラグインはオプションなしで実行されます。", + "Saved options will be removed. The plugin will run with no options.": "保存したオプションが削除されます。プラグインはオプションなしで実行されます。", "Main navigation": "メインナビゲーション", // agents' advice after a change (NOTICES) "Ante reads its catalog at start-up — restart open ante sessions to use this.": "Ante は起動時にカタログを読み込みます。反映するには開いている ante セッションを再起動してください。", @@ -16726,6 +16729,7 @@ const I18N = { "Suggestions": "Vorschläge", "Image description": "Bildbeschreibung", "MCP tool": "MCP-Tool", + "Cache keep-alive": "Cache warm halten", "Routing classifier": "Routing-Klassifikator", "Connection check": "Verbindungstest", "magpie's own": "von magpie selbst", @@ -17181,7 +17185,7 @@ const I18N = { "This account or key will stop being used for requests. You will need to add it again to use it.": "Dieses Konto oder dieser Schlüssel wird nicht mehr für Anfragen verwendet. Um es erneut zu verwenden, müssen Sie es wieder hinzufügen.", "Key weight": "Schlüsselgewicht", "Account weight": "Kontogewicht", - "Saved middleware options will be removed. The plugin will run with no options.": "Die gespeicherten Middleware-Optionen werden entfernt. Das Plugin läuft ohne Optionen.", + "Saved options will be removed. The plugin will run with no options.": "Die gespeicherten Optionen werden entfernt. Das Plugin läuft ohne Optionen.", "Main navigation": "Hauptnavigation", // agents' advice after a change (NOTICES) "Ante reads its catalog at start-up — restart open ante sessions to use this.": "Ante liest seinen Katalog beim Start – offene ante-Sitzungen neu starten, damit es gilt.", diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index e728c18e8..4b42e1acf 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -1216,6 +1216,8 @@ const mw = e.middleware; const gw = e.gateway; const ag = e.agent; + // a provider's or agent's options (plugins#592) + const ownOpts = !e.isMiddleware && !e.isGateway && !!(e.options || e.optionsExample); if (mw || e.isMiddleware) nm.append(kindChip("mw")); if (gw || e.isGateway) nm.append(kindChip("mw", "Request hook")); if (ag || e.isAgent) nm.append(kindChip("ag")); @@ -1275,7 +1277,7 @@ if (e.page && !ask) who.append(pageLine(e.page)); if (e.panels?.length && !ask) who.append(panelsLine(e.panels, e.panelReads)); if (e.actions?.length && !ask) who.append(actionsLine(e.actions)); - if ((mw || e.isGateway) && !e.off && !ask && editing?.pkg === pkg) who.append(optionsEditor(e)); + if ((mw || e.isGateway || ownOpts) && !e.off && !ask && editing?.pkg === pkg) who.append(optionsEditor(e)); // the plugin's own picture (package.json's magpie.icon) before its // first provider's, which a plugin of several gives each its own (#1775) r.append(logo(l?.icon || l?.npm?.icon || e.icon || subs[0]?.icon || ag?.icon, false, e.middlewareOnly ? "mw" : e.inMagpieOnly && e.isAgent && !e.isMiddleware ? "ag" : e.inMagpieOnly && (e.page || e.panels?.length) && !e.isAgent && !e.isMiddleware ? "pg" : toolsOnly && !e.page && !mw && !ag ? "tl" : ""), who); @@ -1325,7 +1327,7 @@ r.append(val); return r; } - if ((e.isGateway || (mw && !mw.error)) && !e.off && editing?.pkg !== pkg) { + if ((e.isGateway || (mw && !mw.error) || ownOpts) && !e.off && editing?.pkg !== pkg) { const o = el("button", "text", t("Options")); o.title = e.options ? t("The options it runs with") : t("It runs with no options; its package suggests some"); o.disabled = !!b; @@ -1357,7 +1359,7 @@ return r; } - // optionsEditor is a middleware's options as JSON, in its row: what it + // optionsEditor is a plugin's options as JSON, in its row: what it // runs with, or what its package suggests when it has none. The draft is // kept in editing, so a redraw while typing doesn't lose it. function optionsEditor(e) { @@ -1396,7 +1398,7 @@ const clr = el("button", "text quiet", t("Clear")); clr.title = t("Runs it with no options"); clr.onclick = async () => { - if (!await confirmAction(t("Clear"), t("Saved middleware options will be removed. The plugin will run with no options."), t("Clear"))) return; + if (!await confirmAction(t("Clear"), t("Saved options will be removed. The plugin will run with no options."), t("Clear"))) return; editing = null; act(name(e.spec), "options", { spec: e.spec, options: null }, () => status(t("{name}'s options cleared", { name: shownName(e) }), "ok")); }; @@ -1407,9 +1409,6 @@ return box; } - // mwLine is a middleware's line in its plugin's row: its hooks, how many - // calls and how long each took, and the calls that failed (which went on - // as if it weren't there), or why it didn't load // clashGroups are a row's clashes, one per other plugin and side: a // plugin that signs in to two providers another one does too is one // line naming both, not a line each saying the same thing (#565) @@ -1426,11 +1425,9 @@ } // clashLine is the providers two installed plugins both sign in to, as - // the row of either says it: served here, or served by the other one. - // The other one goes by its name; when that is this row's own name too - // (the same plugin installed twice, from two places), by where it came - // from, since "CodeArts / OfficeAce also signs in to CodeArts" on the - // CodeArts / OfficeAce row read as the plugin naming itself (#565) + // either row says it. The other one goes by its name, or by where it + // came from when that is this row's name too (one plugin installed + // twice: it read as the plugin naming itself, #565) function clashLine(e, g, nameOfSpec) { const d = el("div", "sub pm-clash" + (g.here ? "" : " warn")); const own = shownName(e); @@ -1523,6 +1520,7 @@ return whereLine(actions, "menu", MENUS, (where) => t("Adds items to {where}, which open its page", { where })); } + // mwLine is a middleware's hooks, calls, time each and failures, or why it didn't load function mwLine(m) { const d = el("div", "sub pm-mw"); if (m.error) { diff --git a/internal/gui/assets/purposes.js b/internal/gui/assets/purposes.js index eb35dd60f..c98a4f76b 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"},"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"},"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"}}; diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go index 5030477ea..86a054b27 100644 --- a/internal/gui/plugins.go +++ b/internal/gui/plugins.go @@ -331,9 +331,11 @@ func pluginsState(ctx context.Context, w Windows) pluginsJSON { if file, only := plugin.Middleware(plugin.Target(e.Spec)); file != "" { j.IsMiddleware, j.MiddlewareOnly = true, only } - if j.IsMiddleware || j.IsGateway { - j.OptionsExample = plugin.OptionsExample(plugin.Target(e.Spec)) - } + // every plugin's, a provider plugin's too (Devin's keepalive, + // plugins#592): its row offers the same options editor. Not only + // one whose providers are known, as those are named in the + // background and the button would come and go with them + j.OptionsExample = plugin.OptionsExample(plugin.Target(e.Spec)) if file, _ := plugin.Agent(plugin.Target(e.Spec)); file != "" { j.IsAgent = true j.InMagpieOnly = plugin.InMagpieOnly(plugin.Target(e.Spec)) diff --git a/internal/gui/plugins_gateway_test.go b/internal/gui/plugins_gateway_test.go index e36668f63..bbe4779df 100644 --- a/internal/gui/plugins_gateway_test.go +++ b/internal/gui/plugins_gateway_test.go @@ -41,3 +41,33 @@ func TestGatewayPluginOptionsAndKind(t *testing.T) { t.Fatalf("disabled gateway: %+v", p) } } + +// A provider plugin's package options are its row's too (plugins#592: +// Devin's cacheKeepaliveInterval and cacheKeepaliveMaxPings), so the +// Installed tab can offer the options editor without plugins.json. +func TestProviderPluginOptionsExample(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + t.Setenv("MAGPIE_PLUGIN_MARKET", "off") + t.Cleanup(plugin.Settle) + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte(`{"name":"provider-fixture","main":"index.js","magpie":{"options":{"cacheKeepaliveInterval":285,"cacheKeepaliveMaxPings":6}}}`), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "index.js"), []byte(`export default async () => ({ auth: { provider: "fixture", methods: [] } })`), 0o644); err != nil { + t.Fatal(err) + } + if _, err := plugin.Add(t.Context(), dir); err != nil { + t.Fatal(err) + } + state := pluginsState(t.Context(), nil) + if len(state.Plugins) != 1 { + t.Fatalf("plugins: %+v", state) + } + p := state.Plugins[0] + if p.IsMiddleware || p.IsGateway || p.OptionsExample["cacheKeepaliveInterval"] != float64(285) || p.OptionsExample["cacheKeepaliveMaxPings"] != float64(6) { + t.Fatalf("provider plugin's options example: %+v", p) + } +} diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 92d38016e..c8c26bbea 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -12,6 +12,13 @@ checks that request hooks have no provider badge. `MAGPIE_GATEWAY_ASSETS` select an older asset directory for a failing regression comparison; user settings and live gateways are never accessed. +`plugin-provider-options.test.cjs` checks the same JSON options editor on a +provider plugin's Installed row (plugins#592: Devin's keep-alive interval and +pings): shown when its package suggests options, starting from them; absent +for a plugin with none and one switched off; Save and a confirmed Clear post +through the real page, in all five languages, at 980px and 420px, on Chromium +and WebKit. The API is faked. + `settings-proxy-auth.test.cjs` checks a proxy's optional username and password in Settings, in fields of their own for SOCKS5/SOCKS5h, HTTP, HTTPS and bare host:port proxies alike, using the real page with isolated diff --git a/internal/gui/tests/plugin-provider-options.test.cjs b/internal/gui/tests/plugin-provider-options.test.cjs new file mode 100644 index 000000000..b5703032e --- /dev/null +++ b/internal/gui/tests/plugin-provider-options.test.cjs @@ -0,0 +1,110 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A provider plugin's own options on the Installed tab (plugins#592): one +// whose package suggests options (Devin's cacheKeepaliveInterval and +// cacheKeepaliveMaxPings) or that has some set gets the same Options +// editor a middleware has, starting from its package's example; one with +// neither, or switched off, gets none. Clearing them asks first, in words +// that don't call them a middleware's. Every language; the API is 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 DEVIN = "npm:@magpie-community/opencode-devin-auth", PLAIN = "npm:@magpie-community/opencode-plain-auth", OFF = "npm:@magpie-community/opencode-off-auth"; +const example = { cacheKeepaliveInterval: 285, cacheKeepaliveMaxPings: 6 }; +const state = { bun: true, bunVersion: "1.3.0", plugins: [ + { spec: DEVIN, ownName: "Devin Auth", providers: ["Devin"], moved: ["devin"], named: true, optionsExample: example }, + { spec: PLAIN, ownName: "Plain Auth", providers: ["Plain"], moved: [], named: true }, + { spec: OFF, ownName: "Offco Auth", off: true, providers: ["Offco"], moved: [], named: true, optionsExample: example }, +] }; + +function server(lang, pluginState) { + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/gateway/trace") return json({ routes: [] }); + if (url.pathname === "/api/plugins/market" || url.pathname === "/api/plugins" || url.pathname === "/api/plugins/listings") return json(url.pathname === "/api/plugins" ? pluginState : url.pathname === "/api/plugins/listings" ? { listings: [] } : { listings: [], state: pluginState }); + 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, body: "" }); } + }; +} + +const W = { + en: { installed: "Installed", options: "Options", save: "Save", clear: "Clear", cancel: "Cancel", gone: /^Saved options will be removed\. The plugin will run with no options\.$/ }, + zh: { installed: "已安装", options: "选项", save: "保存", clear: "清空", cancel: "取消", gone: /^已保存的选项将被移除。插件将不带选项运行。$/ }, + "zh-TW": { installed: "已安裝", options: "選項", save: "儲存", clear: "清空", cancel: "取消", gone: /^已儲存的選項將被移除。外掛將不帶選項執行。$/ }, + ja: { installed: "インストール済み", options: "オプション", save: "保存", clear: "クリア", cancel: "キャンセル", gone: /^保存したオプションが削除されます。プラグインはオプションなしで実行されます。$/ }, + de: { installed: "Installiert", options: "Optionen", save: "Speichern", clear: "Leeren", cancel: "Abbrechen", gone: /^Die gespeicherten Optionen werden entfernt\. Das Plugin läuft ohne Optionen\.$/ }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a provider plugin's options in its row", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const [lang, w] of Object.entries(W)) { + await t.test(lang, async () => { + for (const width of [980, 420]) { + const page = await (await browser.newContext({ viewport: { width, height: 820 } })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posted = []; + page.on("pageerror", (e) => errors.push(e.message)); + const pluginState = structuredClone(state); + await page.route("**/*", server(lang, pluginState)); + await page.route("**/api/plugins/options", (r) => { + const body = r.request().postDataJSON(); + posted.push(body); + pluginState.plugins[0].options = body.options ?? undefined; + return r.fulfill({ json: pluginState }); + }); + await page.goto("http://magpie.test/?view=plugins"); + const view = page.locator("#view-plugins"); + await page.locator(":is(.lib-tabs .opt, .nav-s):visible", { hasText: w.installed }).click(); + const names = { [DEVIN]: "Devin Auth", [PLAIN]: "Plain Auth", [OFF]: "Offco Auth" }; + const row = (spec) => view.locator(".pm-row").filter({ has: page.locator(".name", { hasText: names[spec] }) }); + await row(DEVIN).waitFor(); + await row(PLAIN).waitFor(); + assert.equal(await row(PLAIN).getByRole("button", { name: w.options, exact: true }).count(), 0, "no Options on a plugin that has none"); + assert.equal(await row(OFF).getByRole("button", { name: w.options, exact: true }).count(), 0, "no Options on one switched off"); + const devin = row(DEVIN); + await devin.getByRole("button", { name: w.options, exact: true }).click(); + const ta = devin.locator(".pm-opts textarea"); + await ta.waitFor(); + assert.deepEqual(JSON.parse(await ta.inputValue()), example); + const box = await ta.boundingBox(); + assert.ok(box && box.x >= 0 && box.x + box.width <= width, `the editor fits at ${width}px: ${JSON.stringify(box)}`); + assert.equal(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), true, "no sideways scroll"); + await ta.fill('{"cacheKeepaliveInterval": 240, "cacheKeepaliveMaxPings": 10}'); + await devin.locator(".pm-opts").getByRole("button", { name: w.save, exact: true }).click(); + await devin.locator(".pm-opts").waitFor({ state: "detached" }); + assert.deepEqual(posted, [{ spec: DEVIN, options: { cacheKeepaliveInterval: 240, cacheKeepaliveMaxPings: 10 } }]); + await devin.getByRole("button", { name: w.options, exact: true }).click(); + assert.deepEqual(JSON.parse(await ta.inputValue()), { cacheKeepaliveInterval: 240, cacheKeepaliveMaxPings: 10 }); + await devin.getByRole("button", { name: w.clear, exact: true }).click(); + const confirm = page.getByRole("alertdialog"); + await confirm.waitFor(); + assert.match((await confirm.locator("#actionConfirmMessage").textContent()).trim(), w.gone); + await confirm.getByRole("button", { name: w.cancel, exact: true }).click(); + assert.equal(posted.length, 1, "Cancel keeps the saved options"); + await devin.getByRole("button", { name: w.clear, exact: true }).click(); + await confirm.locator("button").last().click(); + await devin.locator(".pm-opts").waitFor({ state: "detached" }); + assert.deepEqual(posted[1], { spec: DEVIN, options: null }); + assert.equal(await view.locator("select").count(), 0); + assert.deepEqual(errors, []); + await page.context().close(); + } + }); + } + }); +} diff --git a/internal/plugin/host.go b/internal/plugin/host.go index 6aec43968..d20ee5c3f 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -66,6 +66,27 @@ type message struct { // Loads is a "load" event's models and how busy each is, a percent; // -1 clears one (magpie.load in host.js) Loads map[string]float64 `json:"loads"` + // Usage is a "usage" event's request, one the plugin sent its vendor + // on its own (magpie.usage in host.js) + Usage *OwnCall `json:"usage"` +} + +// OwnCall is a request a plugin sent its vendor on its own, outside any +// request magpie handed it, as it reported it (magpie.usage in host.js): +// Devin's cache keepalive ping (plugins#592). Kind says what it was for +// ("cache_keepalive"), Model is the model's id as magpie handed it to the +// plugin, Input the prompt's tokens without the cache's, Status the +// vendor's (0 for none) and Millis how long it took. +type OwnCall struct { + Kind string `json:"kind"` + Model string `json:"model"` + Input int `json:"input"` + Output int `json:"output"` + CacheRead int `json:"cacheRead"` + CacheWrite int `json:"cacheWrite"` + Status int `json:"status"` + Millis int64 `json:"ms"` + Error string `json:"error"` } type callState uint8 @@ -621,6 +642,20 @@ func OnSignIn(f func(provider, account, said string)) { onSignInMu.Unlock() } +var ( + onUsageMu sync.Mutex + onUsage func(provider, account string, u OwnCall) +) + +// OnUsage registers f to be told of each request a plugin reported it +// sent on its own (OwnCall): its provider id and the account key it was +// sent for. f is told in the background. +func OnUsage(f func(provider, account string, u OwnCall)) { + onUsageMu.Lock() + onUsage = f + onUsageMu.Unlock() +} + var ( onListedMu sync.Mutex onListed []func() @@ -1183,6 +1218,14 @@ func (h *host) dispatch(m message) { } case "load": noteLoads(m.Provider, m.Loads, time.Now()) + case "usage": + onUsageMu.Lock() + f := onUsage + onUsageMu.Unlock() + if f != nil && m.Usage != nil && m.Provider != "" { + u := *m.Usage + tell(func() { f(m.Provider, m.Account, u) }) + } case "toast": log.Printf("plugin: %s %s", m.Title, m.Message) case "log": diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 8085a2612..fce3280ef 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -1264,7 +1264,7 @@ async function loadPlugins(list) { // magpie's own (OpenCode has none): the plugin's options as the user // set them in magpie, read when wanted, so a change reaches the // plugin without a restart (#2038) - magpie: { option: optionValue, options: optionValues, load: reportLoad }, + magpie: { option: optionValue, options: optionValues, load: reportLoad, usage: reportUsage, account: keyFor }, } // pi's packages and extensions are loaded as pi loads them (pi.js) let pi @@ -1983,6 +1983,37 @@ function reportLoad(provider, loads) { return n } +// reportUsage is magpie.usage(provider, call): a request a plugin sent its +// vendor on its own, outside any request magpie handed it (Devin's cache +// keepalive ping, plugins#592), for the request log and the usage totals +// to list and count. call is {kind, model, input?, output?, cacheRead?, +// cacheWrite?, status?, ms?, error?, account?}: kind says what the +// request was for ([a-z0-9_-], 1–40: "cache_keepalive"), model the +// model's id as magpie handed it to the plugin; the tokens are whole +// numbers from 0 (input without the cache's), status the vendor's (0 for +// none), ms how long it took. account is the account the request was +// sent for, as magpie.account(provider) named it while a request of +// magpie's was in the plugin's hands; without it, the account of the +// request being served now, else the provider's first. It returns true +// when the call was sent on. +const USAGE_KIND = /^[a-z0-9_-]{1,40}$/ +function reportUsage(provider, call) { + if (typeof provider !== "string" || !provider || provider.length > 200) throw new TypeError("magpie.usage: provider must be a provider id") + if (!call || typeof call !== "object" || Array.isArray(call)) throw new TypeError("magpie.usage: call must be an object") + if (typeof call.kind !== "string" || !USAGE_KIND.test(call.kind)) throw new TypeError("magpie.usage: kind must be 1–40 of [a-z0-9_-]") + const model = shown(call.model, 200) + if (!model) throw new TypeError("magpie.usage: model must be the model's id") + const n = (v, most = 1e12) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.min(Math.floor(v), most) : 0) + const account = typeof call.account === "string" && call.account && providerOf(call.account) === provider ? call.account : keyFor(provider) + send({ + event: "usage", + provider, + account, + usage: { kind: call.kind, model, input: n(call.input), output: n(call.output), cacheRead: n(call.cacheRead), cacheWrite: n(call.cacheWrite), status: n(call.status, 999), ms: n(call.ms), error: shown(call.error, 500) }, + }) + return true +} + // optionValue is one of provider's options as it stands; false for a key // its plugin doesn't declare. function optionValue(provider, key) { diff --git a/internal/plugin/usage_report_test.go b/internal/plugin/usage_report_test.go new file mode 100644 index 000000000..66f6b4e49 --- /dev/null +++ b/internal/plugin/usage_report_test.go @@ -0,0 +1,99 @@ +package plugin + +import ( + "context" + "os" + "path/filepath" + "sync" + "testing" + "time" +) + +// A plugin reports a request it sent its vendor on its own (Devin's cache +// keepalive ping, plugins#592) through input.magpie.usage, from its own +// timer: magpie is told its provider, the account it names (one of the +// provider's; else the request's in hand, else the provider's own id) and +// the call, its tokens whole numbers from 0. A call with no provider, no +// kind of [a-z0-9_-] or no model throws, and nothing is told of it. +func TestPluginReportsOwnUsage(t *testing.T) { + sandbox(t) + type told struct { + provider, account string + u OwnCall + } + var mu sync.Mutex + var got []told + OnUsage(func(provider, account string, u OwnCall) { + mu.Lock() + got = append(got, told{provider, account, u}) + mu.Unlock() + }) + t.Cleanup(func() { OnUsage(nil) }) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + dir := filepath.Join(t.TempDir(), "usageco") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + src := `export default async (input) => { + let threw = 0 + for (const bad of [[5, { kind: "x", model: "m" }], ["usageco", null], ["usageco", [1]], ["usageco", { model: "m" }], ["usageco", { kind: "Bad Kind", model: "m" }], ["usageco", { kind: "cache_keepalive" }], ["", { kind: "x", model: "m" }]]) { + try { input.magpie.usage(...bad) } catch (e) { if (e instanceof TypeError) threw++ } + } + setTimeout(() => { + input.magpie.usage("usageco", { kind: "cache_keepalive", model: " sonnet ", input: 3.7, output: 1, cacheRead: 10984, cacheWrite: -5, status: 200, ms: 812, account: "usageco#ab" }) + input.magpie.usage("usageco", { kind: "cache_keepalive", model: "sonnet", input: NaN, output: "1", cacheRead: Infinity, status: 0, error: "fetch failed", account: "other#cd" }) + input.magpie.usage("usageco", { kind: "threw", model: String(threw) }) + }, 50) + return {} +} +` + if err := os.WriteFile(filepath.Join(dir, "index.js"), []byte(src), 0o644); err != nil { + t.Fatal(err) + } + if _, err := Add(ctx, filepath.Join(dir, "index.js")); err != nil { + t.Fatal(err) + } + if ls, err := Plugins(ctx); err != nil || len(ls) != 1 || ls[0].Error != "" { + t.Fatalf("Plugins = %+v, %v", ls, err) + } + for { + mu.Lock() + n := len(got) + mu.Unlock() + if n >= 3 { + break + } + if ctx.Err() != nil { + t.Fatalf("the plugin's calls never arrived: %+v", got) + } + time.Sleep(10 * time.Millisecond) + } + Told() + mu.Lock() + defer mu.Unlock() + if len(got) != 3 { + t.Fatalf("told %d calls, want 3: %+v", len(got), got) + } + byModel := map[string]told{} + for _, x := range got { + if x.u.Kind == "threw" { + if x.u.Model != "7" { + t.Errorf("%s calls threw, want 7", x.u.Model) + } + continue + } + if x.u.Error == "" { + byModel["ok"] = x + } else { + byModel["failed"] = x + } + } + ok, failed := byModel["ok"], byModel["failed"] + if want := (told{"usageco", "usageco#ab", OwnCall{Kind: "cache_keepalive", Model: "sonnet", Input: 3, Output: 1, CacheRead: 10984, Status: 200, Millis: 812}}); ok != want { + t.Errorf("ping = %+v, want %+v", ok, want) + } + if want := (told{"usageco", "usageco", OwnCall{Kind: "cache_keepalive", Model: "sonnet", Error: "fetch failed"}}); failed != want { + t.Errorf("failed ping = %+v, want %+v", failed, want) + } +} diff --git a/internal/provider/migrate_side.go b/internal/provider/migrate_side.go index c65e51c96..39e85d415 100644 --- a/internal/provider/migrate_side.go +++ b/internal/provider/migrate_side.go @@ -17,7 +17,7 @@ import ( func init() { movers["devin"] = &mover{ pkg: "@magpie-community/opencode-devin-auth", - min: "0.1.30", // 0.1.30: an opt-in cache keepalive, "Keep the cache warm" (off by default): after a reply that used the cache, the same request goes again every 285 s with "continue" and max_tokens 1, as the devin CLI does, until the conversation's next request, a 401, 402 or 429, two misses or 6 pings (plugins #592, zelong77); 0.1.29: a failed tool result on the Messages path says "Error: " first, as on chat completions; 0.1.28: Devin's Claude models are asked on Anthropic's Messages API, each block of the client's its own prompt with Devin's cache mark where the client put cache_control, so a grown history is read from the cache (plugins #566, zelong77); 0.1.27: SWE-2 asked with no effort goes as a free variant, never a paid -lightning one Devin lists first, and as SNAPSHOT's swe-2-high when the account's list leaves the family out, not the bare family id; a model list Devin won't give is logged and shown in usage ("Free models: unknown"), not swallowed (zws13579 on Discord, plugins #533); 0.1.26: a usage read Devin answers 401 marks the account signed out, so its rows offer Sign in again, and a clean read takes the mark off (blue12345655 on Discord); 0.1.25: an anyOf beside a type below a tool's root (what the gateway writes for a Gemini model) goes to Devin's Gemini models merged or as a oneOf, so Kimi Code's Read no longer 400s (plugins #458); 0.1.24: the CLI's sign-in keeps its "cli" mark as the string OpenCode stores, so OpenCode 1 keeps the account (plugins #396); 0.1.23: a reply with only usage or metadata is refused before the stream starts, not passed on as an empty success (plugins #297); 0.1.22: organisations under one email are kept apart, each with its own quota (plugins #296); 0.1.21: a chat request past 8 KiB goes as a gzipped Connect frame, as the devin CLI sends it, where an uncompressed large one could be refused 413 (plugins #275); 0.1.20: a tool result's images go to Devin on the tool message that answers the call, as the built-in sent them; 0.1.19: Devin answers in JSON when the request asks for it (response_format into the instructions, as the built-in); 0.1.18: a tool whose parameters have a root anyOf, oneOf or allOf goes as a plain object (#1196), a branch that is a union itself folded too (#1271); a turn's parallel calls split over two assistant messages keep their results (#1275); a temperature or top_p of 0 goes as 1e-6, which Devin takes (plugins #50); a call id with ":" or "#" goes to the agent as one Claude Code takes, and back to Devin as it was (#1304); a week used up, its share left out of GetUserStatus, is 100% and holds the account until its reset (面条); SWE-2, which Devin's quota doesn't count (its Free cost tier), is left out of the day and week and listed free, so a used-up quota no longer holds it (太陽と向日葵); a tool schema with a list type, an array with no items, or properties or an enum with no type goes to a Gemini model in a shape it takes, not "There is an issue with this request" (7eleven); each model carries the price Devin lists for it, and SWE-2 stays free beside the -lightning variants Devin now files under it (太陽と向日葵, Usage showed no cost) + min: "0.1.31", // 0.1.31: each keepalive ping is reported through magpie.usage (a Cache keep-alive call on the conversation's model and account, with its tokens), and package.json gives the interval and ping count's defaults to the Plugins › Options editor (plugins #592, zelong77); 0.1.30: an opt-in cache keepalive, "Keep the cache warm" (off by default): after a reply that used the cache, the same request goes again every 285 s with "continue" and max_tokens 1, as the devin CLI does, until the conversation's next request, a 401, 402 or 429, two misses or 6 pings (plugins #592, zelong77); 0.1.29: a failed tool result on the Messages path says "Error: " first, as on chat completions; 0.1.28: Devin's Claude models are asked on Anthropic's Messages API, each block of the client's its own prompt with Devin's cache mark where the client put cache_control, so a grown history is read from the cache (plugins #566, zelong77); 0.1.27: SWE-2 asked with no effort goes as a free variant, never a paid -lightning one Devin lists first, and as SNAPSHOT's swe-2-high when the account's list leaves the family out, not the bare family id; a model list Devin won't give is logged and shown in usage ("Free models: unknown"), not swallowed (zws13579 on Discord, plugins #533); 0.1.26: a usage read Devin answers 401 marks the account signed out, so its rows offer Sign in again, and a clean read takes the mark off (blue12345655 on Discord); 0.1.25: an anyOf beside a type below a tool's root (what the gateway writes for a Gemini model) goes to Devin's Gemini models merged or as a oneOf, so Kimi Code's Read no longer 400s (plugins #458); 0.1.24: the CLI's sign-in keeps its "cli" mark as the string OpenCode stores, so OpenCode 1 keeps the account (plugins #396); 0.1.23: a reply with only usage or metadata is refused before the stream starts, not passed on as an empty success (plugins #297); 0.1.22: organisations under one email are kept apart, each with its own quota (plugins #296); 0.1.21: a chat request past 8 KiB goes as a gzipped Connect frame, as the devin CLI sends it, where an uncompressed large one could be refused 413 (plugins #275); 0.1.20: a tool result's images go to Devin on the tool message that answers the call, as the built-in sent them; 0.1.19: Devin answers in JSON when the request asks for it (response_format into the instructions, as the built-in); 0.1.18: a tool whose parameters have a root anyOf, oneOf or allOf goes as a plain object (#1196), a branch that is a union itself folded too (#1271); a turn's parallel calls split over two assistant messages keep their results (#1275); a temperature or top_p of 0 goes as 1e-6, which Devin takes (plugins #50); a call id with ":" or "#" goes to the agent as one Claude Code takes, and back to Devin as it was (#1304); a week used up, its share left out of GetUserStatus, is 100% and holds the account until its reset (面条); SWE-2, which Devin's quota doesn't count (its Free cost tier), is left out of the day and week and listed free, so a used-up quota no longer holds it (太陽と向日葵); a tool schema with a list type, an array with no items, or properties or an enum with no type goes to a Gemini model in a shape it takes, not "There is an issue with this request" (7eleven); each model carries the price Devin lists for it, and SWE-2 stays free beside the -lightning variants Devin now files under it (太陽と向日葵, Usage showed no cost) agents: []string{"devin"}, out: func() ([]Moving, error) { var out []Moving diff --git a/internal/provider/plugin_accounts.go b/internal/provider/plugin_accounts.go index 2065b21ad..92cd32f6d 100644 --- a/internal/provider/plugin_accounts.go +++ b/internal/provider/plugin_accounts.go @@ -420,6 +420,18 @@ func keepPluginPlan(pp plugin.Provider, key, plan string) { } } +// PluginAccountUser is who the plugin id's account at key is (an email, a +// login), as the Routing trace and the request log name it: "" when no +// account is kept there. +func PluginAccountUser(id, key string) string { + for _, l := range readLogins() { + if l.Agent == "plugin:"+id && l.Home == key { + return l.User + } + } + return "" +} + // notePluginLapse marks the account at key lapsed when its vendor refused // a request (401), as a built-in's refused sign-in is marked, and clears // the mark once one goes through. diff --git a/internal/usage/plugin_calls.go b/internal/usage/plugin_calls.go new file mode 100644 index 000000000..efcba203f --- /dev/null +++ b/internal/usage/plugin_calls.go @@ -0,0 +1,28 @@ +package usage + +import ( + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" +) + +// KindKeepalive is the Kind of a cache keepalive ping a plugin sent on its +// own (Devin's, plugins#592): the conversation's request sent again with +// max_tokens 1 so the vendor's prompt cache outlives its 5 minutes. +const KindKeepalive = "cache_keepalive" + +// pluginCall is the row of a request a plugin reported it sent its vendor +// on its own (plugin.OwnCall, magpie.usage in host.js): magpie's, as the +// routing classifier's are, by the plugin's provider and the account it +// was sent for, labelled by its Kind. It is counted as the gateway's +// calls are, in the totals and the cost: such a ping is billed (a cache +// read of the whole context), and the user who turned it on is to see +// what it costs (zelong77, plugins#592). +func pluginCall(id, account string, u plugin.OwnCall) Record { + return Record{Agent: "magpie", Provider: provider.PluginID(id), ProviderAccount: provider.PluginAccountUser(id, account), + Model: u.Model, Requested: u.Model, Kind: u.Kind, Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, + Status: u.Status, Millis: u.Millis, Error: clipProbeError(u.Error)} +} + +func init() { + plugin.OnUsage(func(id, account string, u plugin.OwnCall) { Append(pluginCall(id, account, u)) }) +} diff --git a/internal/usage/plugin_calls_test.go b/internal/usage/plugin_calls_test.go new file mode 100644 index 000000000..9c189c5b7 --- /dev/null +++ b/internal/usage/plugin_calls_test.go @@ -0,0 +1,38 @@ +package usage + +import ( + "os" + "testing" + "time" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/plugin" +) + +// A cache keepalive ping the Devin plugin sent on its own (plugins#592) is +// a row of magpie's on the request log, labelled by its kind, and counted: +// its cache read is in the totals and priced as the plugin's turns are +// (here at the model's maker's list price), as the user who turned the +// keepalive on is to see what it costs (zelong77). +func TestPluginKeepaliveIsCounted(t *testing.T) { + pageHome(t) + os.WriteFile(catalog.CachePath(), []byte(`{"anthropic":{"id":"anthropic","models":{"claude-sonnet-4-5":{"id":"claude-sonnet-4-5","cost":{"input":3,"output":15,"cache_read":0.3,"cache_write":3.75}}}}}`), 0600) + now := holdClock(t, time.Date(2026, 11, 1, 12, 0, 0, 0, time.Local)) + r := pluginCall("devin", "devin#ab", plugin.OwnCall{Kind: KindKeepalive, Model: "claude-sonnet-4-5", Input: 3, Output: 1, CacheRead: 10984, Status: 200, Millis: 812}) + r.Time = Today.Since(now).Add(time.Second) + Append(r) + Append(Record{Time: r.Time.Add(time.Second), Agent: "claude-code", Provider: "devin", Model: "claude-sonnet-4-5", Input: 5, Output: 9, CacheWrite: 10984, Status: 200}) + p := QueryPage(Today, Filter{Purpose: "kind:" + KindKeepalive}, 0, 10) + if p.Total != 1 || len(p.Rows) != 1 || p.Sum.Calls != 1 || p.Sum.CacheRead != 10984 || p.Sum.Input != 3 || p.Sum.Output != 1 || p.Sum.Cost <= 0 { + t.Fatalf("keepalive page = %+v", p) + } + if row := p.Rows[0]; row.Kind != KindKeepalive || row.Agent != "magpie" || row.Provider != "devin" || row.Model != "claude-sonnet-4-5" || row.Failed() || row.IsProbe() { + t.Fatalf("keepalive row = %+v", row) + } + if all := QueryPage(Today, Filter{}, 0, 10); all.Sum.Calls != 2 || all.Sum.CacheRead != 10984 { + t.Fatalf("all calls = %+v, want the ping counted beside the turn", all.Sum) + } + if k := PurposeKinds()[KindKeepalive]; k.Name != "Cache keep-alive" || k.Purpose != "kind:"+KindKeepalive { + t.Fatalf("keepalive purpose = %+v", k) + } +} diff --git a/internal/usage/purpose.go b/internal/usage/purpose.go index 8df55280c..9993175d7 100644 --- a/internal/usage/purpose.go +++ b/internal/usage/purpose.go @@ -35,6 +35,7 @@ var purposeKinds = func() map[string]PurposeKind { add("Detect APIs", "api_detect") // probelog.KindDetect 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) return out }()