gateway: a key's limit lines are read again while the page is open
Young (Discord #feedback, v0.1.18xx) reset his gateway keys' usage (three keys held to 2-3 models, $30 per 5 hours, $153 per 7 days and a token cap per 30 days) and their lines read "$0.00 / $30.00" from then on, while Usage's gateway-key section showed the same keys spending. The cause is in the GUI: the Gateway page read /api/caller-keys, where each key's used limits come from, only on a visit to the page (the `open` hook). Coming back to the window and Refresh re-read providers (`render`) but not the keys, and nothing ticked, so a page left open after Reset usage kept the $0.00 it drew then. The app reopens on its last page, so it could read $0 for days. Now refreshGatewayKeys reads the keys again from `render` (the window back, Refresh) and every 15s while the Gateway page is in sight and a key has a limit, as Usage's own timer does (#3185). The list is drawn again only when the keys changed, and never over a key being added, renamed or its limit edited, nor while an action is on its way. The gateway side was checked first and counts right: a probe test with Young's key shape (model scope incl. a group, $ and token limits), reset, the budget cache dropped as a restart does, and requests on chat/completions, messages and responses, streamed and not, counted every call into each limit's window. The probe is not committed. Test: internal/gui/tests/gateway-key-used-live.test.cjs, Young's key shape, chromium and webkit, en and zh: the line goes from $0.00 to $9.93 on window focus, to $12.50 on the timer, and an open limit editor keeps its typed value and focus through both. Run on mote: - the new file: 4 of 4 ok. - every gateway-*, connect-* GUI file and i18n-keys, both engines (262 tests): 259 ok. The 3 reds are the same on the base without this change and filed: gateway-caller-keys webkit en and gateway-key-models chromium/webkit en at 560px (#3797), i18n-keys "Runs as" (#3897). - go test -tags nogui -timeout 45m ./...: 76 packages ok, exit 0, at5ed6669ceplus this change. - after rebasing on6f0e40572(two commits, neither in the gateway page): go build ./..., the new file with gateway-key-limits and i18n-keys (28 of 28 ok), and internal/gui's Go tests 3 times at -count=1: 2 ok, 1 red in TestRestartHandsTheGatewayOver (a request reset during the handover, #3451, not from this change). Broken by hand, each red in the new test: - render not calling refreshGatewayKeys: red at the focus step. - the timer at 15e6 ms: red at the timer step. - refreshGatewayKeys drawing over an open editor: red (focus lost). Not covered: Young also says Usage's per-key spend stays still while the Overview's gateway tokens move. Usage reads its own data on its own timer, so this change doesn't touch that. The Overview counts every gateway call, keyed or not, while a key's row and limits count only calls that carried that enabled key. A loopback call (an agent here, or a TCP forward like frp tcp or ssh -R to the gateway's port) with a stale or rotated key is still answered, by design, but is counted under no key. Whether that is Young's case is not known yet. Not tried: the real app with a real key over hours.
This commit is contained in:
@@ -690,6 +690,9 @@ magpie.plugin("gateway", (ctx) => {
|
||||
backToReader($("#view-gateway"));
|
||||
};
|
||||
$("#openLanSettings").onclick = () => { openSettings(); setSetTab("network", true); };
|
||||
new MutationObserver(gatewayKeysTicks).observe($("#view-gateway"), { attributes: true, attributeFilter: ["hidden"] });
|
||||
document.addEventListener("visibilitychange", gatewayKeysTicks);
|
||||
gatewayKeysTicks();
|
||||
},
|
||||
// nothing read yet: the page's skeleton (#123)
|
||||
loading: renderGatewayLoading,
|
||||
@@ -707,6 +710,8 @@ magpie.plugin("gateway", (ctx) => {
|
||||
if (was && !$("#view-gateway").classList.contains("loading") && same({ ...was, gateway: { ...was.gateway, calls: 0 } }, { ...providers, gateway: { ...providers.gateway, calls: 0 } })) {
|
||||
if (!same(was.gateway.calls, providers.gateway.calls)) renderActivity();
|
||||
} else renderGatewayView();
|
||||
// and what each key has used of its limits, read on open only before
|
||||
refreshGatewayKeys();
|
||||
},
|
||||
// the recent calls again, a page of them (the setting changed)
|
||||
calls() {
|
||||
|
||||
@@ -74,6 +74,37 @@ async function loadGatewayKeys() {
|
||||
}
|
||||
}
|
||||
|
||||
// refreshGatewayKeys reads the keys again for what each has used of its
|
||||
// limits, which only a visit to the page read before: left open, a reset
|
||||
// key's line said $0.00 however much was spent after it (Young on Discord).
|
||||
// It runs as the page is drawn again (the window back, a Refresh) and on
|
||||
// a timer while the page is in sight; the list is drawn again only when
|
||||
// it changed, and not while a key is being added, renamed or its limit
|
||||
// edited, nor while an action is on its way.
|
||||
async function refreshGatewayKeys() {
|
||||
if (gatewayKeys === null || gatewayKeysBusy) return;
|
||||
const read = ++gatewayKeysRead;
|
||||
let out;
|
||||
try { out = await api("caller-keys"); } catch { return; }
|
||||
if (read !== gatewayKeysRead || gatewayKeysBusy) return;
|
||||
const keys = out.keys || [];
|
||||
if (JSON.stringify(keys) === JSON.stringify(gatewayKeys)) return;
|
||||
gatewayKeys = keys;
|
||||
gatewayAccountNames = out.accountNames || gatewayAccountNames;
|
||||
if (gatewayKeyDraft === null && gatewayLimit === null && !$("#gatewayKeys .rename-in")) renderGatewayKeys();
|
||||
}
|
||||
// the timer: only while the Gateway page is in sight, as a look with
|
||||
// nothing to do wakes the web content process all the same (#3185)
|
||||
let gatewayKeysTick = 0;
|
||||
function gatewayKeysTicks() {
|
||||
const page = $("#view-gateway");
|
||||
if (!page || page.hidden || document.hidden) { clearInterval(gatewayKeysTick); gatewayKeysTick = 0; return; }
|
||||
gatewayKeysTick ||= setInterval(() => {
|
||||
if ($("#view-gateway").hidden || document.hidden) return gatewayKeysTicks();
|
||||
if (view === "gateway" && gatewayKeys?.some((k) => !k.off && keyUsed(k).length)) refreshGatewayKeys();
|
||||
}, 15e3);
|
||||
}
|
||||
|
||||
async function gatewayKeyAction(action, body) {
|
||||
if (gatewayKeysBusy) return null;
|
||||
gatewayKeysBusy = true;
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// A gateway key's limit lines say what it has used while the Gateway
|
||||
// page stays open: Young (Discord, v0.1.18xx) reset his keys' usage and
|
||||
// their lines read $0.00 from then on, while Usage showed the same keys
|
||||
// spending, because the keys were read only on a visit to the page. Now
|
||||
// the window coming back, and a timer while the page is in sight, read
|
||||
// them again. Both engines, en and zh.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
const { fixture } = require("./fixtures/caller-keys.cjs");
|
||||
|
||||
const src = fs.readFileSync(path.resolve(__dirname, "../assets/i18n.js"), "utf8");
|
||||
const I18N = new Function(src.slice(0, src.indexOf("\n};") + 3) + "; return I18N;")();
|
||||
|
||||
const hour = 36e5, day = 864e5;
|
||||
// Young's shape: a key held to some models, $ caps over 5 hours and 7 days
|
||||
// and a token cap over 30, just reset
|
||||
const used = (cost, tokens) => {
|
||||
const since = new Date(Date.now() - 60e3).toISOString();
|
||||
const u = (period, extra) => ({ period, start: since, calls: cost ? 12 : 0, tokens, cost, tokensLeft: 0, costLeft: 0, spent: false, ...extra });
|
||||
return [
|
||||
u("hours", { hours: 5, reset: new Date(Date.now() + 5 * hour).toISOString(), costLimit: 30, costLeft: 30 - cost }),
|
||||
u("days", { days: 7, reset: new Date(Date.now() + 7 * day).toISOString(), costLimit: 153, costLeft: 153 - cost }),
|
||||
u("days", { days: 30, reset: new Date(Date.now() + 30 * day).toISOString(), tokenLimit: 1e13, tokensLeft: 1e13 - tokens }),
|
||||
];
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh"]) {
|
||||
test(`${engine} ${lang}: a key's used limits are read again while the page is open`, async (t) => {
|
||||
const tr = (k, vars = {}) => {
|
||||
const s = lang === "en" ? k : I18N[lang][k];
|
||||
assert.equal(typeof s, "string", `${lang} has ${k}`);
|
||||
return s.replace(/\{(\w+)\}/g, (_, v) => String(vars[v]));
|
||||
};
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width: 1100, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const key = {
|
||||
id: "pool", name: "拼车-自用", masked: "sk-magpie-key-…6fcf81", models: ["a/m", "group/mine"],
|
||||
limit: { period: "hours", hours: 5, cost: 30 },
|
||||
moreLimits: [{ period: "days", days: 7, cost: 153 }, { period: "days", days: 30, tokens: 1e13 }],
|
||||
};
|
||||
const keys = [key, { id: "other", name: "其他模型", masked: "sk-magpie-key-…222222" }];
|
||||
const spend = (cost, tokens) => { key.usedAll = used(cost, tokens); key.used = key.usedAll[0]; };
|
||||
spend(0, 0);
|
||||
await page.clock.install();
|
||||
await page.route("**/*", fixture(lang, "light", [], { lan: true, keys }));
|
||||
await page.goto("http://magpie.test/?view=gateway");
|
||||
const lines = page.locator('#gatewayKeys .acc[data-key="pool"] .key-limit');
|
||||
await lines.first().waitFor();
|
||||
const zero = tr("{used} of {limit} estimated · {left} left", { used: "$0.00", limit: "$30.00", left: "$30.00" });
|
||||
assert((await lines.nth(0).textContent()).includes(zero), await lines.nth(0).textContent());
|
||||
|
||||
// calls made through the key: the window coming back shows them
|
||||
spend(9.93, 63e6);
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("focus")));
|
||||
const spent = tr("{used} of {limit} estimated · {left} left", { used: "$9.93", limit: "$30.00", left: "$20.07" });
|
||||
await page.waitForFunction((s) => document.querySelector('#gatewayKeys .acc[data-key="pool"] .key-limit')?.textContent.includes(s), spent);
|
||||
assert((await lines.nth(1).textContent()).includes("$9.93"), await lines.nth(1).textContent());
|
||||
|
||||
// and, left alone in sight, the timer does
|
||||
spend(12.5, 80e6);
|
||||
await page.clock.runFor(16e3);
|
||||
const later = tr("{used} of {limit} estimated · {left} left", { used: "$12.50", limit: "$30.00", left: "$17.50" });
|
||||
await page.waitForFunction((s) => document.querySelector('#gatewayKeys .acc[data-key="pool"] .key-limit')?.textContent.includes(s), later);
|
||||
|
||||
// an open limit editor is someone typing: never drawn over
|
||||
await page.locator('#gatewayKeys .acc[data-key="pool"] .amodels.limit').click();
|
||||
const ed = page.locator('#gatewayKeys .acc[data-key="pool"] .key-limit-ed');
|
||||
await ed.waitFor();
|
||||
const costIn = ed.getByRole("textbox", { name: tr("Estimated cost limit, US$"), exact: true });
|
||||
await costIn.fill("31");
|
||||
spend(14, 90e6);
|
||||
await page.clock.runFor(16e3);
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("focus")));
|
||||
await page.clock.runFor(2e3);
|
||||
assert.equal(await costIn.inputValue(), "31", "the editor kept what was typed");
|
||||
assert.equal(await costIn.evaluate((e) => e === document.activeElement), true, "and the field being typed in");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user