usage: clear a model's usage, or all of it, from the Usage page
CrazyMouse_TT on X asked for a way to clear usage, all of it or one model's, to measure a local model fresh after deploying it. The Usage page's Models list has a "…" on each row (and a right-click menu) with "Clear usage…", and "Clear all usage…" sits under the lists below the "Counted from…" note. Each asks first, in a confirmation that says what is deleted, that it can't be undone, and that key spending limits and allowances still count the calls. A clear is a mark in settings (usageCleared: provider, model, unix ms), read at read time; usage.jsonl is never rewritten. The Overview hides calls up to the mark in summarizeFrom; the Requests page, heatmap and ledger/CSV hide them in Filter.keepsRow, their one choke point, and the request index's meta carries the marks so its cache is dropped. Key budgets, window holds and Codex reads go through usage.Visit and the raw log, so a clear never resets a key's spending limit or a quota. A later clear of the same model or of everything takes the place of an earlier one. The marks ride the settings part of a sync (sync-backup.md) and a save of the Settings page keeps them (api.go's keep list; the guard test TestSettingsSaveKeepsWhatItDoesNotSend caught it missing). gateway-sessions.md and sync-backup.md say so. Run on mote (mote-run) at this tree, rebased on origin/mainc26b2992e(the Go packages and usage-clear.test.cjs; vet and the 68 GUI files ran at the earlier basef835bd713, four commits behind): - go test -tags nogui -timeout 45m ./internal/usage ./internal/settings ./internal/usageapi ./internal/gui: all ok after the keep-list fix (before it, TestSettingsSaveKeepsWhatItDoesNotSend red). - gofmt -l: clean. GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: exit 0. (Linux vet without nogui fails in wails' cgo, as on main.) - usage-clear.test.cjs: 32/32 in Chromium and WebKit, en/zh/zh-TW/ja/de, at 1200, 560 and 390 (web). With the old page.js/client.js/i18n.js it fails (TimeoutError). - 68 GUI files the change can reach (every usage-*, gui-de/ja/zh-tw, i18n-keys, click-scroll, idle-ticks, mobile-web, panel-usage, sessions-purge): 941/980. The reds are filed and red on main (usage-ledger run alone at origin/main84a6a2c42too): i18n-keys "masking…" (#4053), mobile-web (#3952), usage-agents-hide (#2276, #3414), usage-ledger "newest live route needs no return-to-live button" (#3104, run alone at main too). i18n-keys first also named "Clear usage…" in Go comments of this change; reworded. Broken by hand, each red: hides() always false (usage and gui tests), keepsRow's clear check removed ("Requests after the clear: 5 rows"), clearedKey out of the request meta ("after clearing everything: 3"), the api.go keep line removed (UsageCleared [] after a save). Not tried: the full go ./... suite and the whole GUI suite (mote was busy with other sessions' full suites), the real app, a sync between two computers. usage.jsonl doesn't shrink, and the Sessions tab's figures are not cleared.
This commit is contained in:
@@ -74,6 +74,28 @@ Requests, the Requests ledger and model lists keep each call's own id.
|
||||
Verification: `TestUsageAliasCountsTwoIdsAsOne`,
|
||||
`TestSessionsCountAliasedModelsAsOne`, `TestAliasStatsLeavesItsInputAlone`.
|
||||
|
||||
The Usage page can clear its figures (CrazyMouse_TT on X): a model's row's
|
||||
"…" has "Clear usage…", and "Clear all usage…" sits under the lists. Each
|
||||
asks first, then `POST /api/usage/clear` adds a mark to `usageCleared` in
|
||||
settings.json ([`settings.ClearUsage`](../../internal/settings/settings.go)):
|
||||
a provider and model as the Models list names them (the alias, the
|
||||
provider's shown id), or neither for everything, and the time in Unix
|
||||
milliseconds. usage.jsonl is never rewritten. The usage pages leave out
|
||||
each call at or before a mark that matches it
|
||||
([`cleared.go`](../../internal/usage/cleared.go)): the Overview
|
||||
(`summarizeFrom`), and the Requests page, its heatmap and the CSV through
|
||||
`Filter.keepsRow`; the request index keys its meta on the marks
|
||||
(`clearedKey`), so a cached page is read again. Gateway keys' spending
|
||||
limits, the allowances' window holds and Codex's reads go by `usage.Visit`
|
||||
and the raw log, so they still count every cleared call: a clear never
|
||||
lifts a limit, and the confirmation says so. The marks ride the settings
|
||||
part of a sync, so a clear holds on the computers it syncs with, over
|
||||
their shared days and the agents' session-file rows too, and a later clear
|
||||
of the same model or of everything takes an earlier one's place. Usage ›
|
||||
Sessions is not cleared. Verification: `TestClearedUsageLeavesThePages`,
|
||||
`TestClearUsageKeepsOneMarkAModel`, `TestUsageClearRoute`,
|
||||
`usage-clear.test.cjs`.
|
||||
|
||||
Claude Desktop gateway rows can have a local name even without a CLI
|
||||
transcript (#1675). [`DesktopTitles`](../../internal/sessions/desktop_titles.go)
|
||||
reads `claude-code-sessions/*/*/local_*.json` and
|
||||
|
||||
@@ -47,6 +47,12 @@ session resumes in (`SessionTerminal`) and what the menu bar shows. Launch at
|
||||
login is the system's own setting (`internal/autostart`) and the listen
|
||||
address is `MAGPIE_ADDR`, so neither is in a bundle.
|
||||
|
||||
The Usage page's clears (`usageCleared`, see
|
||||
[gateway sessions](gateway-sessions.md)) are a preference, not a computer's
|
||||
own, so they ride the settings part: a model cleared on one computer is
|
||||
cleared on the others, their shared usage days included. The usage files
|
||||
themselves are never rewritten by a clear.
|
||||
|
||||
The providers part works the same way for which account an agent is kept
|
||||
signed in to (`KeepLogin`, `KeepLoginAs`, `SwitchOnly`): one person keeps a
|
||||
personal account at home and a work account at the office, and sync set
|
||||
|
||||
@@ -1350,6 +1350,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
in.UsageAgentsHidden = cur.UsageAgentsHidden
|
||||
// and the names models' usage is counted under (magpie model alias)
|
||||
in.UsageAliases = cur.UsageAliases
|
||||
// and the clears of usage made on the Usage page
|
||||
in.UsageCleared = cur.UsageCleared
|
||||
// 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
|
||||
|
||||
@@ -1197,6 +1197,8 @@ body.masked :hover > .acct-eye, body.masked .pq-card:hover .acct-eye, body.maske
|
||||
.us-hid .list[hidden] { display: none; }
|
||||
.row.stat.hid > :not(.us-unhide) { opacity: .55; }
|
||||
.usage-note { padding: 10px 4px 2px; font-size: 11px; color: var(--faint); user-select: text; -webkit-user-select: text; }
|
||||
.usage-clear { margin: 0; padding: 2px 0 6px; }
|
||||
.usage-clear button { font-size: 11px; }
|
||||
.usage-pane { display: flex; flex-direction: column; flex: none; }
|
||||
.usage-pane[hidden] { display: none; }
|
||||
|
||||
|
||||
@@ -50,6 +50,7 @@ magpie.plugin("usage", (ctx) => {
|
||||
<div class="row-head" id="usageKeysHead" hidden><button class="fold" type="button" data-fold="keys" aria-expanded="true" aria-controls="usageKeys"><span class="label" data-t>Gateway keys</span></button></div>
|
||||
<div class="list" id="usageKeys" hidden></div>
|
||||
<p class="usage-note" id="usageNote"></p>
|
||||
<p class="usage-clear"><button class="text" id="usageClear" type="button" hidden><span data-t>Clear all usage…</span></button></p>
|
||||
<div class="plugin-slot" data-slot="usage" hidden></div>
|
||||
</div>
|
||||
<div class="usage-pane" id="ledgerPane" hidden>
|
||||
|
||||
@@ -2,6 +2,15 @@
|
||||
// kernel adds them to i18n.js's (magpie.strings).
|
||||
magpie.strings({
|
||||
zh: {
|
||||
"Clear usage…": "清除用量…",
|
||||
"Clear all usage…": "清除全部用量…",
|
||||
"Clear the usage of {model}?": "清除 {model} 的用量?",
|
||||
"Clear all usage?": "清除全部用量?",
|
||||
"Every call to {model} at {provider} so far stops being counted on the Usage page: its requests, tokens, cost, speed and cache, in every period, on this computer and those it syncs with.": "{provider} 上 {model} 至今的每次调用都不再计入「用量」页:它的请求、token、费用、速度和缓存,在所有时间段里、在这台电脑和与它同步的电脑上都不再计入。",
|
||||
"Every call so far stops being counted on the Usage page: the requests, tokens, cost, speed and cache of every agent and model, in every period, on this computer and those it syncs with.": "至今的每次调用都不再计入「用量」页:所有 Agent 和模型的请求、token、费用、速度和缓存,在所有时间段里、在这台电脑和与它同步的电脑上都不再计入。",
|
||||
"Gateway keys' spending limits and the allowances still count these calls. This can't be undone.": "网关密钥的消费上限和额度仍会计入这些调用。此操作无法撤销。",
|
||||
"The usage of {model} is cleared": "{model} 的用量已清除",
|
||||
"All usage is cleared": "全部用量已清除",
|
||||
"+1 key": "+1 个密钥",
|
||||
"+{n} keys": "+{n} 个密钥",
|
||||
"One balance for the account these keys share: {keys}": "这些密钥同属一个账号,余额只显示一次:{keys}",
|
||||
@@ -224,6 +233,15 @@ magpie.strings({
|
||||
"Sent upstream as {to}, as the agent spoke it": "以 {to} 协议发往上游,与 agent 所用协议相同",
|
||||
},
|
||||
"zh-TW": {
|
||||
"Clear usage…": "清除用量…",
|
||||
"Clear all usage…": "清除全部用量…",
|
||||
"Clear the usage of {model}?": "清除 {model} 的用量?",
|
||||
"Clear all usage?": "清除全部用量?",
|
||||
"Every call to {model} at {provider} so far stops being counted on the Usage page: its requests, tokens, cost, speed and cache, in every period, on this computer and those it syncs with.": "{provider} 上 {model} 至今的每次呼叫都不再計入「用量」頁:它的請求、token、費用、速度和快取,在所有時段裡、在這台電腦和與它同步的電腦上都不再計入。",
|
||||
"Every call so far stops being counted on the Usage page: the requests, tokens, cost, speed and cache of every agent and model, in every period, on this computer and those it syncs with.": "至今的每次呼叫都不再計入「用量」頁:所有 Agent 和模型的請求、token、費用、速度和快取,在所有時段裡、在這台電腦和與它同步的電腦上都不再計入。",
|
||||
"Gateway keys' spending limits and the allowances still count these calls. This can't be undone.": "閘道金鑰的消費上限和額度仍會計入這些呼叫。此操作無法復原。",
|
||||
"The usage of {model} is cleared": "{model} 的用量已清除",
|
||||
"All usage is cleared": "全部用量已清除",
|
||||
"+1 key": "+1 個金鑰",
|
||||
"+{n} keys": "+{n} 個金鑰",
|
||||
"One balance for the account these keys share: {keys}": "這些金鑰同屬一個帳號,餘額只顯示一次:{keys}",
|
||||
@@ -446,6 +464,15 @@ magpie.strings({
|
||||
"Sent upstream as {to}, as the agent spoke it": "以 {to} 協議發往上游,與 agent 所用協議相同",
|
||||
},
|
||||
ja: {
|
||||
"Clear usage…": "使用量を消去…",
|
||||
"Clear all usage…": "すべての使用量を消去…",
|
||||
"Clear the usage of {model}?": "{model} の使用量を消去しますか?",
|
||||
"Clear all usage?": "すべての使用量を消去しますか?",
|
||||
"Every call to {model} at {provider} so far stops being counted on the Usage page: its requests, tokens, cost, speed and cache, in every period, on this computer and those it syncs with.": "{provider} の {model} へのこれまでの呼び出しは、使用量ページで数えられなくなります。リクエスト、トークン、コスト、速度、キャッシュが、すべての期間で、このコンピュータと同期先のコンピュータで対象です。",
|
||||
"Every call so far stops being counted on the Usage page: the requests, tokens, cost, speed and cache of every agent and model, in every period, on this computer and those it syncs with.": "これまでのすべての呼び出しは、使用量ページで数えられなくなります。すべてのエージェントとモデルのリクエスト、トークン、コスト、速度、キャッシュが、すべての期間で、このコンピュータと同期先のコンピュータで対象です。",
|
||||
"Gateway keys' spending limits and the allowances still count these calls. This can't be undone.": "ゲートウェイキーの利用上限と割り当てでは、これらの呼び出しは引き続き数えられます。この操作は取り消せません。",
|
||||
"The usage of {model} is cleared": "{model} の使用量を消去しました",
|
||||
"All usage is cleared": "すべての使用量を消去しました",
|
||||
"+1 key": "+1 個のキー",
|
||||
"+{n} keys": "+{n} 個のキー",
|
||||
"One balance for the account these keys share: {keys}": "これらのキーは同じアカウントのもので、残高は一度だけ表示されます:{keys}",
|
||||
@@ -668,6 +695,15 @@ magpie.strings({
|
||||
"Sent upstream as {to}, as the agent spoke it": "エージェントと同じ {to} で上流へ送信",
|
||||
},
|
||||
de: {
|
||||
"Clear usage…": "Nutzung löschen…",
|
||||
"Clear all usage…": "Gesamte Nutzung löschen…",
|
||||
"Clear the usage of {model}?": "Nutzung von {model} löschen?",
|
||||
"Clear all usage?": "Gesamte Nutzung löschen?",
|
||||
"Every call to {model} at {provider} so far stops being counted on the Usage page: its requests, tokens, cost, speed and cache, in every period, on this computer and those it syncs with.": "Jeder bisherige Aufruf von {model} bei {provider} wird auf der Nutzungsseite nicht mehr gezählt: seine Anfragen, Tokens, Kosten, Geschwindigkeit und Cache, in jedem Zeitraum, auf diesem Computer und denen, mit denen er synchronisiert.",
|
||||
"Every call so far stops being counted on the Usage page: the requests, tokens, cost, speed and cache of every agent and model, in every period, on this computer and those it syncs with.": "Jeder bisherige Aufruf wird auf der Nutzungsseite nicht mehr gezählt: Anfragen, Tokens, Kosten, Geschwindigkeit und Cache aller Agenten und Modelle, in jedem Zeitraum, auf diesem Computer und denen, mit denen er synchronisiert.",
|
||||
"Gateway keys' spending limits and the allowances still count these calls. This can't be undone.": "Ausgabenlimits der Gateway-Schlüssel und die Kontingente zählen diese Aufrufe weiterhin. Das kann nicht rückgängig gemacht werden.",
|
||||
"The usage of {model} is cleared": "Die Nutzung von {model} ist gelöscht",
|
||||
"All usage is cleared": "Die gesamte Nutzung ist gelöscht",
|
||||
"+1 key": "+1 Schlüssel",
|
||||
"+{n} keys": "+{n} Schlüssel",
|
||||
"One balance for the account these keys share: {keys}": "Ein Guthaben für das Konto, zu dem diese Schlüssel gehören: {keys}",
|
||||
|
||||
@@ -321,6 +321,7 @@ function renderUsageLoading() {
|
||||
// still there while the period loads (#809, Hu9956: 用量界面红框这行会延迟几秒才会出现)
|
||||
for (const h of $$("#view-usage .row-head:not(#quotaHead, .plugin-panel > .row-head)")) h.hidden = true;
|
||||
$("#usageNote").textContent = "";
|
||||
$("#usageClear").hidden = true;
|
||||
}
|
||||
|
||||
// costHead is the Usage head's sum: the cost at effective prices, or, when
|
||||
@@ -539,6 +540,7 @@ function renderUsage() {
|
||||
const none = noCallsIn(period);
|
||||
stats.append(el("div", "none", t(none) + " " + t("Point an agent at a catalog model and use it; every call through the gateway is counted here.")));
|
||||
$("#usageNote").textContent = "";
|
||||
$("#usageClear").hidden = true;
|
||||
return;
|
||||
}
|
||||
stats.classList.remove("empty");
|
||||
@@ -697,15 +699,64 @@ function renderUsage() {
|
||||
b.onclick = (e) => { e.stopPropagation(); hideUsageAgent(g.id, false); };
|
||||
r.append(b);
|
||||
});
|
||||
list("usageModels", u.models);
|
||||
// a model's usage cleared (CrazyMouse_TT on X: a local model deployed
|
||||
// again, its requests, speed and cache wanted from nothing)
|
||||
list("usageModels", u.models, (r, g) => {
|
||||
if (!g.model) return;
|
||||
r.classList.add("acts");
|
||||
const b = el("button", "icon us-more");
|
||||
b.type = "button";
|
||||
b.setAttribute("aria-haspopup", "menu");
|
||||
b.setAttribute("aria-label", t("Actions for {name}", { name: g.name || g.model }));
|
||||
b.append(svg(DOTS, 14, 2.2));
|
||||
const menu = () => {
|
||||
const again = agentMenu?.anchor === b;
|
||||
closeAgentMenu();
|
||||
if (again) return;
|
||||
openRowMenu(b, [{ name: "Clear usage…", icon: USAGE_CLEAR, run: () => clearUsage(g) }]);
|
||||
};
|
||||
b.onclick = (e) => { e.stopPropagation(); menu(); };
|
||||
r.oncontextmenu = (e) => { e.preventDefault(); menu(); };
|
||||
r.querySelector(".share").after(b);
|
||||
});
|
||||
list("usageAccounts", u.accounts || []);
|
||||
list("usageKeys", u.callerKeys || []);
|
||||
$("#usageNote").textContent = t("Counted from the providers' own usage reports on every call through the gateway · {path}", { path: u.path });
|
||||
const clear = $("#usageClear");
|
||||
clear.hidden = false;
|
||||
clear.onclick = () => clearUsage();
|
||||
// the account cards say how many of this period's requests were
|
||||
// magpie's own (ownLine), which they could only once the summary came
|
||||
if (quotas && (u.accounts?.some((g) => g.own?.calls) || $("#subscriptionUsage .quota-own"))) renderQuotas();
|
||||
}
|
||||
|
||||
// clearUsage clears the Usage page's figures, after the reader confirms:
|
||||
// one model's (g, from the Models list) or everything's (no g). The calls
|
||||
// up to now stop being counted on the usage pages, here and on the
|
||||
// computers this one syncs with; the request log keeps them, so a key's
|
||||
// spending limit and the allowances still count them
|
||||
// (settings.UsageCleared).
|
||||
const USAGE_CLEAR = "M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.6 8.5h5.8l.6-8.5M7 7v3.5M9 7v3.5";
|
||||
async function clearUsage(g) {
|
||||
const ok = await confirmAction(
|
||||
g ? t("Clear the usage of {model}?", { model: g.name || g.model }) : t("Clear all usage?"),
|
||||
(g
|
||||
? t("Every call to {model} at {provider} so far stops being counted on the Usage page: its requests, tokens, cost, speed and cache, in every period, on this computer and those it syncs with.", { model: g.name || g.model, provider: (g.sub || g.provider || "").split(" · ")[0] })
|
||||
: t("Every call so far stops being counted on the Usage page: the requests, tokens, cost, speed and cache of every agent and model, in every period, on this computer and those it syncs with."))
|
||||
+ " " + t("Gateway keys' spending limits and the allowances still count these calls. This can't be undone."),
|
||||
t("Clear"),
|
||||
);
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api("usage/clear", g ? { provider: g.provider || "", model: g.model } : {});
|
||||
status(g ? t("The usage of {model} is cleared", { model: g.name || g.model }) : t("All usage is cleared"), "ok");
|
||||
ledger = null;
|
||||
await loadUsage();
|
||||
} catch (e) {
|
||||
status(e.message, "err");
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -134,6 +134,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
|
||||
ModelAPIs: map[string]string{"p/m": "anthropic"},
|
||||
ModelSameAs: map[string]string{"p/m": "deepseek-v4.1-flash"},
|
||||
UsageAliases: map[string]string{"deepseek-v4.1-flash": "deepseek-flash"},
|
||||
UsageCleared: []settings.UsageClear{{Provider: "p", Model: "m", At: 1761600000000}},
|
||||
ModelKinds: map[string]string{"p/m": "video"},
|
||||
RedactRules: []redact.Rule{{Kind: "prefix", Prefix: "oc_sk_"}},
|
||||
RedactActions: map[string]string{"API_KEY": "block", "EMAIL": "warn"},
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// The Usage page clears its figures (CrazyMouse_TT on X: a local model
|
||||
// deployed again, benchmarked from nothing). A model's "…" (or a
|
||||
// right-click on its row) offers "Clear usage…", and "Clear all usage…"
|
||||
// sits under the lists. Each asks first, in an alert that says what goes,
|
||||
// that key limits and allowances still count it, and that it can't be
|
||||
// undone; Cancel sends nothing, Clear POSTs /api/usage/clear and the page
|
||||
// is read again. Every language, a wide window, a narrow one and magpie
|
||||
// web on a phone; 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 G = (id, name, tokens, extra) => ({ id, name, icon: "generic", calls: 10, input: tokens - 100, output: 100, cache_read: 0, cache_write: 0, cost: 0, ...extra });
|
||||
const QWEN = G("ollama/qwen3:32b", "qwen3:32b", 900000, { provider: "ollama", model: "qwen3:32b", sub: "Ollama" });
|
||||
const LLAMA = G("ollama/llama4", "llama4", 300000, { provider: "ollama", model: "llama4", sub: "Ollama" });
|
||||
const usageOf = (models) => {
|
||||
const total = models.reduce((n, g) => n + g.input + g.output, 0);
|
||||
return {
|
||||
calls: 10 * models.length, errors: 0, input: total - 100 * models.length, output: 100 * models.length, reasoning: 0, cache_read: 0, cache_write: 0, unpriced: 0, cost: 0, bucket: "day",
|
||||
series: [], path: "~/.config/magpie/usage.jsonl",
|
||||
agents: models.length ? [G("pi", "Pi", total)] : [],
|
||||
models,
|
||||
};
|
||||
};
|
||||
|
||||
function server(lang, web, 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" });
|
||||
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: [], clients: [{ id: "pi", name: "Pi", icon: "pi" }], profiles: [], settings: settings(), fx: { rate: 7.2, at: new Date().toISOString() } });
|
||||
if (url.pathname === "/api/usage/clear") {
|
||||
const body = JSON.parse(req.postData() || "{}");
|
||||
posts.push(body);
|
||||
saved.models = body.model ? saved.models.filter((g) => g.model !== body.model) : [];
|
||||
return json({ ok: true });
|
||||
}
|
||||
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.models));
|
||||
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), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const L = {
|
||||
en: { item: "Clear usage…", all: "Clear all usage…", title: "Clear the usage of qwen3:32b?", allTitle: "Clear all usage?", go: "Clear", cancel: "Cancel", undo: "can't be undone", keys: "spending limits" },
|
||||
zh: { item: "清除用量…", all: "清除全部用量…", title: "清除 qwen3:32b 的用量?", allTitle: "清除全部用量?", go: "清空", cancel: "取消", undo: "无法撤销", keys: "消费上限" },
|
||||
"zh-TW": { item: "清除用量…", all: "清除全部用量…", title: "清除 qwen3:32b 的用量?", allTitle: "清除全部用量?", go: "清空", cancel: "取消", undo: "無法復原", keys: "消費上限" },
|
||||
ja: { item: "使用量を消去…", all: "すべての使用量を消去…", title: "qwen3:32b の使用量を消去しますか?", allTitle: "すべての使用量を消去しますか?", go: "クリア", cancel: "キャンセル", undo: "取り消せません", keys: "利用上限" },
|
||||
de: { item: "Nutzung löschen…", all: "Gesamte Nutzung löschen…", title: "Nutzung von qwen3:32b löschen?", allTitle: "Gesamte Nutzung löschen?", go: "Leeren", cancel: "Abbrechen", undo: "nicht rückgängig", keys: "Ausgabenlimits" },
|
||||
};
|
||||
const SIZES = [{ width: 1200, web: false }, { width: 560, web: false }, { width: 390, web: true }];
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": the Usage page clears a model's usage, and all of it, after asking", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
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, web } of SIZES) {
|
||||
const w = L[lang];
|
||||
await t.test(`${lang} ${width}${web ? " web" : ""}`, async () => {
|
||||
const errors = [];
|
||||
const saved = { models: [QWEN, LLAMA] }, posts = [];
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce", hasTouch: web, isMobile: web && engine === "chromium" });
|
||||
const p = await ctx.newPage();
|
||||
p.setDefaultTimeout(5000);
|
||||
p.on("pageerror", (e) => errors.push(e.message));
|
||||
await p.route("**/*", server(lang, web, 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("#usageModels .row.stat").first().waitFor();
|
||||
const ids = () => p.locator("#usageModels .row.stat").evaluateAll((rs) => rs.map((r) => r.dataset.id));
|
||||
assert.deepEqual(await ids(), [QWEN.id, LLAMA.id]);
|
||||
assert.equal(await p.locator("select").count(), 0, "no native select");
|
||||
|
||||
const row = p.locator(`#usageModels .row.stat[data-id="${QWEN.id}"]`);
|
||||
await reader.inView(p, row);
|
||||
if (!web) await row.hover();
|
||||
const more = row.locator(".us-more");
|
||||
await more.click();
|
||||
const item = p.locator(".row-menu .rm-item");
|
||||
assert.deepEqual((await item.allTextContents()).map((s) => s.trim()), [w.item]);
|
||||
await item.click();
|
||||
const dialog = p.locator("dialog.action-confirm");
|
||||
await dialog.waitFor();
|
||||
assert.equal(await dialog.getAttribute("role"), "alertdialog");
|
||||
assert.equal((await dialog.locator("h2").textContent()).trim(), w.title);
|
||||
const said = await dialog.locator("p").textContent();
|
||||
assert(said.includes(w.undo) && said.includes(w.keys) && said.includes("qwen3:32b"), "the alert says what goes and that it stays: " + said);
|
||||
// Cancel sends nothing
|
||||
await dialog.locator("button", { hasText: w.cancel }).click();
|
||||
await dialog.waitFor({ state: "detached" });
|
||||
assert.deepEqual(posts, []);
|
||||
assert.deepEqual(await ids(), [QWEN.id, LLAMA.id]);
|
||||
|
||||
// a right-click opens the same menu; Clear sends the model
|
||||
if (!web) await row.click({ button: "right" });
|
||||
else await more.click();
|
||||
await p.locator(".row-menu .rm-item", { hasText: w.item }).click();
|
||||
await dialog.waitFor();
|
||||
await dialog.locator("button.danger-fill").click();
|
||||
await p.waitForFunction((id) => !document.querySelector(`#usageModels .row.stat[data-id="${CSS.escape(id)}"]`), QWEN.id);
|
||||
assert.deepEqual(posts, [{ provider: "ollama", model: "qwen3:32b" }]);
|
||||
assert.deepEqual(await ids(), [LLAMA.id]);
|
||||
|
||||
// Clear all usage…, under the lists
|
||||
const all = p.locator("#usageClear");
|
||||
await reader.inView(p, all);
|
||||
assert.equal((await all.textContent()).trim(), w.all);
|
||||
await all.click();
|
||||
await dialog.waitFor();
|
||||
assert.equal((await dialog.locator("h2").textContent()).trim(), w.allTitle);
|
||||
assert.equal((await dialog.locator("button.danger-fill").textContent()).trim(), w.go);
|
||||
await dialog.locator("button.danger-fill").click();
|
||||
await p.waitForFunction(() => document.querySelector("#stats")?.classList.contains("empty"));
|
||||
assert.deepEqual(posts.at(-1), {});
|
||||
assert.equal(await all.isHidden(), true, "nothing left to clear: the button goes");
|
||||
|
||||
const wide = await p.evaluate(() => { const v = document.querySelector("#view-usage"); return [v.scrollWidth, v.clientWidth, document.documentElement.scrollWidth, window.innerWidth]; });
|
||||
assert(wide[0] <= wide[1] + 1 && wide[2] <= wide[3] + 1, "no sideways scroll: " + wide);
|
||||
assert.deepEqual(errors, []);
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
"github.com/yetone/magpie/internal/usageapi"
|
||||
)
|
||||
@@ -129,6 +130,23 @@ func usageRoutes(mux *http.ServeMux, w Windows) {
|
||||
}
|
||||
writeJSON(rw, out)
|
||||
})
|
||||
// a clear of usage from the Usage page (CrazyMouse_TT on X): the calls up to
|
||||
// now of one provider's model, or of everything with both "", stop
|
||||
// being counted on the usage pages. usage.jsonl keeps them, and a key's
|
||||
// spending limit and the allowances still count them
|
||||
// (settings.UsageCleared).
|
||||
mux.HandleFunc("POST /api/usage/clear", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Provider, Model string }
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
if err := settings.ClearUsage(in.Provider, in.Model, usage.Clock()); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, map[string]bool{"ok": true})
|
||||
})
|
||||
// a deleted provider's calls, as the Usage page lists them under id:
|
||||
// merged into a provider there is now (Into, "" to part them again)
|
||||
// or shown by a name of the user's (Name, "" for its own); one not
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// The Usage page's clear on a model's row, and the one for all usage
|
||||
// under the lists (CrazyMouse_TT on X), POST /api/usage/clear: the
|
||||
// model's calls, or every call, leave the page's figures.
|
||||
func TestUsageClearRoute(t *testing.T) {
|
||||
sandboxHome(t)
|
||||
at := time.Now().Add(-time.Hour)
|
||||
usage.Append(usage.Record{Time: at, Agent: "codex", Provider: "ollama", Model: "qwen3", Input: 10, Status: 200})
|
||||
usage.Append(usage.Record{Time: at, Agent: "codex", Provider: "ollama", Model: "llama4", Input: 5, Status: 200})
|
||||
mux := http.NewServeMux()
|
||||
usageRoutes(mux, folderOnly{})
|
||||
post := func(body string, code int) {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/usage/clear", strings.NewReader(body)))
|
||||
if w.Code != code {
|
||||
t.Fatalf("POST %s: %d %s", body, w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
post(`{"provider":"ollama","model":"qwen3"}`, 200)
|
||||
if s := usage.Summarize(usage.All); s.Calls != 1 || len(s.Models) != 1 || s.Models[0].Model != "llama4" {
|
||||
t.Fatalf("after clearing qwen3: %+v", s.Models)
|
||||
}
|
||||
post(`{"provider":"ollama"}`, http.StatusBadRequest)
|
||||
post(`{}`, 200)
|
||||
if s := usage.Summarize(usage.All); s.Calls != 0 {
|
||||
t.Fatalf("after clearing everything: %d calls", s.Calls)
|
||||
}
|
||||
if got := settings.Load().UsageCleared; len(got) != 1 {
|
||||
t.Fatalf("settings: %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -645,6 +645,15 @@ type Settings struct {
|
||||
// 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"`
|
||||
// UsageCleared are the user's clears of the Usage page's figures
|
||||
// (CrazyMouse_TT on X: a local model benchmarked again from nothing),
|
||||
// each the calls up to its time, of one provider's model or of
|
||||
// everything. Only what the usage pages report: usage.jsonl keeps every
|
||||
// call, and a key's spending limit, the allowances' window holds and
|
||||
// the gateway's own reads of its log still count them. It rides the
|
||||
// settings part of a sync, so a clear holds on every computer that
|
||||
// syncs with this one, other computers' shared days included.
|
||||
UsageCleared []UsageClear `json:"usageCleared,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.
|
||||
@@ -1685,6 +1694,7 @@ func save(s Settings, recording bool) error {
|
||||
s.PanelUsageHidden = ids(s.PanelUsageHidden)
|
||||
s.UsageAgentsHidden = ids(s.UsageAgentsHidden)
|
||||
s.ClientAgents = clientAgents(s.ClientAgents)
|
||||
s.UsageCleared = usageCleared(s.UsageCleared)
|
||||
s.TrayUsages = ids(s.TrayUsages)
|
||||
for i, u := range s.CodexAutoReset {
|
||||
s.CodexAutoReset[i] = strings.ToLower(u)
|
||||
@@ -1903,6 +1913,102 @@ func clientAgents(m map[string]string) map[string]string {
|
||||
return out
|
||||
}
|
||||
|
||||
// UsageClear is one clear of the Usage page's figures: the calls up to At
|
||||
// (Unix milliseconds) of Model at Provider, as the page's Models list
|
||||
// names them (the model counted under its usage alias, the provider under
|
||||
// the id it is shown by now), stop being counted there. Both "" is every
|
||||
// call.
|
||||
type UsageClear struct {
|
||||
Provider string `json:"provider,omitempty"`
|
||||
Model string `json:"model,omitempty"`
|
||||
At int64 `json:"at"`
|
||||
}
|
||||
|
||||
// Time is when the clear was made.
|
||||
func (c UsageClear) Time() time.Time { return time.UnixMilli(c.At) }
|
||||
|
||||
// Covers is whether c clears every call o clears: everything, or the same
|
||||
// model, up to a time no earlier.
|
||||
func (c UsageClear) Covers(o UsageClear) bool {
|
||||
return c.At >= o.At && (c.Provider == "" && c.Model == "" || c.Provider == o.Provider && c.Model == o.Model)
|
||||
}
|
||||
|
||||
// usageCleared is UsageCleared as kept: one without a time left out, and
|
||||
// one another covers (a later clear of everything, or of the same model)
|
||||
// dropped, so the list holds no more than one a model.
|
||||
func usageCleared(in []UsageClear) []UsageClear {
|
||||
var out []UsageClear
|
||||
for i, c := range in {
|
||||
c.Provider, c.Model = strings.TrimSpace(c.Provider), strings.TrimSpace(c.Model)
|
||||
if c.At <= 0 {
|
||||
continue
|
||||
}
|
||||
covered := false
|
||||
for j, o := range in {
|
||||
o.Provider, o.Model = strings.TrimSpace(o.Provider), strings.TrimSpace(o.Model)
|
||||
// of two the same, the first is kept
|
||||
if j != i && o.At > 0 && o.Covers(c) && (!c.Covers(o) || j < i) {
|
||||
covered = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !covered {
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ClearUsage adds a clear of the Usage page's figures up to at: of model at
|
||||
// provider, or of everything with both "". It changes UsageCleared alone,
|
||||
// from what the file holds now, so a save elsewhere from an older snapshot
|
||||
// isn't undone; a settings file that can't be read is left as it is, with
|
||||
// the error.
|
||||
func ClearUsage(provider, model string, at time.Time) error {
|
||||
provider, model = strings.TrimSpace(provider), strings.TrimSpace(model)
|
||||
if model == "" && provider != "" {
|
||||
return fmt.Errorf("a clear of %q's usage names its model", provider)
|
||||
}
|
||||
if at.UnixMilli() <= 0 {
|
||||
return fmt.Errorf("a clear of usage needs a time")
|
||||
}
|
||||
defer lockFile()()
|
||||
s, err := loadChecked()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.UsageCleared = usageCleared(append(slices.Clone(s.UsageCleared), UsageClear{Provider: provider, Model: model, At: at.UnixMilli()}))
|
||||
return save(s, false)
|
||||
}
|
||||
|
||||
// UsageClearedNow is Load().UsageCleared, parsed again only once the file
|
||||
// changed: every read of the usage pages asks for it.
|
||||
func UsageClearedNow() []UsageClear {
|
||||
fileMu.RLock()
|
||||
defer fileMu.RUnlock()
|
||||
m, err := filememo.Read("settings.usageCleared", Path(), func(b []byte) ([]UsageClear, error) {
|
||||
if len(bytes.TrimSpace(b)) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var s struct {
|
||||
UsageCleared []UsageClear `json:"usageCleared"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return usageCleared(s.UsageCleared), 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 usageCleared(load().UsageCleared)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A clear of usage from the Usage page (CrazyMouse_TT on X) keeps one mark a
|
||||
// model: a later clear of the same model, or of everything, takes the
|
||||
// place of an earlier one, and a clear of a provider names its model.
|
||||
func TestClearUsageKeepsOneMarkAModel(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
if err := os.MkdirAll(Dir(), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
at := time.Date(2026, 10, 28, 9, 0, 0, 0, time.UTC)
|
||||
if err := ClearUsage("ollama", "qwen3", at); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ClearUsage("ollama", "llama4", at); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// the same model again, later: one mark, the later
|
||||
if err := ClearUsage(" ollama ", "qwen3 ", at.Add(time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := UsageClearedNow()
|
||||
if len(got) != 2 || got[0].Model != "llama4" || got[1].Model != "qwen3" || got[1].At != at.Add(time.Hour).UnixMilli() {
|
||||
t.Fatalf("after three clears of two models: %+v", got)
|
||||
}
|
||||
if s := Load(); len(s.UsageCleared) != 2 {
|
||||
t.Fatalf("Load: %+v", s.UsageCleared)
|
||||
}
|
||||
if err := ClearUsage("ollama", "", at); err == nil {
|
||||
t.Fatal("a clear of a provider with no model was taken")
|
||||
}
|
||||
if err := ClearUsage("", "", time.Time{}); err == nil {
|
||||
t.Fatal("a clear with no time was taken")
|
||||
}
|
||||
// everything, at the latest: the models' marks it covers go
|
||||
if err := ClearUsage("", "", at.Add(2*time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := UsageClearedNow(); len(got) != 1 || got[0].Provider != "" || got[0].Model != "" {
|
||||
t.Fatalf("after clearing everything: %+v", got)
|
||||
}
|
||||
// a model cleared after that is kept beside it
|
||||
if err := ClearUsage("ollama", "qwen3", at.Add(3*time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := UsageClearedNow(); len(got) != 2 {
|
||||
t.Fatalf("a model cleared after everything: %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// Clearing the Usage page's figures (CrazyMouse_TT on X: a local model
|
||||
// deployed again and benchmarked, its requests, speed and cache wanted from
|
||||
// nothing). A clear is kept in settings (settings.UsageCleared) and read
|
||||
// over whatever the pages count, never written into usage.jsonl: the log
|
||||
// keeps every call, so a key's spending limit (package budget), the
|
||||
// allowances' window holds and the gateway's own reads of it (Visit) still
|
||||
// count the calls cleared, and the agents' session files and other
|
||||
// computers' shared days, which magpie can't rewrite, are cleared the same
|
||||
// way as its own log.
|
||||
|
||||
// clearSet is the user's clears as last read, the usage aliases a model's
|
||||
// clear takes in, and a key for the caches built on what they hide.
|
||||
type clearSet struct {
|
||||
marks []settings.UsageClear
|
||||
alias func(string) string
|
||||
// all is the latest clear of everything, zero for none
|
||||
all time.Time
|
||||
key string
|
||||
}
|
||||
|
||||
var clearedAs atomic.Pointer[clearSet]
|
||||
|
||||
// readCleared reads the user's clears again, for a pass over the usage:
|
||||
// each record of the pass is then judged by what was read here
|
||||
// (clearedNow). It reads settings.json, so it is called before any lock a
|
||||
// reader of the usage waits on.
|
||||
func readCleared() *clearSet {
|
||||
marks := settings.UsageClearedNow()
|
||||
var aliases map[string]string
|
||||
if len(marks) > 0 {
|
||||
aliases = provider.UsageAliases()
|
||||
}
|
||||
b, _ := json.Marshal(struct {
|
||||
M []settings.UsageClear
|
||||
A map[string]string
|
||||
}{marks, aliases})
|
||||
key := string(b)
|
||||
if cur := clearedAs.Load(); cur != nil && cur.key == key {
|
||||
return cur
|
||||
}
|
||||
c := &clearSet{marks: marks, key: key}
|
||||
if len(aliases) > 0 {
|
||||
c.alias = provider.UsageAliasIn(aliases)
|
||||
}
|
||||
for _, m := range marks {
|
||||
if m.Provider == "" && m.Model == "" && m.Time().After(c.all) {
|
||||
c.all = m.Time()
|
||||
}
|
||||
}
|
||||
clearedAs.Store(c)
|
||||
return c
|
||||
}
|
||||
|
||||
// clearedKey is what the caches of counted records key on.
|
||||
func clearedKey() string { return readCleared().key }
|
||||
|
||||
// clearedNow is the clears the last readCleared read; nil before any.
|
||||
func clearedNow() *clearSet { return clearedAs.Load() }
|
||||
|
||||
// hides is whether the user cleared r from the usage pages: a clear of
|
||||
// everything, or of its provider's model, made at or after its time. r's
|
||||
// provider is the one it is shown under (renameBy) and its model is taken
|
||||
// by its own id or by the usage alias it is counted under, as the
|
||||
// Overview's Models list names it.
|
||||
func (c *clearSet) hides(r *Record) bool {
|
||||
if c == nil || len(c.marks) == 0 {
|
||||
return false
|
||||
}
|
||||
if !c.all.IsZero() && !r.Time.After(c.all) {
|
||||
return true
|
||||
}
|
||||
model := ""
|
||||
for _, m := range c.marks {
|
||||
if m.Model == "" || r.Time.After(m.Time()) || m.Provider != r.Provider {
|
||||
continue
|
||||
}
|
||||
if r.Model == m.Model {
|
||||
return true
|
||||
}
|
||||
if c.alias != nil {
|
||||
if model == "" {
|
||||
model = c.alias(r.Model)
|
||||
}
|
||||
if model == m.Model {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// clearedSince is when the usage counted begins after a clear of
|
||||
// everything: first, or the clear's time when it is later.
|
||||
func (c *clearSet) clearedSince(first time.Time) time.Time {
|
||||
if c == nil || c.all.IsZero() || !first.IsZero() && first.After(c.all) {
|
||||
return first
|
||||
}
|
||||
return c.all
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// CrazyMouse_TT on X: a local model deployed again is benchmarked from
|
||||
// nothing. A clear of one model hides its calls up to the clear from the
|
||||
// Overview, the Requests page, its heatmap and the ledger (the CSV), its
|
||||
// alias's ids with it, and leaves other models and later calls counted; a
|
||||
// clear of everything hides every call up to it. The log keeps them, so
|
||||
// Visit (key spending limits, window holds) still counts them all.
|
||||
func TestClearedUsageLeavesThePages(t *testing.T) {
|
||||
resetUsageTest(t)
|
||||
now := Clock()
|
||||
at := now.Add(-2 * time.Hour)
|
||||
Append(Record{Time: at, Agent: "codex", Provider: "ollama", Model: "qwen3:32b", Input: 100, Output: 10, Status: 200})
|
||||
Append(Record{Time: at.Add(time.Minute), Agent: "codex", Provider: "ollama", Model: "qwen3-32b-q4", Input: 50, Output: 5, Status: 200})
|
||||
Append(Record{Time: at.Add(2 * time.Minute), Agent: "codex", Provider: "ollama", Model: "llama4", Input: 7, Output: 3, Status: 200})
|
||||
Append(Record{Time: at.Add(3 * time.Minute), Agent: "codex", Provider: "openai", Model: "qwen3:32b", Input: 9, Output: 1, Status: 200})
|
||||
if _, err := provider.SetUsageAlias("qwen3-32b-q4", "qwen3:32b"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
models := func() map[string]int {
|
||||
out := map[string]int{}
|
||||
for _, g := range Summarize(All).Models {
|
||||
out[g.Provider+"/"+g.Model] += g.Calls
|
||||
}
|
||||
return out
|
||||
}
|
||||
if got := models(); got["ollama/qwen3:32b"] != 2 || got["ollama/llama4"] != 1 || got["openai/qwen3:32b"] != 1 {
|
||||
t.Fatalf("before the clear: %v", got)
|
||||
}
|
||||
// warm every cache the pages read, so the clear has to reach past them
|
||||
_ = QueryPage(All, Filter{}, 0, 50)
|
||||
_ = HeatmapOf(Filter{})
|
||||
|
||||
if err := settings.ClearUsage("ollama", "qwen3:32b", Clock().Add(-time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// a call after the clear is counted
|
||||
Append(Record{Time: Clock(), Agent: "codex", Provider: "ollama", Model: "qwen3:32b", Input: 1, Output: 1, Status: 200})
|
||||
|
||||
if got := models(); got["ollama/qwen3:32b"] != 1 || got["ollama/llama4"] != 1 || got["openai/qwen3:32b"] != 1 {
|
||||
t.Fatalf("Overview after clearing ollama's qwen3:32b: %v", got)
|
||||
}
|
||||
if s := Summarize(All); s.Calls != 3 || s.Input != 17 {
|
||||
t.Fatalf("Overview totals: %d calls, %d in", s.Calls, s.Input)
|
||||
}
|
||||
page := QueryPage(All, Filter{}, 0, 50)
|
||||
if page.Total != 3 {
|
||||
t.Fatalf("Requests after the clear: %d rows", page.Total)
|
||||
}
|
||||
for _, r := range page.Rows {
|
||||
if r.Provider == "ollama" && r.Time.Before(Clock().Add(-time.Hour)) && r.Model != "llama4" {
|
||||
t.Fatalf("a cleared row is listed: %+v", r.Record)
|
||||
}
|
||||
}
|
||||
heat := 0
|
||||
for _, d := range HeatmapOf(Filter{}).Days {
|
||||
heat += d.Calls
|
||||
}
|
||||
if heat != 3 {
|
||||
t.Fatalf("heatmap after the clear: %d calls", heat)
|
||||
}
|
||||
if rows, _, _ := Ledger(All, Filter{}); len(rows) != 3 {
|
||||
t.Fatalf("ledger (CSV) after the clear: %d rows", len(rows))
|
||||
}
|
||||
// the log is whole: what key limits and window holds read
|
||||
seen := 0
|
||||
Visit(time.Time{}, func(Record) { seen++ })
|
||||
if seen != 5 {
|
||||
t.Fatalf("Visit after the clear: %d records, want all 5", seen)
|
||||
}
|
||||
|
||||
// everything, now: nothing up to it is counted
|
||||
if err := settings.ClearUsage("", "", Clock()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := Summarize(All); s.Calls != 0 || len(s.Models) != 0 {
|
||||
t.Fatalf("Overview after clearing everything: %d calls, %d models", s.Calls, len(s.Models))
|
||||
}
|
||||
if page := QueryPage(All, Filter{}, 0, 50); page.Total != 0 {
|
||||
t.Fatalf("Requests after clearing everything: %d", page.Total)
|
||||
}
|
||||
Append(Record{Time: Clock().Add(time.Second), Agent: "pi", Provider: "ollama", Model: "llama4", Input: 2, Output: 2, Status: 200})
|
||||
if s := Summarize(All); s.Calls != 1 || !slices.ContainsFunc(s.Agents, func(g Group) bool { return g.ID == "pi" }) {
|
||||
t.Fatalf("a call after clearing everything: %+v", s.Agents)
|
||||
}
|
||||
seen = 0
|
||||
Visit(time.Time{}, func(Record) { seen++ })
|
||||
if seen != 6 {
|
||||
t.Fatalf("Visit after clearing everything: %d", seen)
|
||||
}
|
||||
}
|
||||
@@ -120,6 +120,9 @@ func SourceOf(r Row) string {
|
||||
// keepsRow is keeps with the one dimension a Record does not carry: which of
|
||||
// the two sources the row is of (Row.Source, not the record's).
|
||||
func (f Filter) keepsRow(r *Row) bool {
|
||||
if clearedNow().hides(&r.Record) { // the user's clears (cleared.go)
|
||||
return false
|
||||
}
|
||||
if f.Through != "" && SourceOf(*r) != f.Through {
|
||||
return false
|
||||
}
|
||||
@@ -256,6 +259,7 @@ func LedgerOfAt(p Period, f Filter, now time.Time) Ledgered {
|
||||
|
||||
// ledgerOfAt is LedgerOfAt over the session files' calls reader reads.
|
||||
func ledgerOfAt(p Period, f Filter, now time.Time, reader func(time.Time) []sessions.Call) Ledgered {
|
||||
readCleared() // the user's clears, which keepsRow leaves out
|
||||
since := p.Since(now)
|
||||
gatewaySince := since
|
||||
if !since.IsZero() {
|
||||
|
||||
@@ -644,7 +644,7 @@ func readRequestState(now time.Time) requestState {
|
||||
cfg := settings.Load()
|
||||
prices, _ := json.Marshal(cfg.ModelPrices)
|
||||
wires, _ := json.Marshal(cfg.ModelWires)
|
||||
meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%s", ids, renamed, prices, wires, statKey(provider.Path()), statKey(catalog.CachePath()), clientAgentsKey())
|
||||
meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%s|%s", ids, renamed, prices, wires, statKey(provider.Path()), statKey(catalog.CachePath()), clientAgentsKey(), clearedKey())
|
||||
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 != "")
|
||||
|
||||
@@ -951,6 +951,10 @@ func summarizeFrom(p Period, now time.Time, first time.Time, historicalKeys map[
|
||||
}
|
||||
}
|
||||
historicalKeys = normalizedKeys
|
||||
// the user's clears (cleared.go): a call cleared is in no figure, and a
|
||||
// clear of everything starts the timeline again
|
||||
cleared := readCleared()
|
||||
first = cleared.clearedSince(first)
|
||||
// a picked range's own days alone: its chart can start on the Monday
|
||||
// before its first, and it ends before now (#1492)
|
||||
from, until := p.Since(now), p.Until(now)
|
||||
@@ -960,6 +964,9 @@ func summarizeFrom(p Period, now time.Time, first time.Time, historicalKeys map[
|
||||
return
|
||||
}
|
||||
r.renameBy(renamed)
|
||||
if cleared.hides(&r) {
|
||||
return
|
||||
}
|
||||
fn(r)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user