amp-usage 0.1.2: an open page survives the plugin host restarting (#1099)

amp-usage keeps its service token across a host restart; a held lock is waited for, and the page polls with a timeout and clears its notice on recovery. Fixes #1098.

Reviewed at 8a6a66162; 585c921ae only drops a docs file.
Run (WSL, Bun 1.4.2, temp HOME): amp-usage tests 53/53, bun scripts/check.mjs exit 0.
Broken by hand: main's lib/server.mjs fails tests 1 and 2; main's index.mjs fails test 3.
Not tried: a real Amp account through a restarted magpie.
This commit is contained in:
ming_jiang
2026-11-13 20:28:35 +08:00
committed by GitHub
parent c441017527
commit c2f54a8e74
8 changed files with 261 additions and 43 deletions
+3 -2
View File
@@ -74,7 +74,7 @@ magpie plugin add /absolute/path/to/plugins/packages/amp-usage
- `threadDirs`:本地线程目录的绝对路径数组;空数组使用默认目录,不递归扫描、不跟随目录项符号链接。
- `excludedThreadIds` / `excludedModels`:精确排除的线程 ID 或模型名。
Magpie 的远程网页通过声明的页面服务代理访问;不要求向网络开放采集服务端口。页面 API 使用每次启动生成的随机令牌,校验 Host 和 Origin,并限制请求大小。
Magpie 的远程网页通过声明的页面服务代理访问;不要求向网络开放采集服务端口。页面 API 使用随机令牌,服务重启(如其他插件更新导致插件宿主重启)后沿用,已打开的页面无需重新打开;同时校验 Host 和 Origin,并限制请求大小。
## 本地状态与隐私
@@ -83,7 +83,8 @@ Magpie 的远程网页通过声明的页面服务代理访问;不要求向网
- `state.json`:已确认记录指纹、待稳定记录、网关重复的判定。
- `cloud-index.json`:线程导出检查点。
- `cloud/`:只包含用量、消息标识、完成状态、时间和各轮发送时间的精简导出。
- `collector.lock`:防止多个服务同时维护同一检查点;进程退出时删除,残留的陈旧或损坏的锁在下次启动时自动接管。
- `collector.lock`:防止多个服务同时维护同一检查点;进程退出时删除,残留的陈旧或损坏的锁在下次启动时自动接管。锁或端口仍被活着的实例占用时(如 Magpie 更新插件后,旧插件宿主还在完成调用,最长 10 分钟),服务每 5 秒重试一次,最长 11 分钟,期间不阻塞宿主加载其他插件。
- `service-token.json`:页面 API 令牌;删除或损坏时下次启动重新生成,已打开的页面需要重新打开。
Amp 导出命令的完整结果会短暂经过内存,但不保存提示词、回复、工具内容、项目路径或账号密钥。页面不会展示线程原文。日志解析失败时保留原状态,不静默清空去重数据。看板的数字来自插件自己读到的 Amp 记录,不是重新查询的 Magpie 账本;费用仍在 Magpie 的用量页查看。页面支持中文和英文,并跟随 Magpie 的主题。
+37 -8
View File
@@ -1,6 +1,14 @@
import { join } from "node:path";
import { startServer } from "./lib/server.mjs";
let running, current;
// When any plugin updates, Magpie starts a new host at once but lets the old
// one finish its calls for up to 10 minutes. Until then the old service holds
// the lock and the port, so this one waits for them instead of failing.
const retryEvery = 5_000;
const retryFor = 11 * 60_000;
const held = (e) => e?.code === "ELOCKED" || e?.code === "EADDRINUSE";
let running, current, ready;
export default {
id: "amp-usage",
async server(input, options) {
@@ -12,20 +20,41 @@ export default {
if (wanted !== current) {
const previous = running;
current = wanted;
let waiting;
const waited = new Promise((resolve) => (waiting = resolve));
running = (async () => {
await (await previous?.catch(() => null))?.close();
return startServer({
port: Number(options.port ?? 3497),
configDir: input.directory,
dataDir: join(input.directory, "amp-usage"),
options,
});
const until = Date.now() + retryFor;
for (;;) {
try {
return await startServer({
port: Number(options.port ?? 3497),
configDir: input.directory,
dataDir: join(input.directory, "amp-usage"),
options,
});
} catch (e) {
if (!held(e) || current !== wanted) throw e;
if (Date.now() >= until) {
console.error(`amp-usage: gave up waiting: ${e.message}`);
throw e;
}
if (waiting) {
console.warn(`amp-usage: ${e.message} Retrying.`);
waiting();
waiting = null;
}
await new Promise((resolve) => setTimeout(resolve, retryEvery));
}
}
})();
running.catch(() => {
if (current === wanted) current = undefined;
});
// A service that must wait does not hold up the host's plugin load.
ready = Promise.race([running, waited]);
}
await running;
await ready;
return {};
},
};
+3 -1
View File
@@ -51,9 +51,11 @@ export async function acquireLock(dir) {
await unlink(path).catch(() => {});
continue;
}
throw new Error(
const held = new Error(
"Another Amp collector is running for this Magpie configuration.",
);
held.code = "ELOCKED"; // a node-style code, not one the page shows
throw held;
}
}
throw new Error("Could not acquire collector lock.");
+21 -12
View File
@@ -4,8 +4,21 @@ import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { createCollector, acquireLock } from "./collector.mjs";
import { readJSON, writeJSON } from "./storage.mjs";
const ui = fileURLToPath(new URL("../ui/", import.meta.url));
// The token outlives the service: Magpie restarts its plugin host whenever
// any plugin updates, and a page already open must keep its token.
async function serviceToken(dataDir) {
const path = join(dataDir, "service-token.json");
const kept = await readJSON(path, null).catch(() => null);
if (/^[a-f0-9]{64}$/.test(kept?.token)) return kept.token;
const token = randomBytes(32).toString("hex");
await writeJSON(path, { token });
return token;
}
export async function startServer({
port = 3497,
dataDir,
@@ -16,15 +29,15 @@ export async function startServer({
if (!Number.isInteger(port) || port < 0 || port > 65535)
throw new Error("Invalid service port.");
const release = await acquireLock(dataDir);
let collector;
let collector, token;
try {
token = await serviceToken(dataDir);
collector =
injected || (await createCollector({ dataDir, configDir, options }));
} catch (e) {
await release();
throw e;
}
const token = randomBytes(32).toString("hex");
let actualPort;
const send = (res, code, body, type = "application/json") => {
res.writeHead(code, {
@@ -48,17 +61,18 @@ export async function startServer({
!origin || origin === "null" || origin === `http://${host}`;
if (!originOK) return send(res, 403, { error: "Invalid origin." });
if (url.pathname.startsWith("/api/")) {
// Sandboxed pages must also be able to read authentication failures.
res.setHeader(
"Access-Control-Allow-Origin",
origin || `http://${host}`,
);
res.setHeader("Vary", "Origin");
if (req.method === "OPTIONS") {
res.setHeader(
"Access-Control-Allow-Origin",
origin || `http://${host}`,
);
res.setHeader(
"Access-Control-Allow-Headers",
"Content-Type, X-Amp-Usage-Token",
);
res.setHeader("Access-Control-Allow-Methods", "GET, POST");
res.setHeader("Vary", "Origin");
return send(res, 204, "", "text/plain");
}
const given = Buffer.from(
@@ -73,11 +87,6 @@ export async function startServer({
error: "Reopen the Amp usage page to reconnect.",
code: "reconnect",
});
res.setHeader(
"Access-Control-Allow-Origin",
origin || `http://${host}`,
);
res.setHeader("Vary", "Origin");
if (url.pathname === "/api/status" && req.method === "GET")
return send(res, 200, collector.view());
if (req.method !== "POST")
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/page-amp-usage",
"version": "0.1.1",
"version": "0.1.2",
"description": "An Amp usage board in Magpie's window, with a local background service that can sync Amp usage into Magpie's usage ledger.",
"type": "module",
"main": "./index.mjs",
+102 -9
View File
@@ -1,10 +1,13 @@
import { request } from "node:http";
import { createServer as createNetServer } from "node:net";
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, rm } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { startServer } from "../lib/server.mjs";
import { acquireLock } from "../lib/collector.mjs";
import plugin from "../index.mjs";
test("loopback service protects every API and accepts authenticated sandbox requests", async (t) => {
const dir = await mkdtemp(join(tmpdir(), "amp-service-"));
@@ -51,17 +54,30 @@ test("loopback service protects every API and accepts authenticated sandbox requ
const token = root.body.match(
/name="service-token" content="([a-f0-9]+)"/,
)[1];
const denied = await fetch(base + "/api/status");
const denied = await fetch(base + "/api/status", {
headers: { origin: "null", "x-amp-usage-token": "stale" },
});
assert.equal(denied.status, 403);
assert.equal(denied.headers.get("access-control-allow-origin"), "null");
assert.equal(denied.headers.get("vary"), "Origin");
assert.equal((await denied.json()).code, "reconnect");
assert.equal(
(
await fetch(base + "/api/status", {
headers: { "x-amp-usage-token": token, origin: "https://evil.test" },
})
).status,
403,
);
const staleRefresh = await fetch(base + "/api/refresh", {
method: "POST",
headers: {
origin: "null",
"x-amp-usage-token": "stale",
"content-type": "application/json",
},
body: "{}",
});
assert.equal(staleRefresh.status, 403);
assert.equal(staleRefresh.headers.get("access-control-allow-origin"), "null");
assert.equal(scanned, 0);
const foreign = await fetch(base + "/api/status", {
headers: { "x-amp-usage-token": token, origin: "https://evil.test" },
});
assert.equal(foreign.status, 403);
assert.equal(foreign.headers.get("access-control-allow-origin"), null);
const badHost = await new Promise((resolve, reject) => {
const req = request(
base + "/api/status",
@@ -102,3 +118,80 @@ test("loopback service protects every API and accepts authenticated sandbox requ
);
assert.equal((await fetch(base + "/unknown")).status, 404);
});
test("a page opened before the service restarts keeps working", async (t) => {
const dir = await mkdtemp(join(tmpdir(), "amp-service-"));
const fake = { view: () => ({ phase: "idle" }), close: async () => {} };
const tokenOf = async (s) => {
const html = await new Promise((resolve, reject) => {
const req = request(
`http://127.0.0.1:${s.port}/`,
{ headers: { "sec-fetch-mode": "navigate" } },
(res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("end", () => resolve(body));
},
);
req.on("error", reject);
req.end();
});
return html.match(/name="service-token" content="([a-f0-9]+)"/)[1];
};
const first = await startServer({ port: 0, dataDir: dir, collector: fake });
const token = await tokenOf(first);
await first.close();
const second = await startServer({ port: 0, dataDir: dir, collector: fake });
t.after(async () => {
await second.close();
await rm(dir, { recursive: true, force: true });
});
const r = await fetch(`http://127.0.0.1:${second.port}/api/status`, {
headers: { origin: "null", "x-amp-usage-token": token },
});
assert.equal(r.status, 200);
assert.equal(await tokenOf(second), token);
});
test("a service whose lock is still held waits for it without blocking the host", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const warned = t.mock.method(console, "warn", () => {});
const dir = await mkdtemp(join(tmpdir(), "amp-service-"));
const port = await new Promise((resolve) => {
const s = createNetServer().listen(0, "127.0.0.1", () => {
const { port } = s.address();
s.close(() => resolve(port));
});
});
const status = () =>
new Promise((resolve) => {
const req = request(`http://127.0.0.1:${port}/`, (res) => {
res.resume();
resolve(res.statusCode);
});
req.on("error", () => resolve(0));
req.end();
});
// A retiring host's service, as Magpie's update restart leaves it.
const release = await acquireLock(join(dir, "amp-usage"));
t.after(async () => {
// An invalid port fails at once, after closing the service it replaces.
await assert.rejects(plugin.server({ directory: dir }, { port: -1 }));
await rm(dir, { recursive: true, force: true });
});
assert.deepEqual(await plugin.server({ directory: dir }, { port }), {});
assert.equal(warned.mock.callCount(), 1);
assert.equal(await status(), 0);
t.mock.timers.tick(5_000);
for (let i = 0; i < 50; i++) await new Promise((r) => setImmediate(r));
assert.equal(await status(), 0);
await release();
t.mock.timers.tick(5_000);
let code = 0;
for (let i = 0; i < 200 && !code; i++) {
await new Promise((r) => setImmediate(r));
code = await status();
}
assert.equal(code, 200);
assert.equal(warned.mock.callCount(), 1);
});
+82 -9
View File
@@ -47,20 +47,27 @@ test("an unknown code reads as the generic message, never as the code", () => {
});
// Opens the page on a bare stand-in for the browser, answers its status poll
// with a scan finished `ago` ms before, and returns the API paths it called.
async function open(ago) {
// with a scan finished `ago` ms before. Timers are advanced explicitly.
const settle = async () => {
for (let i = 0; i < 20; i++) await new Promise((r) => setImmediate(r));
};
async function open(ago, fetchImpl) {
const element = () => ({
children: [],
dataset: {},
style: {},
classList: { toggle() {} },
append() {},
replaceChildren() {},
replaceChildren(...children) {
this.children = children;
},
setAttribute() {},
addEventListener() {},
});
const elements = new Map();
const called = [];
const timers = new Map();
let tick;
const status = {
phase: "idle",
lastScan: new Date(Date.now() - ago).toISOString(),
@@ -83,23 +90,89 @@ async function open(ago) {
matchMedia: () => ({ matches: false }),
atob,
localStorage: { getItem: () => null, setItem() {} },
setInterval() {},
setInterval(fn) {
tick = fn;
},
setTimeout(fn, ms) {
timers.set(fn, ms);
return fn;
},
clearTimeout(id) {
timers.delete(id);
},
AbortController,
AmpUsage: scope.AmpUsage,
fetch: async (url) => {
fetch: async (url, init) => {
called.push(new URL(url).pathname);
if (fetchImpl) return fetchImpl(url, init, status);
return { ok: true, json: async () => status };
},
};
new Function(...Object.keys(page), await read("../ui/app.js"))(
...Object.values(page),
);
for (let i = 0; i < 20; i++) await new Promise((r) => setImmediate(r));
return called;
await settle();
return { called, elements, tick, timers };
}
test("with nothing kept, the open page refreshes once a scan is 5 minutes old", async () => {
assert.deepEqual(await open(4 * 60_000), ["/api/status"]);
assert.deepEqual(await open(6 * 60_000), ["/api/status", "/api/refresh"]);
assert.deepEqual((await open(4 * 60_000)).called, ["/api/status"]);
assert.deepEqual((await open(6 * 60_000)).called, [
"/api/status",
"/api/refresh",
]);
});
test("a stalled status request times out without overlapping polls and recovers", async () => {
let first = true;
const page = await open(0, async (url, { signal }, status) => {
if (!first) return { ok: true, json: async () => status };
first = false;
return new Promise((resolve, reject) => {
signal.addEventListener("abort", () => reject(new Error("aborted")));
});
});
await page.tick();
assert.deepEqual(page.called, ["/api/status"]);
assert.equal(page.timers.size, 1);
const [[timeout, ms]] = page.timers;
assert.equal(ms, 10_000);
timeout();
await settle();
assert.equal(page.elements.get("errors").hidden, false);
assert.equal(page.timers.size, 0);
await page.tick();
assert.equal(page.elements.get("errors").hidden, true);
});
test("a successful status poll clears a transient refresh failure", async () => {
let failRefresh = true;
const page = await open(0, async (url, init, status) => {
if (new URL(url).pathname.endsWith("refresh") && failRefresh)
throw new Error("connection reset");
return { ok: true, json: async () => status };
});
await page.elements.get("refresh").onclick();
assert.equal(page.elements.get("errors").hidden, false);
failRefresh = false;
await page.tick();
assert.equal(page.elements.get("errors").hidden, true);
assert.equal(page.elements.get("refresh").disabled, false);
});
test("a late poll failure cannot overwrite a newer successful refresh", async () => {
let rejectPoll;
const page = await open(0, async (url, init, status) => {
if (new URL(url).pathname.endsWith("status"))
return new Promise((resolve, reject) => {
rejectPoll = reject;
});
return { ok: true, json: async () => status };
});
await page.elements.get("refresh").onclick();
rejectPoll(new Error("connection reset"));
await settle();
assert.equal(page.elements.get("errors").hidden, true);
});
test("the page loads its words before its script", async () => {
+12 -1
View File
@@ -120,9 +120,12 @@ $("auto").value = auto;
async function api(path, body) {
let r, result;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10_000);
// Errors are codes the page words itself; see W.err.
try {
r = await fetch(new URL(`api/${path}`, location.href), {
signal: controller.signal,
method: body === undefined ? "GET" : "POST",
headers: {
"X-Amp-Usage-Token": token,
@@ -133,6 +136,8 @@ async function api(path, body) {
result = await r.json();
} catch {
throw new Error("unreachable");
} finally {
clearTimeout(timeout);
}
if (!r.ok) throw new Error(result.code || "unexpected");
return result;
@@ -352,12 +357,16 @@ for (const id of ["from", "to"])
};
let left = Infinity;
let polling = false;
async function poll() {
if (polling || busy) return;
polling = true;
const mine = turn;
try {
const s = await api("status");
// A reply that raced an action is older than what the action returned.
if (busy || mine !== turn) return;
if (failure === "unreachable") failure = "";
render(s);
if (s.phase !== "idle") return;
const age = s.lastScan ? Date.now() - Date.parse(s.lastScan) : Infinity;
@@ -368,7 +377,9 @@ async function poll() {
void act(read);
}
} catch (e) {
if (!busy) errors([e.message]);
if (!busy && mine === turn) errors([e.message]);
} finally {
polling = false;
}
}
void poll();