usage: a client the user counts as an agent is counted as it on Usage and Sessions (#1958, NorethSea)
NorethSea's bridge (hermes-codex-thread-bridge) starts Codex's
app-server under a User-Agent of its own, so its calls were a row
apart from Codex on Usage, and its threads weren't Codex's in Sessions.
Rather than learn one bridge's name, the user says which agent a client
counts as.
- settings: clientAgents, client name (lowercased) -> agent id.
ClientAgentsNow reads just that field through filememo, so a pass over
the ledger costs a stat.
- usage: ReportedAs(ua) is AgentOf, then the user's mapping. It is used
for what is reported only: the summary, the agents list and filters,
request rows and pages, priced blocks, direct, Vias and gateway
sessions. The gateway's routing, keys and caps still go by AgentOf,
the client's own name. The mapping is read once per ledger pass
(readLogSnapshot) and is part of the keys of the summary price cache,
the vias cache and the request page cache, so a change redraws the
history already counted. A request row keeps the client's own name in
a new "client" field, shown as "Client" in its details.
- gui: POST /api/usage/arrange takes {count:{client,as}}. It refuses a
client magpie already knows as an agent, "other" or magpie's own, and
an "as" that isn't a known agent or is magpie. as "" counts it on its
own again. /api/settings keeps the mapping it doesn't send. On the
Usage page an unknown client's "…" offers "Count as an agent…" (a
picker of the known agents), the agent's row says "with <client>",
and the agent's "…" offers "Count <client> on its own". Strings are
in all 5 languages.
Run:
- go test -count=1 ./internal/usage ./internal/settings ./internal/gui: ok.
- TestClientCountedAsAgent goes red with reportedAs broken, and with the
mapping left out of the vias key or the request page key. With the
summary key alone left out it stays green, because the settings stat
already moves it.
- TestUsageArrangeCountClient and TestSettingsSaveKeepsWhatItDoesNotSend
(ClientAgents added) pass.
- Playwright usage-count-client.test.cjs (new) and usage-agents-hide
(its menu now has two items for an unknown client) pass in Chromium
and WebKit, in all 5 languages, at 1100 and 420: 54/54. With
countable() forced false, the new test goes red.
- gofmt -l is clean. go vet is clean for darwin, linux -tags nogui and
windows.
Not tried: a real hermes bridge (the records' UA is from the issue), and
the Client line in a request's details has no GUI test.
This commit is contained in:
+44
-2
@@ -46,6 +46,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/update"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// cliBehind is the terminal's magpie command when it's a copied file rather
|
||||
@@ -1177,6 +1178,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
in.PanelUsageHidden = cur.PanelUsageHidden
|
||||
// and the clients the Usage page's Agents list leaves out, set there
|
||||
in.UsageAgentsHidden = cur.UsageAgentsHidden
|
||||
// and the clients it counts as agents, set there too (#1958)
|
||||
in.ClientAgents = cur.ClientAgents
|
||||
// how agents' lists name models, set on its own for the agents to be told
|
||||
in.PlainNames, in.PlainOwnNames = cur.PlainNames, cur.PlainOwnNames
|
||||
in.BareModelIDs = cur.BareModelIDs // set on its own (bare-ids below)
|
||||
@@ -1772,19 +1775,30 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
writeJSON(rw, settingsState())
|
||||
})
|
||||
// the Usage page's order of its cards, which the tray panel's Allowances
|
||||
// tab follows, what that tab leaves out, and the clients the page's
|
||||
// Agents list leaves out, in magpie's settings; one not sent stays as it is
|
||||
// tab follows, what that tab leaves out, the clients the page's Agents
|
||||
// list leaves out, and a client it counts as one of the agents (Count,
|
||||
// #1958; As "" counts it on its own again), in magpie's settings; one
|
||||
// not sent stays as it is
|
||||
mux.HandleFunc("POST /api/usage/arrange", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Order *[]string
|
||||
PanelHidden *[]string
|
||||
AgentsHidden *[]string
|
||||
Count *struct{ Client, As string }
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
s := settings.Load()
|
||||
if in.Count != nil {
|
||||
m, err := countClient(s.ClientAgents, in.Count.Client, in.Count.As)
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
s.ClientAgents = m
|
||||
}
|
||||
if in.Order != nil {
|
||||
s.UsageOrder = *in.Order
|
||||
}
|
||||
@@ -2261,3 +2275,31 @@ func editRedactRule(rules []redact.Rule, at int, was, to redact.Rule) ([]redact.
|
||||
next[at] = tidy[0]
|
||||
return next, nil
|
||||
}
|
||||
|
||||
// countClient is the user's ClientAgents with client counted as the agent
|
||||
// as (#1958), or on its own again when as is "". Only a client magpie
|
||||
// doesn't know is counted as another, and only as an agent it knows: an
|
||||
// agent counted as another would be lost from its own row, and magpie's
|
||||
// own calls are kept apart from the agents' (#1839).
|
||||
func countClient(m map[string]string, client, as string) (map[string]string, error) {
|
||||
client, as = strings.TrimSpace(client), strings.TrimSpace(as)
|
||||
if client == "" {
|
||||
return nil, fmt.Errorf("no client to count")
|
||||
}
|
||||
out := maps.Clone(m)
|
||||
if out == nil {
|
||||
out = map[string]string{}
|
||||
}
|
||||
if as == "" {
|
||||
delete(out, strings.ToLower(client))
|
||||
return out, nil
|
||||
}
|
||||
if usage.IsAgent(client) || client == "other" || usage.AgentOf(client) == "magpie" || strings.HasPrefix(strings.ToLower(client), "magpie") {
|
||||
return nil, fmt.Errorf("%s is counted on its own", client)
|
||||
}
|
||||
if !usage.IsAgent(as) || as == "magpie" {
|
||||
return nil, fmt.Errorf("%s is not an agent magpie knows", as)
|
||||
}
|
||||
out[strings.ToLower(client)] = as
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -17593,12 +17593,24 @@ function renderUsage() {
|
||||
b.setAttribute("aria-haspopup", "menu");
|
||||
b.setAttribute("aria-label", t("Actions for {name}", { name: g.name || g.id }));
|
||||
b.append(svg(DOTS, 14, 2.2));
|
||||
// a client magpie doesn't know can be counted as one of the agents
|
||||
// it does (#1958, NorethSea): a bridge that starts Codex under a name
|
||||
// of its own; the agent counting one has it put back on its own
|
||||
const counted = Object.entries(state.settings?.clientAgents || {}).filter(([, as]) => as === g.id).map(([c]) => c);
|
||||
const menu = () => {
|
||||
const again = agentMenu?.anchor === b;
|
||||
closeAgentMenu();
|
||||
if (again) return;
|
||||
openRowMenu(b, [{ name: "Hide from this list", icon: EYE_OFF, run: () => hideUsageAgent(g.id, true) }]);
|
||||
openRowMenu(b, [
|
||||
...(countable(g.id) ? [{ name: "Count as an agent…", icon: COUNT_AS, run: () => pickCountAs(b, g) }] : []),
|
||||
...counted.map((c) => ({ name: t("Count {client} on its own", { client: c }), icon: OUT, run: () => countClientAs(c, "") })),
|
||||
{ name: "Hide from this list", icon: EYE_OFF, sep: countable(g.id) || counted.length > 0, run: () => hideUsageAgent(g.id, true) },
|
||||
]);
|
||||
};
|
||||
if (counted.length) {
|
||||
const sub = r.querySelector(".who .sub");
|
||||
sub.textContent = t("with {clients}", { clients: counted.join(", ") }) + " · " + sub.textContent;
|
||||
}
|
||||
b.onclick = (e) => { e.stopPropagation(); menu(); };
|
||||
r.oncontextmenu = (e) => { e.preventDefault(); menu(); };
|
||||
r.querySelector(".share").after(b);
|
||||
@@ -17628,6 +17640,33 @@ function renderUsage() {
|
||||
if (quotas && (u.accounts?.some((g) => g.own?.calls) || $("#subscriptionUsage .quota-own"))) renderQuotas();
|
||||
}
|
||||
|
||||
// countable is whether the Usage page's Agents list offers to count a
|
||||
// client as an agent: one magpie doesn't know, not magpie's own (#1839)
|
||||
// nor the calls that named no client.
|
||||
const COUNT_AS = "M3 3v3.5A3.5 3.5 0 0 0 6.5 10H13M10 7l3 3-3 3";
|
||||
function countable(id) {
|
||||
return !!id && id !== "other" && !/^magpie/i.test(id) && !(state.clients || []).some((a) => a.id === id);
|
||||
}
|
||||
// pickCountAs opens the agents a client can be counted as, under its menu
|
||||
// button.
|
||||
function pickCountAs(anchor, g) {
|
||||
const opts = (state.clients || []).filter((a) => a.id !== "magpie").map((a) => ({ v: a.id, name: a.name, literalName: true, note: "" }));
|
||||
openProtoMenu(anchor, opts, "", (v) => countClientAs(g.id, v), "Count this client's calls as", "", "left", false, opts.length > 8 ? "Search agents…" : "");
|
||||
}
|
||||
// countClientAs counts a client's calls as an agent's on the Usage and
|
||||
// Sessions pages, or on its own again (as ""), and draws the page again
|
||||
// from the ledger read anew: the history is counted the new way too.
|
||||
async function countClientAs(client, as) {
|
||||
try {
|
||||
const s = await api("usage/arrange", { count: { client, as } });
|
||||
state.settings = { ...state.settings, clientAgents: s.clientAgents || {} };
|
||||
status(as ? t("{client} is counted as {agent}", { client, agent: (state.clients || []).find((a) => a.id === as)?.name || as }) : t("{client} is counted on its own", { client }), "ok");
|
||||
await loadUsage();
|
||||
} catch (e) {
|
||||
status(e.message, "err");
|
||||
}
|
||||
}
|
||||
|
||||
// hideUsageAgent takes a client out of the Usage page's Agents list, or
|
||||
// puts it back: drawn at once, put back if the save fails. Its calls stay
|
||||
// in the ledger and in every total.
|
||||
@@ -17855,6 +17894,8 @@ function ledDetail(r, cols) {
|
||||
dl.append(el("dt", "", t("Routing")), dd);
|
||||
}
|
||||
if (r.computerName) add("Computer", r.computerName);
|
||||
// the client's own name, for one the user counts as an agent (#1958)
|
||||
add("Client", r.client);
|
||||
// the columns a narrow window leaves out, shown only while it does (#860)
|
||||
const opt = (name, value) => {
|
||||
if (!value) return;
|
||||
|
||||
@@ -3187,6 +3187,13 @@ const I18N = {
|
||||
"Found groups are off: only yours are listed and served": "已关闭自动创建路由组:只保留你自己的组",
|
||||
"Bring it back": "恢复",
|
||||
"Hide from this list": "从列表中隐藏",
|
||||
"Count as an agent…": "计入某个 Agent…",
|
||||
"Count {client} on its own": "将 {client} 单独计算",
|
||||
"with {clients}": "含 {clients}",
|
||||
"Count this client's calls as": "将此客户端的调用计入",
|
||||
"{client} is counted as {agent}": "{client} 已计入 {agent}",
|
||||
"{client} is counted on its own": "{client} 已单独计算",
|
||||
"Client": "客户端",
|
||||
"Actions for {name}": "{name} 的操作",
|
||||
"Unhide": "取消隐藏",
|
||||
"Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "只是不在此列表中显示,它们的调用仍计入总数和图表。点击查看。",
|
||||
@@ -7874,6 +7881,13 @@ const I18N = {
|
||||
"Found groups are off: only yours are listed and served": "已關閉自動建立路由組:只保留你自己的組",
|
||||
"Bring it back": "恢復",
|
||||
"Hide from this list": "從列表中隱藏",
|
||||
"Count as an agent…": "計入某個 Agent…",
|
||||
"Count {client} on its own": "將 {client} 單獨計算",
|
||||
"with {clients}": "含 {clients}",
|
||||
"Count this client's calls as": "將此用戶端的呼叫計入",
|
||||
"{client} is counted as {agent}": "{client} 已計入 {agent}",
|
||||
"{client} is counted on its own": "{client} 已單獨計算",
|
||||
"Client": "用戶端",
|
||||
"Actions for {name}": "{name} 的操作",
|
||||
"Unhide": "取消隱藏",
|
||||
"Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "只是不在此列表中顯示,它們的呼叫仍計入總數和圖表。點按查看。",
|
||||
@@ -12571,6 +12585,13 @@ const I18N = {
|
||||
"Found groups are off: only yours are listed and served": "グループの自動作成はオフです:自分のグループだけを一覧・提供します",
|
||||
"Bring it back": "元に戻す",
|
||||
"Hide from this list": "この一覧から隠す",
|
||||
"Count as an agent…": "エージェントとして数える…",
|
||||
"Count {client} on its own": "{client} を別に数える",
|
||||
"with {clients}": "{clients} を含む",
|
||||
"Count this client's calls as": "このクライアントの呼び出しを数える先",
|
||||
"{client} is counted as {agent}": "{client} を {agent} として数えます",
|
||||
"{client} is counted on its own": "{client} を別に数えます",
|
||||
"Client": "クライアント",
|
||||
"Actions for {name}": "{name} の操作",
|
||||
"Unhide": "再表示",
|
||||
"Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "この一覧に表示しないだけで、呼び出しは合計とグラフに含まれます。クリックで表示します。",
|
||||
@@ -17268,6 +17289,13 @@ const I18N = {
|
||||
"Found groups are off: only yours are listed and served": "Gefundene Gruppen sind ausgeschaltet: nur Ihre werden aufgelistet und bereitgestellt",
|
||||
"Bring it back": "Wiederherstellen",
|
||||
"Hide from this list": "In dieser Liste ausblenden",
|
||||
"Count as an agent…": "Als Agent zählen…",
|
||||
"Count {client} on its own": "{client} wieder einzeln zählen",
|
||||
"with {clients}": "mit {clients}",
|
||||
"Count this client's calls as": "Aufrufe dieses Clients zählen als",
|
||||
"{client} is counted as {agent}": "{client} wird als {agent} gezählt",
|
||||
"{client} is counted on its own": "{client} wird einzeln gezählt",
|
||||
"Client": "Client",
|
||||
"Actions for {name}": "Aktionen für {name}",
|
||||
"Unhide": "Einblenden",
|
||||
"Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "Nur in dieser Liste ausgeblendet: Ihre Aufrufe zählen weiter in den Summen und im Diagramm. Klicken, um sie zu sehen.",
|
||||
|
||||
@@ -146,6 +146,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
|
||||
UsageOrder: []string{"kimi", "codex"},
|
||||
PanelUsageHidden: []string{"deepseek"},
|
||||
UsageAgentsHidden: []string{"curl"},
|
||||
ClientAgents: map[string]string{"hermes-codex-thread-bridge": "codex"},
|
||||
PlainNames: true,
|
||||
PlainOwnNames: true,
|
||||
BareModelIDs: true,
|
||||
|
||||
@@ -43,7 +43,9 @@ function server(lang, web, saved, posts) {
|
||||
const settings = () => ({ lang, theme: "light", usageAgentsHidden: saved.hidden });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` });
|
||||
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: settings(), fx: { rate: 7.2, at: new Date().toISOString() } });
|
||||
// the clients magpie knows, curl among them, as /api/state lists them:
|
||||
// the others it doesn't know can be counted as one of them (#1958)
|
||||
if (url.pathname === "/api/state") return json({ agents: [], clients: [{ id: "pi", name: "Pi", icon: "pi" }, { id: "curl", name: "curl", icon: "curl" }], profiles: [], settings: settings(), fx: { rate: 7.2, at: new Date().toISOString() } });
|
||||
if (url.pathname === "/api/usage/arrange") {
|
||||
const body = JSON.parse(req.postData() || "{}");
|
||||
posts.push(body);
|
||||
@@ -132,13 +134,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await reader.inView(p, row("Go-http-client"));
|
||||
at = await top(p);
|
||||
await row("Go-http-client").click({ button: "right" });
|
||||
await p.locator(".row-menu .rm-item").click();
|
||||
await p.locator(".row-menu .rm-item", { hasText: w.hide }).click();
|
||||
await p.waitForFunction(() => !document.querySelector('#usageAgents .row.stat[data-id="Go-http-client"]'));
|
||||
} else {
|
||||
await reader.inView(p, row("Go-http-client"));
|
||||
at = await top(p);
|
||||
await row("Go-http-client").locator(".us-more").click();
|
||||
await p.locator(".row-menu .rm-item").click();
|
||||
await p.locator(".row-menu .rm-item", { hasText: w.hide }).click();
|
||||
await p.waitForFunction(() => !document.querySelector('#usageAgents .row.stat[data-id="Go-http-client"]'));
|
||||
}
|
||||
assert.deepEqual(saved.hidden, ["python-httpx", "curl", "Go-http-client"]);
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A client magpie doesn't know is counted as one of the agents it does,
|
||||
// from the Usage page's Agents list (#1958, NorethSea): a bridge that
|
||||
// starts Codex's app-server under a name of its own
|
||||
// (hermes-codex-thread-bridge) was a row apart from Codex. Its row's "…"
|
||||
// offers "Count as an agent…", which lists the agents magpie knows; Codex
|
||||
// picked, it is saved (POST /api/usage/arrange, count) and the page is
|
||||
// drawn again from the ledger, the bridge's calls in Codex's row, which
|
||||
// says it has them. Codex's own "…" counts it on its own again. An agent
|
||||
// magpie knows (curl) isn't offered to be counted as another. Every
|
||||
// language, a wide window and a narrow one, Chromium and WebKit; no
|
||||
// backend, 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 reader = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const BRIDGE = "hermes-codex-thread-bridge";
|
||||
|
||||
const G = (id, name, calls, tokens, icon) => ({ id, name, icon: icon || "generic", calls, input: tokens - 100, output: 100, cache_read: 0, cache_write: 0, cost: 0 });
|
||||
const CLIENTS = [{ id: "codex", name: "Codex", icon: "codex" }, { id: "claude-code", name: "Claude Code", icon: "claude" }, { id: "curl", name: "curl", icon: "curl" }, { id: "magpie", name: "magpie", icon: "magpie" }];
|
||||
|
||||
// the summary as the backend counts it: the bridge apart, or in Codex's row
|
||||
function usageOf(counted) {
|
||||
const agents = counted
|
||||
? [G("codex", "Codex", 23, 900000 + 13000, "codex"), G("curl", "curl", 4, 40000, "curl")]
|
||||
: [G("codex", "Codex", 10, 900000, "codex"), G(BRIDGE, BRIDGE, 13, 13000), G("curl", "curl", 4, 40000, "curl")];
|
||||
const total = agents.reduce((n, g) => n + g.input + g.output, 0);
|
||||
return {
|
||||
calls: 27, errors: 0, input: total - 300, output: 300, reasoning: 0, cache_read: 0, cache_write: 0, unpriced: 0, cost: 0, bucket: "day",
|
||||
series: [], path: "~/.config/magpie/usage.jsonl", agents,
|
||||
models: [{ ...G("m", "glm-5", 27, total), model: "glm-5" }],
|
||||
};
|
||||
}
|
||||
|
||||
function server(lang, saved, posts) {
|
||||
return async (route) => {
|
||||
const req = route.request();
|
||||
const url = new URL(req.url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
const settings = () => ({ lang, theme: "light", clientAgents: { ...saved.clients } });
|
||||
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: [], clients: CLIENTS, profiles: [], settings: settings() });
|
||||
if (url.pathname === "/api/usage/arrange") {
|
||||
const body = JSON.parse(req.postData() || "{}");
|
||||
posts.push(body);
|
||||
if (body.count) {
|
||||
if (body.count.as) saved.clients[body.count.client.toLowerCase()] = body.count.as;
|
||||
else delete saved.clients[body.count.client.toLowerCase()];
|
||||
}
|
||||
return json(settings());
|
||||
}
|
||||
if (url.pathname === "/api/settings") return json(settings());
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/usage") return json(usageOf(saved.clients[BRIDGE] === "codex"));
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], models: [], gateway: { running: false } });
|
||||
if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] });
|
||||
if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
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).catch(() => ""), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const L = {
|
||||
en: { count: "Count as an agent…", head: "Count this client's calls as", own: `Count ${BRIDGE} on its own`, with: `with ${BRIDGE}`, hide: "Hide from this list" },
|
||||
zh: { count: "计入某个 Agent…", head: "将此客户端的调用计入", own: `将 ${BRIDGE} 单独计算`, with: `含 ${BRIDGE}`, hide: "从列表中隐藏" },
|
||||
"zh-TW": { count: "計入某個 Agent…", head: "將此用戶端的呼叫計入", own: `將 ${BRIDGE} 單獨計算`, with: `含 ${BRIDGE}`, hide: "從列表中隱藏" },
|
||||
ja: { count: "エージェントとして数える…", head: "このクライアントの呼び出しを数える先", own: `${BRIDGE} を別に数える`, with: `${BRIDGE} を含む`, hide: "この一覧から隠す" },
|
||||
de: { count: "Als Agent zählen…", head: "Aufrufe dieses Clients zählen als", own: `${BRIDGE} wieder einzeln zählen`, with: `mit ${BRIDGE}`, hide: "In dieser Liste ausblenden" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": a client is counted as an agent from the Usage page, and on its own again", async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
for (const lang of Object.keys(L)) {
|
||||
for (const width of [1100, 420]) {
|
||||
const w = L[lang];
|
||||
await t.test(`${lang} ${width}`, async () => {
|
||||
const errors = [], posts = [], saved = { clients: {} };
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" });
|
||||
const p = await ctx.newPage();
|
||||
p.setDefaultTimeout(5000);
|
||||
p.on("pageerror", (e) => errors.push(e.message));
|
||||
await p.route("**/*", server(lang, saved, posts));
|
||||
await p.goto("http://magpie.test/");
|
||||
const nav = p.locator('[data-view="usage"]:visible').first();
|
||||
if (await nav.count()) await nav.click();
|
||||
else await p.evaluate(() => show("usage"));
|
||||
await p.locator("#usageAgents .row.stat").first().waitFor();
|
||||
const ids = () => p.locator("#usageAgents .row.stat").evaluateAll((rs) => rs.map((r) => r.dataset.id));
|
||||
const row = (id) => p.locator(`#usageAgents .row.stat[data-id="${id}"]`);
|
||||
const items = () => p.locator(".row-menu .rm-item .rm-name").allTextContents();
|
||||
const openMenu = async (id) => {
|
||||
await reader.inView(p, row(id));
|
||||
await row(id).hover();
|
||||
await row(id).locator(".us-more").click();
|
||||
await p.locator(".row-menu").waitFor();
|
||||
};
|
||||
assert.deepEqual(await ids(), ["codex", BRIDGE, "curl"]);
|
||||
|
||||
// an agent magpie knows isn't offered to be counted as another
|
||||
await openMenu("curl");
|
||||
assert.deepEqual(await items(), [w.hide]);
|
||||
await p.keyboard.press("Escape");
|
||||
|
||||
// the bridge's "…": Count as an agent…, then Codex
|
||||
await openMenu(BRIDGE);
|
||||
assert.deepEqual(await items(), [w.count, w.hide]);
|
||||
await p.locator(".row-menu .rm-item", { hasText: w.count }).click();
|
||||
const pick = p.locator(".proto-menu");
|
||||
await pick.waitFor();
|
||||
assert.equal((await pick.locator(".pm-head").textContent()).trim(), w.head);
|
||||
const names = await pick.locator(".pm-item .pm-name").allTextContents();
|
||||
assert(names.includes("Codex") && !names.includes("magpie"), "the agents offered: " + names);
|
||||
await pick.locator(".pm-item", { hasText: "Codex" }).click();
|
||||
await p.waitForFunction((b) => !document.querySelector(`#usageAgents .row.stat[data-id="${b}"]`), BRIDGE);
|
||||
assert.deepEqual(posts.at(-1), { count: { client: BRIDGE, as: "codex" } });
|
||||
assert.deepEqual(await ids(), ["codex", "curl"]);
|
||||
const sub = (await row("codex").locator(".sub").textContent()).trim();
|
||||
assert(sub.startsWith(w.with), "Codex's row doesn't say it has the bridge: " + sub);
|
||||
|
||||
// nothing is wider than the page
|
||||
const wide = await p.evaluate(() => [document.documentElement.scrollWidth, window.innerWidth]);
|
||||
assert(wide[0] <= wide[1] + 1, "no sideways scroll: " + wide);
|
||||
|
||||
// Codex's "…" counts the bridge on its own again
|
||||
await openMenu("codex");
|
||||
assert.deepEqual(await items(), [w.own, w.hide]);
|
||||
await p.locator(".row-menu .rm-item", { hasText: w.own }).click();
|
||||
await p.waitForFunction((b) => !!document.querySelector(`#usageAgents .row.stat[data-id="${b}"]`), BRIDGE);
|
||||
assert.deepEqual(posts.at(-1), { count: { client: BRIDGE, as: "" } });
|
||||
assert.deepEqual(await ids(), ["codex", BRIDGE, "curl"]);
|
||||
assert(!(await row("codex").locator(".sub").textContent()).includes(BRIDGE));
|
||||
assert.deepEqual(errors, []);
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
@@ -87,3 +88,50 @@ func TestUsageArrangeAgentsHidden(t *testing.T) {
|
||||
post("/api/usage/arrange", `{"agentsHidden":[]}`)
|
||||
want(nil, []string{"deepseek"})
|
||||
}
|
||||
|
||||
// A client magpie doesn't know is counted as one of its agents from the
|
||||
// Usage page's Agents list (#1958, NorethSea), saved on its own and kept
|
||||
// through a save of the Settings page; As "" counts it on its own again.
|
||||
// An agent magpie knows isn't counted as another, nor anything as
|
||||
// magpie, nor as a client that isn't an agent.
|
||||
func TestUsageArrangeCountClient(t *testing.T) {
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", h)
|
||||
t.Setenv("USERPROFILE", h)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
|
||||
t.Setenv("APPDATA", filepath.Join(h, "AppData", "Roaming"))
|
||||
t.Setenv("LOCALAPPDATA", filepath.Join(h, "AppData", "Local"))
|
||||
post := func(path, body string) int {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
Handler(nil, nil).ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
|
||||
return rec.Code
|
||||
}
|
||||
want := func(m map[string]string) {
|
||||
t.Helper()
|
||||
if got := settings.Load().ClientAgents; !maps.Equal(got, m) {
|
||||
t.Fatalf("clientAgents %v, want %v", got, m)
|
||||
}
|
||||
}
|
||||
if c := post("/api/usage/arrange", `{"count":{"client":"hermes-codex-thread-bridge","as":"codex"}}`); c != http.StatusOK {
|
||||
t.Fatalf("count: %d", c)
|
||||
}
|
||||
want(map[string]string{"hermes-codex-thread-bridge": "codex"})
|
||||
post("/api/settings", `{"theme":"dark"}`)
|
||||
want(map[string]string{"hermes-codex-thread-bridge": "codex"})
|
||||
for _, bad := range []string{
|
||||
`{"count":{"client":"claude-code","as":"codex"}}`,
|
||||
`{"count":{"client":"magpie-router","as":"codex"}}`,
|
||||
`{"count":{"client":"my-bridge","as":"magpie"}}`,
|
||||
`{"count":{"client":"my-bridge","as":"Python-urllib"}}`,
|
||||
`{"count":{"client":"","as":"codex"}}`,
|
||||
} {
|
||||
if c := post("/api/usage/arrange", bad); c == http.StatusOK {
|
||||
t.Fatalf("%s was taken", bad)
|
||||
}
|
||||
}
|
||||
want(map[string]string{"hermes-codex-thread-bridge": "codex"})
|
||||
post("/api/usage/arrange", `{"count":{"client":"Hermes-Codex-Thread-Bridge","as":""}}`)
|
||||
want(nil)
|
||||
}
|
||||
|
||||
@@ -461,6 +461,15 @@ type Settings struct {
|
||||
// Agents list leaves out (ikunbots on X). It is that list's only: the
|
||||
// ledger keeps their calls, and the totals and the chart count them.
|
||||
UsageAgentsHidden []string `json:"usageAgentsHidden,omitempty"`
|
||||
// ClientAgents counts a client magpie doesn't know as one of the agents
|
||||
// it does, on the Usage and Sessions pages (#1958, NorethSea): a bridge
|
||||
// that starts Codex's app-server under a name of its own
|
||||
// ("hermes-codex-thread-bridge") is counted as Codex. Keyed by the
|
||||
// client's name as the ledger records it, lower-cased, to the agent's
|
||||
// id. Only what the pages report: the ledger keeps the client's own
|
||||
// name, and routing, keys, caps and budgets go on by it. A pair taken
|
||||
// out counts the client on its own again, the history with it.
|
||||
ClientAgents map[string]string `json:"clientAgents,omitempty"`
|
||||
// Visible narrows the models an agent is shown, by agent id: the
|
||||
// families (the tag a provider or group is given), provider ids and
|
||||
// group ids its lists hold. An agent it doesn't name is shown them all.
|
||||
@@ -1189,6 +1198,7 @@ func save(s Settings, recording bool) error {
|
||||
s.UsageOrder = ids(s.UsageOrder)
|
||||
s.PanelUsageHidden = ids(s.PanelUsageHidden)
|
||||
s.UsageAgentsHidden = ids(s.UsageAgentsHidden)
|
||||
s.ClientAgents = clientAgents(s.ClientAgents)
|
||||
s.TrayUsages = ids(s.TrayUsages)
|
||||
for i, u := range s.CodexAutoReset {
|
||||
s.CodexAutoReset[i] = strings.ToLower(u)
|
||||
@@ -1377,3 +1387,51 @@ func ids(in []string) []string {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// clientAgents is ClientAgents as kept: the clients' names lower-cased and
|
||||
// trimmed, an empty name or agent left out.
|
||||
func clientAgents(m map[string]string) map[string]string {
|
||||
if len(m) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string]string, len(m))
|
||||
for k, v := range m {
|
||||
k, v = strings.ToLower(strings.TrimSpace(k)), strings.TrimSpace(v)
|
||||
if k != "" && v != "" {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ClientAgentsNow is Load().ClientAgents, parsed again only once the file
|
||||
// changed: the usage pages ask for it on every read of the ledger, which
|
||||
// the gateway does too, and the whole settings file is more to parse.
|
||||
func ClientAgentsNow() map[string]string {
|
||||
fileMu.RLock()
|
||||
defer fileMu.RUnlock()
|
||||
m, err := filememo.Read("settings.clientAgents", Path(), func(b []byte) (map[string]string, error) {
|
||||
if len(bytes.TrimSpace(b)) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var s struct {
|
||||
ClientAgents map[string]string `json:"clientAgents"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return clientAgents(s.ClientAgents), nil
|
||||
})
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
// what load makes of a file that doesn't parse (its last good
|
||||
// generation), not none
|
||||
return clientAgents(load().ClientAgents)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ type blockPricer struct {
|
||||
wires map[string]string
|
||||
price func(Record) *catalog.Price
|
||||
by map[[4]string]pricedAs
|
||||
agents map[string]string
|
||||
agents map[string][2]string
|
||||
pooled []*[]packedRow
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ func (b *blockPricer) release() {
|
||||
}
|
||||
|
||||
func newBlockPricer(aliases, wires map[string]string, price func(Record) *catalog.Price) *blockPricer {
|
||||
return &blockPricer{aliases: aliases, wires: wires, price: price, by: map[[4]string]pricedAs{}, agents: map[string]string{}}
|
||||
return &blockPricer{aliases: aliases, wires: wires, price: price, by: map[[4]string]pricedAs{}, agents: map[string][2]string{}}
|
||||
}
|
||||
|
||||
// as is priceRow's answer for a gateway call of these names.
|
||||
@@ -73,13 +73,15 @@ func (b *blockPricer) as(prov, model, served, effort string) pricedAs {
|
||||
return a
|
||||
}
|
||||
|
||||
func (b *blockPricer) agent(ua string) string {
|
||||
// agent is reportedAs's answer for a client, the agent counted and the
|
||||
// client's own name when the user's counting changed it.
|
||||
func (b *blockPricer) agent(ua string) (string, string) {
|
||||
a, ok := b.agents[ua]
|
||||
if !ok {
|
||||
a = AgentOf(ua)
|
||||
a[0], a[1] = reportedAs(ua)
|
||||
b.agents[ua] = a
|
||||
}
|
||||
return a
|
||||
return a[0], a[1]
|
||||
}
|
||||
|
||||
// block is the priced copy of a raw block, made for one query and not kept.
|
||||
@@ -119,7 +121,7 @@ func (b *blockPricer) block(packed *rowChunk) *rowChunk {
|
||||
price *catalog.Price
|
||||
}
|
||||
names := map[[4]uint32]ids{}
|
||||
agents := map[uint32]uint32{}
|
||||
agents := map[uint32][2]uint32{}
|
||||
for i := range c.Rows {
|
||||
p := &c.Rows[i]
|
||||
k := [4]uint32{p.Text[1], p.Text[5], p.Text[7], p.Text[8]}
|
||||
@@ -131,10 +133,11 @@ func (b *blockPricer) block(packed *rowChunk) *rowChunk {
|
||||
}
|
||||
agent, ok := agents[p.Text[0]]
|
||||
if !ok {
|
||||
agent = intern(b.agent(c.Strings[p.Text[0]]), p.Text[0])
|
||||
a, client := b.agent(c.Strings[p.Text[0]])
|
||||
agent = [2]uint32{intern(a, p.Text[0]), intern(client, p.Text[rowClient])}
|
||||
agents[p.Text[0]] = agent
|
||||
}
|
||||
p.Text[0], p.Text[1] = agent, got.provider
|
||||
p.Text[0], p.Text[1], p.Text[rowClient] = agent[0], got.provider, agent[1]
|
||||
p.Flags = p.Flags&^(1|2|32) | got.flags
|
||||
if p.Flags&rowOwnCost != 0 {
|
||||
// a reported call that said what it cost costs that (#1874)
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// clientMap is the user's ClientAgents (#1958) as last read, and a key
|
||||
// for the caches built on what it counts.
|
||||
type clientMap struct {
|
||||
m map[string]string
|
||||
key string
|
||||
}
|
||||
|
||||
var clientAs atomic.Pointer[clientMap]
|
||||
|
||||
// readClientAgents reads the user's ClientAgents again, for a pass over
|
||||
// the ledger (readLogSnapshot) and the caches' keys: each record of the
|
||||
// pass is then counted by what was read here.
|
||||
func readClientAgents() *clientMap {
|
||||
m := settings.ClientAgentsNow()
|
||||
if cur := clientAs.Load(); cur != nil && maps.Equal(cur.m, m) {
|
||||
return cur
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, k := range slices.Sorted(maps.Keys(m)) {
|
||||
b.WriteString(k + "=" + m[k] + ";")
|
||||
}
|
||||
c := &clientMap{m: m, key: b.String()}
|
||||
clientAs.Store(c)
|
||||
return c
|
||||
}
|
||||
|
||||
// clientAgentsKey is what the caches of counted records key on.
|
||||
func clientAgentsKey() string { return readClientAgents().key }
|
||||
|
||||
// ReportedAs is the agent the Usage and Sessions pages count a client's
|
||||
// calls under: AgentOf's, unless the user counts that client as an agent
|
||||
// of theirs (settings.ClientAgents). Only for what is reported: the
|
||||
// gateway's own choices (routing, keys, caps) go by AgentOf, the client's
|
||||
// own name.
|
||||
func ReportedAs(ua string) string {
|
||||
a, _ := reportedAs(ua)
|
||||
return a
|
||||
}
|
||||
|
||||
// reportedAs is ReportedAs, and the client's own name when the user's
|
||||
// counting changed it ("" when it didn't).
|
||||
func reportedAs(ua string) (agent, client string) {
|
||||
a := AgentOf(ua)
|
||||
c := clientAs.Load()
|
||||
if c == nil || len(c.m) == 0 {
|
||||
return a, ""
|
||||
}
|
||||
if to := c.m[strings.ToLower(a)]; to != "" && to != a {
|
||||
return to, a
|
||||
}
|
||||
return a, ""
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// #1958 (NorethSea): a bridge that starts Codex's app-server under a name
|
||||
// of its own was counted as a client apart from Codex. Counted as Codex in
|
||||
// the user's settings, its calls are Codex's in the Usage summary, the
|
||||
// request filters and rows, and Sessions, the history with them; the rows
|
||||
// still say the client's own name, and the pair taken out counts it on
|
||||
// its own again.
|
||||
func TestClientCountedAsAgent(t *testing.T) {
|
||||
resetUsageTest(t)
|
||||
at := Clock().Add(-time.Hour)
|
||||
bridge := "hermes-codex-thread-bridge/0.4 (Mac OS 26.2; arm64)"
|
||||
Append(Record{Time: at, Agent: bridge, Session: "thread-1", Provider: "p", Model: "m", Input: 10, Output: 2, Status: 200})
|
||||
Append(Record{Time: at.Add(time.Minute), Agent: bridge, Session: "thread-1", Provider: "p", Model: "m", Input: 5, Output: 1, Status: 200})
|
||||
Append(Record{Time: at.Add(2 * time.Minute), Agent: "codex", Session: "thread-2", Provider: "p", Model: "m", Input: 7, Output: 3, Status: 200})
|
||||
|
||||
agentIDs := func(s Summary) []string {
|
||||
var out []string
|
||||
for _, g := range s.Agents {
|
||||
out = append(out, g.ID)
|
||||
}
|
||||
slices.Sort(out)
|
||||
return out
|
||||
}
|
||||
// before: two clients, as the ledger records them
|
||||
if got := agentIDs(Summarize(All)); !slices.Equal(got, []string{"codex", "hermes-codex-thread-bridge"}) {
|
||||
t.Fatalf("agents before counting: %v", got)
|
||||
}
|
||||
// warm every cache the pages read, so counting has to reach past them
|
||||
_ = Vias(time.Time{})
|
||||
_ = GatewaySessions(time.Time{}, nil)
|
||||
_ = QueryPage(All, Filter{}, 0, 50)
|
||||
|
||||
s := settings.Load()
|
||||
s.ClientAgents = map[string]string{"Hermes-Codex-Thread-Bridge": "codex"}
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sum := Summarize(All)
|
||||
if got := agentIDs(sum); !slices.Equal(got, []string{"codex"}) {
|
||||
t.Fatalf("Usage's agents with the bridge counted as Codex: %v", got)
|
||||
}
|
||||
if sum.Agents[0].Calls != 3 || sum.Agents[0].Input != 22 {
|
||||
t.Fatalf("Codex's row doesn't hold the bridge's calls: %+v", sum.Agents[0])
|
||||
}
|
||||
if got := Vias(time.Time{}); len(got["codex|thread-1"]) != 1 || len(got["hermes-codex-thread-bridge|thread-1"]) != 0 {
|
||||
t.Fatalf("Routing's sessions: %v", got)
|
||||
}
|
||||
g, ok := GatewaySessionByID("codex", "thread-1", nil)
|
||||
if !ok || g.Agent != "codex" || g.Input != 15 {
|
||||
t.Fatalf("Sessions doesn't have the bridge's thread as Codex's: %+v %v", g, ok)
|
||||
}
|
||||
// a native Codex session file of the same thread is the one shown
|
||||
if got := GatewaySessions(time.Time{}, map[string]bool{"codex|thread-1": true}); len(got) != 1 || got[0].ID != "thread-2" {
|
||||
t.Fatalf("the native session doesn't win over the bridge's: %+v", got)
|
||||
}
|
||||
page := QueryPage(All, Filter{Agent: "codex"}, 0, 50)
|
||||
if page.Total != 3 || !slices.Equal(page.Agents, []string{"codex"}) {
|
||||
t.Fatalf("Requests filtered to Codex: total %d, agents %v", page.Total, page.Agents)
|
||||
}
|
||||
clients := map[string]int{}
|
||||
for _, r := range page.Rows {
|
||||
clients[r.Client]++
|
||||
}
|
||||
if clients["hermes-codex-thread-bridge"] != 2 || clients[""] != 1 {
|
||||
t.Fatalf("the rows' own client names: %v", clients)
|
||||
}
|
||||
if rows, _, _ := Ledger(All, Filter{Agent: "codex"}); len(rows) != 3 {
|
||||
t.Fatalf("the ledger filtered to Codex: %d rows", len(rows))
|
||||
}
|
||||
// what the gateway goes by is the client's own name
|
||||
if got := AgentOf(bridge); got != "hermes-codex-thread-bridge" {
|
||||
t.Fatalf("AgentOf = %q", got)
|
||||
}
|
||||
|
||||
// taken out, the bridge is on its own again, the history with it
|
||||
s = settings.Load()
|
||||
s.ClientAgents = nil
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := agentIDs(Summarize(All)); !slices.Equal(got, []string{"codex", "hermes-codex-thread-bridge"}) {
|
||||
t.Fatalf("agents after the pair is taken out: %v", got)
|
||||
}
|
||||
if got := QueryPage(All, Filter{Agent: "codex"}, 0, 50); got.Total != 1 {
|
||||
t.Fatalf("Requests filtered to Codex after: %d", got.Total)
|
||||
}
|
||||
if _, ok := GatewaySessionByID("codex", "thread-1", nil); ok {
|
||||
t.Fatal("Sessions still has the bridge's thread as Codex's")
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,7 @@ func direct(p Period, now time.Time, rows []Row) Summary {
|
||||
continue
|
||||
}
|
||||
s.Totals.addRow(r)
|
||||
id := AgentOf(r.Agent)
|
||||
id := ReportedAs(r.Agent)
|
||||
put(agents, id, Group{ID: id}, r)
|
||||
put(models, r.Provider+"/"+r.Model, Group{ID: r.Provider + "/" + r.Model, Provider: r.Provider, Model: r.Model}, r)
|
||||
if who := r.Account(); who != "" {
|
||||
|
||||
@@ -68,7 +68,7 @@ func GatewaySessionByID(agent, id string, nativeKeys map[string]bool) (GatewaySe
|
||||
if id == "" {
|
||||
return GatewaySession{}, false
|
||||
}
|
||||
agent = AgentOf(agent)
|
||||
agent = ReportedAs(agent)
|
||||
if nativeKeys[agent+"|"+id] {
|
||||
return GatewaySession{}, false
|
||||
}
|
||||
@@ -182,7 +182,7 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map
|
||||
if r.IsRejected() || r.IsReported() || r.Session == "" {
|
||||
return
|
||||
}
|
||||
a := AgentOf(r.Agent)
|
||||
a := ReportedAs(r.Agent)
|
||||
k := key{a, r.Session}
|
||||
if nativeKeys != nil && nativeKeys[a+"|"+r.Session] {
|
||||
return
|
||||
|
||||
@@ -33,6 +33,10 @@ type Row struct {
|
||||
// which the gateway never saw: no status, no provider, no model asked
|
||||
// for, but what the file says of the call. "" for one the gateway logged.
|
||||
Source string `json:"source,omitempty"`
|
||||
// Client is the client's own name when the user counts it as another
|
||||
// agent (settings.ClientAgents, #1958): Agent is the one it is
|
||||
// counted as, this what the ledger recorded it as
|
||||
Client string `json:"client,omitempty"`
|
||||
}
|
||||
|
||||
// Failed is whether the call failed: the agent was answered an error status,
|
||||
@@ -146,7 +150,7 @@ func (f Filter) keeps(r Record) bool {
|
||||
if f.Model != "" && r.Model != f.Model {
|
||||
return false
|
||||
}
|
||||
if f.Agent != "" && AgentOf(r.Agent) != f.Agent {
|
||||
if f.Agent != "" && ReportedAs(r.Agent) != f.Agent {
|
||||
return false
|
||||
}
|
||||
if f.Provider != "" && r.Provider != f.Provider {
|
||||
@@ -338,7 +342,7 @@ func logRecord(c sessions.Call) Record {
|
||||
func gatewayMatches(recs []Record, logs []sessions.Call) map[int]bool {
|
||||
gateway, local := &rowChunk{}, &rowChunk{}
|
||||
for i, r := range recs {
|
||||
r.Agent = AgentOf(r.Agent)
|
||||
r.Agent = ReportedAs(r.Agent)
|
||||
gateway.add(Row{Record: r}, "", int64(i), false)
|
||||
}
|
||||
for i, c := range logs {
|
||||
@@ -377,7 +381,7 @@ func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessi
|
||||
agents, providers = []string{}, []string{}
|
||||
identities := newSessionResolver(logs)
|
||||
add := func(r Record, pr *catalog.Price, source string) {
|
||||
if a := AgentOf(r.Agent); !slices.Contains(agents, a) {
|
||||
if a := ReportedAs(r.Agent); !slices.Contains(agents, a) {
|
||||
agents = append(agents, a)
|
||||
}
|
||||
if r.Provider != "" && !slices.Contains(providers, r.Provider) {
|
||||
@@ -394,7 +398,7 @@ func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessi
|
||||
if pr != nil && r.Input+r.Output > 0 {
|
||||
row.Cost, row.Priced = r.CostAt(*pr), true
|
||||
}
|
||||
row.Agent = AgentOf(r.Agent)
|
||||
row.Agent, row.Client = reportedAs(r.Agent)
|
||||
if !r.IsRejected() {
|
||||
sum.addFrom(row, pr)
|
||||
}
|
||||
|
||||
@@ -64,6 +64,9 @@ var logAppends struct {
|
||||
}
|
||||
|
||||
func readLogSnapshot() *logSnapshot {
|
||||
// the clients the user counts as agents, read once for the pass the
|
||||
// snapshot is read for (#1958)
|
||||
readClientAgents()
|
||||
logIndex.Lock()
|
||||
defer logIndex.Unlock()
|
||||
path := Path()
|
||||
|
||||
@@ -62,7 +62,7 @@ type RequestPage struct {
|
||||
|
||||
type packedRow struct {
|
||||
Time time.Time
|
||||
Text [34]uint32
|
||||
Text [35]uint32
|
||||
Tokens [6]int64
|
||||
Millis, TTFT, FirstText, Order int64
|
||||
Sent, Flow, FirstReasoning int64
|
||||
@@ -104,16 +104,19 @@ type rowChunk struct {
|
||||
// rowMsg is the Text of a row's Claude message id, after rowText's, and
|
||||
// rowError its error's
|
||||
const (
|
||||
rowMsg = 33
|
||||
rowMsg = 34
|
||||
rowError = 9
|
||||
// rowClient is the Text of the client's own name, when the user counts
|
||||
// it as another agent (Row.Client, #1958)
|
||||
rowClient = 33
|
||||
)
|
||||
|
||||
// rowText is every string of a row's record, the upstream's own stop
|
||||
// reason ("Upstream stop reason", #1927) and the service tiers (#1784)
|
||||
// among them: a string left out comes back empty from the cache, in the
|
||||
// page and in /v1/magpie/usage/requests (TestRowTextHoldsEveryString)
|
||||
func rowText(r *Row) [33]*string {
|
||||
return [33]*string{&r.Agent, &r.Provider, &r.Host, &r.SessionProvider, &r.SessionAccount, &r.Model, &r.Requested, &r.Served, &r.Effort, &r.Error, &r.ErrType, &r.RequestID, &r.Endpoint, &r.Session, &r.NativeSession, &r.Kind, &r.Source, &r.Via, &r.ProviderKeyID, &r.ProviderKeyName, &r.CallerKeyID, &r.CallerKeyName, &r.Archive, &r.Operation, &r.ProviderAccount, &r.ResponseID, &r.Upstream, &r.Subagent, &r.ParentAgent, &r.Stop, &r.TierAsked, &r.TierSent, &r.TierServed}
|
||||
func rowText(r *Row) [34]*string {
|
||||
return [34]*string{&r.Agent, &r.Provider, &r.Host, &r.SessionProvider, &r.SessionAccount, &r.Model, &r.Requested, &r.Served, &r.Effort, &r.Error, &r.ErrType, &r.RequestID, &r.Endpoint, &r.Session, &r.NativeSession, &r.Kind, &r.Source, &r.Via, &r.ProviderKeyID, &r.ProviderKeyName, &r.CallerKeyID, &r.CallerKeyName, &r.Archive, &r.Operation, &r.ProviderAccount, &r.ResponseID, &r.Upstream, &r.Subagent, &r.ParentAgent, &r.Stop, &r.TierAsked, &r.TierSent, &r.TierServed, &r.Client}
|
||||
}
|
||||
func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
|
||||
if c.dict == nil {
|
||||
@@ -299,7 +302,7 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
|
||||
cfg := settings.Load()
|
||||
prices, _ := json.Marshal(cfg.ModelPrices)
|
||||
wires, _ := json.Marshal(cfg.ModelWires)
|
||||
meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s", ids, renamed, prices, wires, statKey(provider.Path()), statKey(catalog.CachePath()))
|
||||
meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%s", ids, renamed, prices, wires, statKey(provider.Path()), statKey(catalog.CachePath()), clientAgentsKey())
|
||||
h := sha256.New()
|
||||
for _, current := range provider.All() {
|
||||
fmt.Fprintf(h, "%q:%q:%v:%t:%t:%t;", current.ID, current.Where(), current.Catalogs(), current.IsPlugin(), current.Account == nil, current.Key != "")
|
||||
@@ -383,7 +386,7 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
|
||||
row.Priced = true
|
||||
row.Cost = r.CostAt(*pr)
|
||||
}
|
||||
row.Agent = AgentOf(r.Agent)
|
||||
row.Agent, row.Client = reportedAs(r.Agent)
|
||||
return row
|
||||
}
|
||||
since := p.Since(now)
|
||||
|
||||
@@ -113,5 +113,6 @@ func usagePriceCacheKey(now time.Time) string {
|
||||
fmt.Fprint(h, statKey(catalog.LivePath(current.ID)))
|
||||
}
|
||||
meta += fmt.Sprintf("|%x", h.Sum(nil))
|
||||
return meta
|
||||
// and the clients the user counts as agents (#1958)
|
||||
return meta + "|" + clientAgentsKey()
|
||||
}
|
||||
|
||||
@@ -850,7 +850,7 @@ func summarizeFrom(p Period, now time.Time, first time.Time, historicalKeys map[
|
||||
if i >= 0 && i < len(s.Series) {
|
||||
s.Series[i].add(r, pr)
|
||||
}
|
||||
id := AgentOf(r.Agent) // one kept before magpie knew the agent by name
|
||||
id := ReportedAs(r.Agent) // one kept before magpie knew the agent by name
|
||||
a := agents[id]
|
||||
if a == nil {
|
||||
a = &Group{ID: id}
|
||||
@@ -976,7 +976,7 @@ func buildVias(snapshot *logSnapshot, since time.Time) map[string][]Via {
|
||||
if r.IsRejected() || r.IsReported() || r.Session == "" || r.Model == "" {
|
||||
return
|
||||
}
|
||||
k := AgentOf(r.Agent) + "|" + r.Session
|
||||
k := ReportedAs(r.Agent) + "|" + r.Session
|
||||
vs := out[k]
|
||||
i := slices.IndexFunc(vs, func(v Via) bool { return v.Provider == r.Provider && v.Model == r.Model && v.Effort == r.Effort })
|
||||
if i < 0 {
|
||||
|
||||
@@ -10,18 +10,20 @@ var viasCache struct {
|
||||
sync.Mutex
|
||||
version uint64
|
||||
since time.Time
|
||||
clients string // the clients counted as agents (#1958)
|
||||
value map[string][]Via
|
||||
}
|
||||
|
||||
func cachedVias(since time.Time) map[string][]Via {
|
||||
snapshot := readLogSnapshot()
|
||||
clients := clientAgentsKey()
|
||||
viasCache.Lock()
|
||||
defer viasCache.Unlock()
|
||||
value := viasCache.value
|
||||
if value == nil || viasCache.version != snapshot.version || !viasCache.since.Equal(since) {
|
||||
if value == nil || viasCache.version != snapshot.version || !viasCache.since.Equal(since) || viasCache.clients != clients {
|
||||
value = buildVias(snapshot, since)
|
||||
if snapshot.info != nil && snapshot.off == snapshot.info.Size() {
|
||||
viasCache.version, viasCache.since, viasCache.value = snapshot.version, since, value
|
||||
viasCache.version, viasCache.since, viasCache.value, viasCache.clients = snapshot.version, since, value, clients
|
||||
}
|
||||
}
|
||||
out := make(map[string][]Via, len(value))
|
||||
|
||||
Reference in New Issue
Block a user