agent-console 1.3.3: reconnect on return, sidebar dots, permission-wait, chat icon (#760)
qingnian108's follow-up to #747 and #758, on top of 1.3.2.
- A permission request still open when its turn ends is cancelled by the
daemon (manager and ACP session both), and an ACP request the Agent
withdraws ($/cancel_request, through the handler's AbortSignal) closes
as cancelled. The page waits only on cards that still show buttons, so
a finished turn no longer leaves 等待授权 with nothing to click. The
等待授权 pill scrolls to the waiting card.
- 添加到对话 uses a speech-bubble icon.
- Sidebar dot: blinks while running, green after a completed turn, red
on failure, amber while waiting.
- Wrapper: every disconnect / invalid-link end state offers Reconnect;
the last safe back URL is kept in sessionStorage (safeBack re-checked
on read). Coming back to the page (visible / focus) probes the child
for 4 s instead of waiting out timers pushed back while hidden.
Review (head 0c8ee32b): every changed source line read. 1.3.2's Codex
model_catalog_json change is kept (codex/provider.ts untouched, rebuilt
dist still carries it). No new network in tests, page text set through
textContent/React, no new timers in the page or daemon; the wrapper's
sessionStorage back passes the same loopback check (tested with an evil
stored value).
Run (mote, macOS), standalone copy of packages/agent-console:
- npm ci; npm run check OK.
- vitest: 65 files, 489 passed / 17 skipped.
- npm run build, then verify:build: committed app/ and daemon/dist
identical to the rebuild.
On the PR merged onto main 5026f636: root `bun test
packages/agent-console` 6/6, `bun scripts/check.mjs` exit 0.
Not tried: scripts/e2e-v1.mjs (Playwright, scenario 28), the page with a
live Cursor/Claude/Codex, Windows/Linux.
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
// ACP permission requests that outlive their turn (Nolan's Cursor thread, 1.2.0: 等待授权 in the top bar, no card to click).
|
||||
// Cursor asked session/request_permission, then its model stream died ("[canceled] http/2 stream closed … CANCEL") and
|
||||
// the turn ended without the request being answered or withdrawn. The request must be closed as cancelled before the
|
||||
// turn end, and a request the Agent withdraws ($/cancel_request) must close too.
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { createAcpProvider } from "../../daemon/src/providers/acp/provider.js";
|
||||
import type { ProviderSession } from "../../daemon/src/providers/types.js";
|
||||
import type { ProviderEvent } from "../../daemon/src/timeline/types.js";
|
||||
|
||||
const fixture = resolve(__dirname, "fixtures", "fake-acp-agent.mjs");
|
||||
const launch = { cmd: process.execPath, prefixArgs: [fixture] };
|
||||
let dir: string;
|
||||
|
||||
beforeAll(() => { dir = mkdtempSync(join(tmpdir(), "acp-perm-")); });
|
||||
afterAll(() => rmSync(dir, { recursive: true, force: true }));
|
||||
afterEach(() => { delete process.env.FAKE_ACP_PERM; delete process.env.FAKE_ACP_PERM_LOG; });
|
||||
|
||||
type Run = { session: ProviderSession; events: ProviderEvent[]; plog: string; done: Promise<void> };
|
||||
|
||||
async function open(mode: string): Promise<Run> {
|
||||
const plog = join(dir, `p-${Math.random().toString(36).slice(2)}.jsonl`);
|
||||
process.env.FAKE_ACP_PERM = mode;
|
||||
process.env.FAKE_ACP_PERM_LOG = plog;
|
||||
const provider = createAcpProvider({ id: "fake-perm", name: "Fake ACP", binName: "fake-acp", acpArgs: [], installHint: "" });
|
||||
const session = await provider.createSession({ threadId: "t1", cwd: dir, model: null, mode: "default", effort: null, resumeId: null, launch });
|
||||
const events: ProviderEvent[] = [];
|
||||
const done = (async () => { for await (const ev of session.events) events.push(ev); })();
|
||||
return { session, events, plog, done };
|
||||
}
|
||||
async function until(check: () => boolean, ms = 10000) {
|
||||
const end = Date.now() + ms;
|
||||
while (!check()) {
|
||||
if (Date.now() > end) throw new Error("timed out");
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
}
|
||||
}
|
||||
const answers = (r: Run) => existsSync(r.plog) ? readFileSync(r.plog, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l)) : [];
|
||||
const idx = (r: Run, type: string) => r.events.findIndex((e) => e.type === type);
|
||||
type Req = Extract<ProviderEvent, { type: "permission_request" }>;
|
||||
type Res = Extract<ProviderEvent, { type: "permission_resolved" }>;
|
||||
|
||||
describe("ACP permission requests and the end of a turn", () => {
|
||||
it("a turn that ends with the request unanswered closes it as cancelled, before turn_ended", async () => {
|
||||
const r = await open("abandon");
|
||||
try {
|
||||
await r.session.send({ text: "status", images: [] });
|
||||
await until(() => idx(r, "turn_ended") >= 0);
|
||||
const req = r.events.find((e) => e.type === "permission_request") as Req;
|
||||
const res = r.events.find((e) => e.type === "permission_resolved") as Res | undefined;
|
||||
expect(res).toMatchObject({ requestId: req.requestId, cancelled: true });
|
||||
expect(idx(r, "permission_resolved")).toBeLessThan(idx(r, "turn_ended"));
|
||||
// The Agent's request got its answer (cancelled) instead of hanging
|
||||
await until(() => answers(r).length === 1);
|
||||
expect(answers(r)[0].result).toEqual({ outcome: { outcome: "cancelled" } });
|
||||
// Answering it now is a no-op (no second resolved event)
|
||||
r.session.respond(req.requestId, { optionId: "allow-once" });
|
||||
expect(r.events.filter((e) => e.type === "permission_resolved")).toHaveLength(1);
|
||||
} finally {
|
||||
await r.session.close();
|
||||
await r.done;
|
||||
}
|
||||
}, 20000);
|
||||
|
||||
it("a request the Agent withdraws ($/cancel_request) closes as cancelled", async () => {
|
||||
const r = await open("withdraw");
|
||||
try {
|
||||
await r.session.send({ text: "status", images: [] });
|
||||
await until(() => idx(r, "turn_ended") >= 0);
|
||||
const req = r.events.find((e) => e.type === "permission_request") as Req;
|
||||
expect(r.events.find((e) => e.type === "permission_resolved")).toMatchObject({ requestId: req.requestId, cancelled: true });
|
||||
expect(idx(r, "permission_resolved")).toBeLessThan(idx(r, "turn_ended"));
|
||||
} finally {
|
||||
await r.session.close();
|
||||
await r.done;
|
||||
}
|
||||
}, 20000);
|
||||
|
||||
it("answering passes the chosen optionId through (allow-always reaches Cursor as allow-always)", async () => {
|
||||
const r = await open("answer");
|
||||
try {
|
||||
await r.session.send({ text: "status", images: [] });
|
||||
await until(() => idx(r, "permission_request") >= 0);
|
||||
const req = r.events.find((e) => e.type === "permission_request") as Req;
|
||||
r.session.respond(req.requestId, { optionId: "allow-always" });
|
||||
await until(() => idx(r, "turn_ended") >= 0);
|
||||
expect(answers(r)[0].result).toEqual({ outcome: { outcome: "selected", optionId: "allow-always" } });
|
||||
expect(r.events.filter((e) => e.type === "permission_resolved")).toEqual([
|
||||
expect.objectContaining({ requestId: req.requestId, optionId: "allow-always" }),
|
||||
]);
|
||||
} finally {
|
||||
await r.session.close();
|
||||
await r.done;
|
||||
}
|
||||
}, 20000);
|
||||
});
|
||||
@@ -4,6 +4,11 @@
|
||||
// (default: neither; matches the ACP baseline until an Agent opts in)
|
||||
// FAKE_ACP_LOG file each received session/prompt is appended to, one JSON line per prompt
|
||||
// FAKE_ACP_SESSION_LOG file each session/new|load|resume is appended to, one JSON line { method, sessionId }
|
||||
// FAKE_ACP_PERM "abandon": each prompt asks session/request_permission, then ends the turn at once without
|
||||
// waiting (Cursor when its model stream dies: "[canceled] http/2 stream closed … CANCEL");
|
||||
// "withdraw": asks, then sends $/cancel_request for it and ends the turn once the client answers
|
||||
// "answer": asks and ends the turn once the client answers (the normal path)
|
||||
// FAKE_ACP_PERM_LOG file each answer to session/request_permission is appended to, one JSON line
|
||||
// Every prompt is answered with one agent_message_chunk ("ok: <n> blocks") and stopReason end_turn.
|
||||
import { appendFileSync } from "node:fs";
|
||||
import { createInterface } from "node:readline";
|
||||
@@ -12,6 +17,10 @@ const caps = process.env.FAKE_ACP_PROMPT_CAPS ? JSON.parse(process.env.FAKE_ACP_
|
||||
const session = process.env.FAKE_ACP_SESSION ? JSON.parse(process.env.FAKE_ACP_SESSION) : {};
|
||||
const logFile = process.env.FAKE_ACP_LOG;
|
||||
const sessionLog = process.env.FAKE_ACP_SESSION_LOG;
|
||||
const permMode = process.env.FAKE_ACP_PERM;
|
||||
const permLog = process.env.FAKE_ACP_PERM_LOG;
|
||||
let nextOwnId = 9000;
|
||||
const waiting = new Map(); // our request id -> callback(response)
|
||||
const out = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\n");
|
||||
const answer = (id, result) => out({ id, result });
|
||||
const logSession = (method, sessionId) => {
|
||||
@@ -31,7 +40,14 @@ createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!m.method) return; // responses to our own (no) requests
|
||||
if (!m.method) {
|
||||
// A response to our own request (session/request_permission)
|
||||
if (permLog && waiting.has(m.id)) appendFileSync(permLog, JSON.stringify({ result: m.result, error: m.error }) + "\n");
|
||||
const cb = waiting.get(m.id);
|
||||
waiting.delete(m.id);
|
||||
cb?.(m);
|
||||
return;
|
||||
}
|
||||
const p = m.params ?? {};
|
||||
switch (m.method) {
|
||||
case "initialize":
|
||||
@@ -73,6 +89,34 @@ createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: `ok: ${p.prompt.length} blocks` } },
|
||||
},
|
||||
});
|
||||
if (permMode) {
|
||||
const ask = nextOwnId++;
|
||||
const done = () => answer(m.id, { stopReason: "end_turn" });
|
||||
waiting.set(ask, permMode === "abandon" ? () => {} : done);
|
||||
out({
|
||||
id: ask,
|
||||
method: "session/request_permission",
|
||||
params: {
|
||||
sessionId: p.sessionId,
|
||||
toolCall: { toolCallId: "tc-" + ask, title: "`git status`", kind: "execute", rawInput: {} },
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow", kind: "allow_once" },
|
||||
{ optionId: "allow-always", name: "Always", kind: "allow_always" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
},
|
||||
});
|
||||
if (permMode === "abandon") {
|
||||
out({
|
||||
method: "session/update",
|
||||
params: { sessionId: p.sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Error: RetriableError: [canceled] http/2 stream closed with error code CANCEL (0x8)" } } },
|
||||
});
|
||||
setTimeout(done, 50);
|
||||
} else if (permMode === "withdraw") {
|
||||
setTimeout(() => out({ method: "$/cancel_request", params: { requestId: ask } }), 100);
|
||||
}
|
||||
return;
|
||||
}
|
||||
return answer(m.id, { stopReason: "end_turn" });
|
||||
}
|
||||
case "session/cancel":
|
||||
|
||||
@@ -154,6 +154,24 @@ describe("AgentManager", () => {
|
||||
expect(manager.runtimeInfo(threadId)?.pending.length).toBe(0);
|
||||
}, 15000);
|
||||
|
||||
it("a turn that ends with a permission still open cancels it (Cursor stream CANCEL, 等待授权 with no card)", async () => {
|
||||
await manager.send(threadId, { text: "/perm-abandon" });
|
||||
await waitFor(async () => (await threads.get(threadId))?.status === "idle");
|
||||
// Nothing is left waiting: threads.get would otherwise hand the page a pending request for a card that shows 已取消
|
||||
expect(manager.runtimeInfo(threadId)?.pending.length).toBe(0);
|
||||
const evs = await events();
|
||||
const req = evs.find((e) => e.type === "permission_request") as { requestId: string; seq: number } | undefined;
|
||||
expect(req).toBeTruthy();
|
||||
const res = evs.find((e) => e.type === "permission_resolved" && (e as { requestId?: string }).requestId === req!.requestId) as { cancelled?: boolean; seq: number } | undefined;
|
||||
expect(res?.cancelled).toBe(true);
|
||||
const end = evs.find((e) => e.type === "turn_ended") as { seq: number } | undefined;
|
||||
expect(res!.seq).toBeLessThan(end!.seq); // written before the turn end, so a replay never sees it open
|
||||
// The next turn runs normally
|
||||
await manager.send(threadId, { text: "你好" });
|
||||
await waitFor(async () => (await events()).filter((e) => e.type === "turn_ended").length === 2);
|
||||
expect(manager.runtimeInfo(threadId)?.pending.length).toBe(0);
|
||||
}, 15000);
|
||||
|
||||
it("/exit crash → closed; the next send resumes", async () => {
|
||||
await manager.send(threadId, { text: "/exit" });
|
||||
await waitFor(async () => (await threads.get(threadId))?.status === "closed");
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// Nolan, Cursor on 1.2.0: the top bar said 等待授权 and the composer was locked ("等待你确认上面的授权请求"), but no card
|
||||
// in the timeline had buttons. His timeline had one permission_request (seq 501) with no permission_resolved: Cursor's
|
||||
// stream died ("[canceled] http/2 stream closed … CANCEL") right after asking and the turn ended "completed"; the daemon
|
||||
// kept the request in its pending list, threads.get handed it to the page, and the card (thread idle) showed 已取消.
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { applyEvent, newTimelineState, pendingRequests, reduceTimeline, type DisplayItem } from "../../web/src/timeline/reducer.js";
|
||||
import { foldTimeline, TOOL_COLLAPSE_AT } from "../../web/src/timeline/fold.js";
|
||||
|
||||
type Ev = Record<string, unknown>;
|
||||
let seq = 0;
|
||||
const tl = (evs: Ev[]) => evs.map((e) => ({ seq: ++seq, ts: seq, threadId: "t", ...e })) as never[];
|
||||
const tool = (itemId: string, extra: Ev = {}): Ev => ({ type: "tool_call", itemId, kind: "search", title: `search ${itemId}`, status: "ok", ...extra });
|
||||
const perm = (requestId: string): Ev => ({
|
||||
type: "permission_request", requestId, title: "`git status -sb; git diff --stat`", kind: "execute",
|
||||
options: [{ id: "allow-once", label: "Allow", kind: "allow_once" }, { id: "allow-always", label: "Always", kind: "allow_always" }, { id: "reject-once", label: "Reject", kind: "reject_once" }],
|
||||
});
|
||||
const permItem = (items: DisplayItem[], id: string) =>
|
||||
items.find((i) => i.kind === "permission" && i.requestId === id) as Extract<DisplayItem, { kind: "permission" }> | undefined;
|
||||
|
||||
// The shape of Nolan's thread t_mw1ubvax40e6cd around seq 501, then later turns that ran normally
|
||||
const nolan = () => tl([
|
||||
{ type: "user_message", text: "看下状态" },
|
||||
{ type: "turn_started", turnId: "u_1" },
|
||||
tool("a"),
|
||||
perm("pmp09ibgx"),
|
||||
{ type: "assistant_message", itemId: "m1", text: "Error: RetriableError: [canceled] http/2 stream closed with error code CANCEL (0x8)" },
|
||||
{ type: "turn_ended", turnId: "u_1", status: "completed" },
|
||||
{ type: "user_message", text: "继续" },
|
||||
{ type: "turn_started", turnId: "u_2" },
|
||||
perm("pjhfg5zac"),
|
||||
{ type: "permission_resolved", requestId: "pjhfg5zac", optionId: "allow-always" },
|
||||
tool("b"),
|
||||
{ type: "turn_ended", turnId: "u_2", status: "completed" },
|
||||
]);
|
||||
|
||||
describe("a permission request left open by an ended turn (等待授权 with no card)", () => {
|
||||
it("replaying 1.2 history: the orphan closes at its turn end, so nothing waits — even while a later turn runs", () => {
|
||||
for (const runtimeStatus of ["idle", "running"]) {
|
||||
const { items } = reduceTimeline(nolan(), { runtimeStatus });
|
||||
expect(permItem(items, "pmp09ibgx")?.status).toBe("cancelled");
|
||||
expect(permItem(items, "pjhfg5zac")?.status).toBe("resolved");
|
||||
expect(pendingRequests(items)).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
it("live: the turn_ended event alone closes it (before the idle status arrives)", () => {
|
||||
const st = newTimelineState();
|
||||
const evs = nolan();
|
||||
for (const e of evs.slice(0, 4)) applyEvent(st, e);
|
||||
expect(pendingRequests(st.items).map((p) => p.requestId)).toEqual(["pmp09ibgx"]);
|
||||
for (const e of evs.slice(4, 6)) applyEvent(st, e);
|
||||
expect(pendingRequests(st.items)).toEqual([]);
|
||||
});
|
||||
|
||||
it("a request of the running turn still waits, and its card has the key the top bar scrolls to", () => {
|
||||
const { items } = reduceTimeline(tl([
|
||||
{ type: "user_message", text: "x" }, { type: "turn_started", turnId: "u_3" }, tool("c"), perm("live1"),
|
||||
]), { runtimeStatus: "running" });
|
||||
expect(pendingRequests(items)).toEqual([{ requestId: "live1", kind: "permission", key: "perm:live1" }]);
|
||||
expect(items.some((i) => i.key === "perm:live1")).toBe(true);
|
||||
});
|
||||
|
||||
it("a cancelled question closes too (the daemon cancels questions with permission_resolved{cancelled})", () => {
|
||||
const { items } = reduceTimeline(tl([
|
||||
{ type: "turn_started", turnId: "u_4" },
|
||||
{ type: "question", requestId: "q1", questions: [{ id: "a", question: "?" }] },
|
||||
{ type: "permission_resolved", requestId: "q1", cancelled: true },
|
||||
]), { runtimeStatus: "running" });
|
||||
expect(pendingRequests(items)).toEqual([]);
|
||||
});
|
||||
|
||||
it("a pending card is never folded into a tool run, however long the run", () => {
|
||||
const run = (p: string, n: number) => Array.from({ length: n }, (_, i) => tool(`${p}${i}`));
|
||||
const { items } = reduceTimeline(tl([
|
||||
{ type: "turn_started", turnId: "u_5" },
|
||||
...run("x", TOOL_COLLAPSE_AT + 3),
|
||||
{ type: "reasoning", itemId: "r", text: "短" },
|
||||
perm("mid"),
|
||||
{ type: "reasoning", itemId: "r2", text: "短" },
|
||||
...run("y", TOOL_COLLAPSE_AT + 3),
|
||||
]), { runtimeStatus: "running" });
|
||||
const folded = foldTimeline(items);
|
||||
const top = folded.filter((i) => i.kind === "permission");
|
||||
expect(top.map((i) => (i as { requestId: string }).requestId)).toEqual(["mid"]);
|
||||
expect(folded.filter((i) => i.kind === "toolgroup")).toHaveLength(2);
|
||||
expect(pendingRequests(folded).map((p) => p.requestId)).toEqual(["mid"]);
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,11 @@ const wrapperUrl = pathToFileURL(join(root, "lib", "wrapper.mjs")).href;
|
||||
type Msg = { source: unknown; data: unknown };
|
||||
|
||||
/** Runs the wrapper's script against a tiny fake DOM with a controllable clock */
|
||||
async function runWrapper(hash: string, search = "", opts: { visible?: boolean } = {}) {
|
||||
async function runWrapper(
|
||||
hash: string,
|
||||
search = "",
|
||||
opts: { visible?: boolean; sessionStorage?: Record<string, string> } = {},
|
||||
) {
|
||||
const { wrapperHtml, WRAP_TIMING } = await import(/* @vite-ignore */ wrapperUrl);
|
||||
const html: string = wrapperHtml("n0nce", WRAP_TIMING);
|
||||
const script = html.split('<script nonce="n0nce">')[1]!.split("</script>")[0]!;
|
||||
@@ -25,22 +29,45 @@ async function runWrapper(hash: string, search = "", opts: { visible?: boolean }
|
||||
const els: Record<string, ReturnType<typeof el>> = { f: el("f"), m: el("m"), s: el("s"), r: el("r") };
|
||||
(els.f as unknown as { contentWindow: unknown }).contentWindow = childWin;
|
||||
let onMessage: (e: Msg) => void = () => {};
|
||||
const loc = { hash, search, replaced: null as string | null, replace(u: string) { this.replaced = u; } };
|
||||
const winOn: Record<string, (() => void)[]> = {};
|
||||
const docOn: Record<string, (() => void)[]> = {};
|
||||
const loc = {
|
||||
hash, search, replaced: null as string | null, reloaded: 0,
|
||||
replace(u: string) { this.replaced = u; },
|
||||
reload() { this.reloaded++; },
|
||||
};
|
||||
const store = new Map<string, string>(Object.entries(opts.sessionStorage ?? {}));
|
||||
const sessionStorage = {
|
||||
getItem(k: string) { return store.has(k) ? store.get(k)! : null; },
|
||||
setItem(k: string, v: string) { store.set(k, String(v)); },
|
||||
removeItem(k: string) { store.delete(k); },
|
||||
clear() { store.clear(); },
|
||||
};
|
||||
const win: Record<string, unknown> = {
|
||||
parent: parentWin,
|
||||
addEventListener: (t: string, fn: (e: Msg) => void) => { if (t === "message") onMessage = fn; },
|
||||
addEventListener: (t: string, fn: (e: Msg) => void) => {
|
||||
if (t === "message") onMessage = fn;
|
||||
else (winOn[t] ??= []).push(fn as unknown as () => void);
|
||||
},
|
||||
};
|
||||
const doc = {
|
||||
getElementById: (id: string) => els[id], documentElement: { className: "" },
|
||||
visibilityState: opts.visible === false ? "hidden" : "visible",
|
||||
addEventListener: (t: string, fn: () => void) => { (docOn[t] ??= []).push(fn); },
|
||||
};
|
||||
const doc = { getElementById: (id: string) => els[id], documentElement: { className: "" }, visibilityState: opts.visible === false ? "hidden" : "visible" };
|
||||
const DateFake = { now: () => now };
|
||||
const fn = new Function("window", "document", "location", "setInterval", "Date", "URL", "URLSearchParams", script);
|
||||
fn(win, doc, loc, (f: () => void) => { intervals.push(f); return 1; }, DateFake, URL, URLSearchParams);
|
||||
const fn = new Function("window", "document", "location", "setInterval", "Date", "URL", "URLSearchParams", "sessionStorage", script);
|
||||
fn(win, doc, loc, (f: () => void) => { intervals.push(f); return 1; }, DateFake, URL, URLSearchParams, sessionStorage);
|
||||
const tick = (ms: number, step = 1000) => { for (let t = 0; t < ms; t += step) { now += step; intervals.forEach((f) => f()); } };
|
||||
return {
|
||||
els, loc, childWin, parentWin, tick, doc,
|
||||
els, loc, childWin, parentWin, tick, doc, store,
|
||||
fromChild: (data: unknown) => onMessage({ source: childWin, data }),
|
||||
fromParent: (data: unknown) => onMessage({ source: parentWin, data }),
|
||||
fromOther: (data: unknown) => onMessage({ source: {}, data }),
|
||||
jump: (ms: number) => { now += ms; },
|
||||
hide: () => { doc.visibilityState = "hidden"; (docOn.visibilitychange ?? []).forEach((f) => f()); },
|
||||
show: () => { doc.visibilityState = "visible"; (docOn.visibilitychange ?? []).forEach((f) => f()); },
|
||||
focus: () => { (winOn.focus ?? []).forEach((f) => f()); },
|
||||
now: () => now,
|
||||
};
|
||||
}
|
||||
@@ -101,12 +128,26 @@ describe("wrapper page", () => {
|
||||
it("refuses a bad token or port, and never follows a non-Magpie back URL", async () => {
|
||||
const w1 = await runWrapper(hash({ t: "x", p: "4321", b: BACK }));
|
||||
expect(w1.els.f!.src).toBe("");
|
||||
const w2 = await runWrapper(hash({ t: TOKEN, p: "99999", b: BACK }));
|
||||
expect(w1.els.r!.hidden).toBe(false);
|
||||
expect(w1.els.r!.textContent).toBe("重新连接");
|
||||
w1.els.r!.onclick!();
|
||||
// valid #b= was stored before the early return, so Reconnect walks back through Magpie
|
||||
expect(w1.loc.replaced).toBe(BACK);
|
||||
expect(w1.loc.reloaded).toBe(0);
|
||||
|
||||
const w2 = await runWrapper(hash({ t: TOKEN, p: "99999", b: BACK }), "?lang=en");
|
||||
expect(w2.els.f!.src).toBe("");
|
||||
expect(w2.els.r!.textContent).toBe("Reconnect");
|
||||
expect(w2.els.s!.textContent).toContain("Click Reconnect");
|
||||
|
||||
const w3 = await runWrapper(hash({ t: TOKEN, p: "4321", b: "https://evil.example/_magpie/plugin/a/index.html" }));
|
||||
expect(w3.store.has("ac_wrap_back")).toBe(false);
|
||||
w3.fromChild({ ac_console: "lost", at: 5 });
|
||||
expect(w3.loc.replaced).toBeNull();
|
||||
expect(w3.els.m!.hidden).toBe(false);
|
||||
expect(w3.els.r!.hidden).toBe(false);
|
||||
w3.els.r!.onclick!();
|
||||
expect(w3.loc.reloaded).toBe(1);
|
||||
});
|
||||
|
||||
it("a reload onto a dead daemon (no alive within 12 s) goes back through the Magpie page", async () => {
|
||||
@@ -172,6 +213,181 @@ describe("wrapper page", () => {
|
||||
expect(new URL(old.loc.replaced!).searchParams.get("ac_try")).toBe(`${old.now()}.1`);
|
||||
});
|
||||
|
||||
it("remembers a safe #b= in sessionStorage and reuses it when the hash has none", async () => {
|
||||
const first = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }));
|
||||
expect(first.store.get("ac_wrap_back")).toBe(BACK);
|
||||
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321" }), "", { sessionStorage: { ac_wrap_back: BACK } });
|
||||
w.fromChild({ ac_console: "lost", at: 99 });
|
||||
const u = new URL(w.loc.replaced!);
|
||||
expect(u.origin + u.pathname).toBe("http://127.0.0.1:5000/_magpie/plugin/abc123/page/index.html");
|
||||
expect(u.searchParams.get("ac_lost")).toBe("99");
|
||||
expect(u.searchParams.has("ac_try")).toBe(false); // go(false): not an automatic try
|
||||
expect(w.loc.replaced).not.toContain(TOKEN);
|
||||
});
|
||||
|
||||
it("ignores an unsafe sessionStorage back and still offers Reconnect via reload", async () => {
|
||||
const evil = "https://evil.example/_magpie/plugin/a/index.html";
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321" }), "?lang=en", { sessionStorage: { ac_wrap_back: evil } });
|
||||
w.fromChild({ ac_console: "lost", at: 1 });
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
expect(w.els.r!.hidden).toBe(false);
|
||||
expect(w.els.r!.textContent).toBe("Reconnect");
|
||||
expect(w.els.s!.textContent).toMatch(/Click Reconnect/);
|
||||
expect(w.els.s!.textContent).toMatch(/top-bar/);
|
||||
w.els.r!.onclick!();
|
||||
expect(w.loc.reloaded).toBe(1);
|
||||
});
|
||||
|
||||
it("with no back at all, Reconnect reloads and the copy explains the Magpie top-bar fallback", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321" }));
|
||||
w.fromChild({ ac_console: "lost", at: 1 });
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
expect(w.els.r!.hidden).toBe(false);
|
||||
expect(w.els.r!.textContent).toBe("重新连接");
|
||||
expect(w.els.s!.textContent).toContain("重新连接");
|
||||
expect(w.els.s!.textContent).toContain("Agent 控制台");
|
||||
expect(w.els.s!.textContent).toContain("顶栏");
|
||||
w.els.r!.onclick!();
|
||||
expect(w.loc.reloaded).toBe(1);
|
||||
});
|
||||
|
||||
it("an invalid link with only a stored back still Reconnects through Magpie", async () => {
|
||||
const w = await runWrapper(hash({ t: "nope", p: "1" }), "", { sessionStorage: { ac_wrap_back: BACK } });
|
||||
expect(w.els.f!.src).toBe("");
|
||||
expect(w.els.r!.hidden).toBe(false);
|
||||
w.els.r!.onclick!();
|
||||
expect(w.loc.replaced).toBe(BACK);
|
||||
expect(w.loc.reloaded).toBe(0);
|
||||
});
|
||||
|
||||
it("coming back visible after a long hidden spell: a child that answers is left alone", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }));
|
||||
w.fromChild({ ac_console: "alive" });
|
||||
w.hide();
|
||||
w.tick(600_000, 60_000); // ten minutes hidden, heartbeats throttled away
|
||||
w.show();
|
||||
w.tick(2000);
|
||||
w.fromChild({ ac_console: "alive" }); // next heartbeat after unthrottling
|
||||
w.tick(10_000, 2000);
|
||||
w.fromChild({ ac_console: "alive" });
|
||||
w.tick(2000);
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
expect(w.loc.reloaded).toBe(0);
|
||||
// focus while it's fresh does nothing either
|
||||
w.focus();
|
||||
w.tick(5000);
|
||||
w.fromChild({ ac_console: "alive" });
|
||||
w.tick(5000);
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
});
|
||||
|
||||
it("coming back visible with a silent child recovers within the probe window, not after silentMs", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }));
|
||||
w.fromChild({ ac_console: "alive" });
|
||||
const heard = w.now();
|
||||
w.hide();
|
||||
w.tick(600_000, 60_000);
|
||||
w.show();
|
||||
w.tick(3000);
|
||||
expect(w.loc.replaced).toBeNull(); // still giving it its heartbeat
|
||||
w.tick(1000);
|
||||
const u = new URL(w.loc.replaced!);
|
||||
expect(u.searchParams.get("ac_lost")).toBe(String(heard));
|
||||
expect(u.searchParams.get("ac_try")).toMatch(/^\d+\.1$/);
|
||||
expect(w.loc.replaced).not.toContain(TOKEN);
|
||||
});
|
||||
|
||||
it("window focus after sleep (timers suspended) also checks at once", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }));
|
||||
w.fromChild({ ac_console: "alive" });
|
||||
w.jump(3_600_000); // asleep: no ticks, no heartbeats
|
||||
w.focus();
|
||||
w.tick(1000); // the big gap bumps lastAlive; the probe still runs from the real heardAt
|
||||
w.tick(3000);
|
||||
expect(w.loc.replaced).not.toBeNull();
|
||||
});
|
||||
|
||||
it("never alive: loaded hidden and shown after bootMs recovers within the probe window", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }), "", { visible: false });
|
||||
w.tick(60_000);
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
w.show();
|
||||
w.tick(4000);
|
||||
const u = new URL(w.loc.replaced!);
|
||||
expect(u.searchParams.has("ac_lost")).toBe(false);
|
||||
expect(u.searchParams.get("ac_try")).toMatch(/^\d+\.1$/);
|
||||
// shown before bootMs: no early probe, the normal 12 s boot window applies
|
||||
const e = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }), "", { visible: false });
|
||||
e.tick(3000);
|
||||
e.show();
|
||||
e.tick(5000);
|
||||
expect(e.loc.replaced).toBeNull();
|
||||
e.fromChild({ ac_console: "alive" });
|
||||
e.tick(5000);
|
||||
expect(e.loc.replaced).toBeNull();
|
||||
});
|
||||
|
||||
it("a probe is dropped if the page hides again before it ends", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }));
|
||||
w.fromChild({ ac_console: "alive" });
|
||||
w.hide();
|
||||
w.tick(120_000, 60_000);
|
||||
w.show();
|
||||
w.tick(2000);
|
||||
w.hide();
|
||||
w.tick(60_000);
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
});
|
||||
|
||||
it("auto tries used up: coming back counts as clicking Reconnect (once)", async () => {
|
||||
const start = 1_800_000_000_000 - 30_000;
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }), `?ac_try=${start}.3`);
|
||||
w.fromChild({ ac_console: "lost", at: 1 });
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
expect(w.els.r!.hidden).toBe(false);
|
||||
w.hide();
|
||||
w.show();
|
||||
const u = new URL(w.loc.replaced!);
|
||||
expect(u.origin + u.pathname).toBe("http://127.0.0.1:5000/_magpie/plugin/abc123/page/index.html");
|
||||
expect(u.searchParams.has("ac_try")).toBe(false); // go(false), like the button
|
||||
expect(w.els.r!.disabled).toBe(true);
|
||||
w.loc.replaced = null;
|
||||
w.focus();
|
||||
w.els.r!.onclick!();
|
||||
expect(w.loc.replaced).toBeNull(); // already on its way: not twice
|
||||
});
|
||||
|
||||
it("no back at all: coming back to the end state reloads like the button", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321" }));
|
||||
w.fromChild({ ac_console: "lost", at: 1 });
|
||||
expect(w.loc.reloaded).toBe(0);
|
||||
w.focus();
|
||||
expect(w.loc.reloaded).toBe(1);
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
w.show();
|
||||
expect(w.loc.reloaded).toBe(1);
|
||||
});
|
||||
|
||||
it("invalid link: coming back runs Reconnect through the stored back; unsafe stored back is never followed", async () => {
|
||||
const w = await runWrapper(hash({ t: "nope", p: "1" }), "", { sessionStorage: { ac_wrap_back: BACK } });
|
||||
w.show();
|
||||
expect(w.loc.replaced).toBe(BACK);
|
||||
const evil = await runWrapper(hash({ t: "nope", p: "1", b: "https://evil.example/_magpie/plugin/a/index.html" }), "",
|
||||
{ sessionStorage: { ac_wrap_back: "http://evil.example/_magpie/plugin/a/index.html" } });
|
||||
evil.focus();
|
||||
expect(evil.loc.replaced).toBeNull();
|
||||
expect(evil.loc.reloaded).toBe(1);
|
||||
});
|
||||
|
||||
it("hidden page: focus/visibility events while hidden do nothing", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }), "", { visible: false });
|
||||
w.tick(60_000);
|
||||
w.focus();
|
||||
w.tick(10_000);
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
});
|
||||
|
||||
it("relays only the Magpie theme protocol", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }));
|
||||
w.fromChild({ magpie: 1, id: 7, method: "hello", extra: "x" });
|
||||
|
||||
Reference in New Issue
Block a user