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:
@@ -103,7 +103,7 @@ The daemon can run Agents with full access to your machine, so the token that un
|
||||
- **Host is checked on every request and WebSocket upgrade** (gate and daemon): it must be `127.0.0.1:<port>` or `localhost:<port>` with the actually bound port, otherwise 421. This blocks DNS rebinding, where the attacker's requests carry no `Origin` at all.
|
||||
- The gate answers only `GET /open?k=<gate key>` (the daemon token is not accepted there) and `GET /app` (1.3, below), refuses any request that carries an `Origin` header, and sends `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`.
|
||||
- WebSocket connections must send `hello` with the token within 5 seconds, otherwise they are closed with code 4401.
|
||||
- **Coming back after sleep / a daemon restart (1.3).** Before 1.3 the plugin frame sat on the daemon's random port; when the daemon was gone after sleep and the WebView reloaded the frame, it showed "127.0.0.1 拒绝连接" with none of our script left to recover. Now `/open` redirects to the gate's own `GET /app`, a static page that frames the daemon page, so a reload lands on the stable gate port. The daemon page (told by `w=1`) posts `{ac_console:"alive"}` to it every 2 s while its WebSocket is open and `{ac_console:"lost"}` after 5 s without it; no alive within 12 s (6 s after the child frame loaded), a lost, or 15 s of silence while visible (time the wrapper's own timers were suspended doesn't count) sends the frame back through the Magpie page (`b`, as below), which restarts the daemon. At most 3 automatic tries in 2 minutes (`ac_try`), then a button. The wrapper holds no secret of its own: the token arrives only in its fragment and goes on only in the child's fragment, the gate key never reaches it, the child is always `http://127.0.0.1:<integer port>/`, `b` passes the same loopback Magpie-page check, only the Magpie theme protocol is relayed (theme events and hello answers down, the hello call up, messages checked by `event.source`), and it is served with a per-response nonce CSP (`default-src 'none'`, `frame-src http://127.0.0.1:*`, and `frame-ancestors 'self' http://127.0.0.1:* http://localhost:* http://[::1]:* http://wails.localhost:* wails:`, so only a loopback page or Magpie's own desktop window can frame it). Host and Origin checks apply to `/app` like to `/open`.
|
||||
- **Coming back after sleep / a daemon restart (1.3).** Before 1.3 the plugin frame sat on the daemon's random port; when the daemon was gone after sleep and the WebView reloaded the frame, it showed "127.0.0.1 拒绝连接" with none of our script left to recover. Now `/open` redirects to the gate's own `GET /app`, a static page that frames the daemon page, so a reload lands on the stable gate port. The daemon page (told by `w=1`) posts `{ac_console:"alive"}` to it every 2 s while its WebSocket is open and `{ac_console:"lost"}` after 5 s without it; no alive within 12 s (6 s after the child frame loaded), a lost, or 15 s of silence while visible (time the wrapper's own timers were suspended doesn't count) sends the frame back through the Magpie page (`b`, as below), which restarts the daemon. At most 3 automatic tries in 2 minutes (`ac_try`), then a button. Coming back to the page (`visibilitychange` → visible, or window focus) checks at once instead of waiting out the timers pushed back while hidden: if the child never said alive within 12 s of loading or its last real alive is older than 15 s, it gets 4 s (two heartbeats) to speak up before the same recovery runs; a child that answers is left alone. If a disconnect end state is showing, coming back counts as clicking Reconnect, also when the automatic tries are used up. The wrapper holds no secret of its own: the token arrives only in its fragment and goes on only in the child's fragment, the gate key never reaches it, the child is always `http://127.0.0.1:<integer port>/`, `b` passes the same loopback Magpie-page check, only the Magpie theme protocol is relayed (theme events and hello answers down, the hello call up, messages checked by `event.source`), and it is served with a per-response nonce CSP (`default-src 'none'`, `frame-src http://127.0.0.1:*`, and `frame-ancestors 'self' http://127.0.0.1:* http://localhost:* http://[::1]:* http://wails.localhost:* wails:`, so only a loopback page or Magpie's own desktop window can frame it). Host and Origin checks apply to `/app` like to `/open`.
|
||||
- **Coming back after a plugin host restart.** Magpie restarts its plugin host from time to time; the old host's daemon exits with it and the new host has a new gate key. `boot.js` passes its own page URL to the gate as `back`; the gate accepts it only if it is a loopback `/_magpie/plugin/<id>/index.html` URL and forwards it **only in the fragment** (`#t=…&b=…`). When the daemon page can't reconnect for 5 seconds (or on 重试 / Retry) it navigates back to that page, which reads the fresh `session.js` and opens the new gate. To tell a live host's `session.js` from one a killed host left behind (a hard kill can't delete it), the file carries `ts` and `beat`: from the first page open on, the host rewrites it every 4 s, and after a lost connection `boot.js` only takes a file written after the loss; a host that was never opened doesn't rewrite it, and a new host deletes a file whose writer (pid in `session-owner.json`, outside the page folder) is gone before Magpie serves the page. The daemon page checks the URL again before following it, so it is never an open redirect, and the token never leaves its own fragment.
|
||||
|
||||
### Preview proxy (1.2)
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+51
-8
@@ -712,6 +712,22 @@ async function scriptPerm(ctx) {
|
||||
emit({ type: "tool_call", itemId: "p1", kind: "bash", title: "\u8FD0\u884C npm test", status: "ok", output: "\u2713 12 \u4E2A\u6D4B\u8BD5\u901A\u8FC7", exitCode: 0, durationMs: 500 });
|
||||
emit({ type: "assistant_message", itemId: "pm", text: "\u6D4B\u8BD5\u901A\u8FC7\u4E86\u3002" });
|
||||
}
|
||||
async function scriptPermAbandon(ctx) {
|
||||
const { emit } = ctx;
|
||||
emit({
|
||||
type: "permission_request",
|
||||
requestId: "perm-" + rid(),
|
||||
title: "\u8FD0\u884C git status",
|
||||
kind: "execute",
|
||||
detail: { command: "git status" },
|
||||
options: [
|
||||
{ id: "allow-once", label: tr("perm.allow"), kind: "allow_once" },
|
||||
{ id: "reject-once", label: tr("perm.deny"), kind: "reject_once" }
|
||||
]
|
||||
});
|
||||
await sleepAbortable(200, ctx);
|
||||
emit({ type: "assistant_message", itemId: "pa", text: "Error: RetriableError: [canceled] http/2 stream closed with error code CANCEL (0x8)" });
|
||||
}
|
||||
async function scriptPlan(ctx) {
|
||||
const { emit } = ctx;
|
||||
emit({
|
||||
@@ -801,6 +817,7 @@ async function scriptExit(_ctx) {
|
||||
}
|
||||
function pickScript(text) {
|
||||
const t = text.trim();
|
||||
if (t.startsWith("/perm-abandon")) return scriptPermAbandon;
|
||||
if (t.startsWith("/perm")) return scriptPerm;
|
||||
if (t.startsWith("/plan")) return scriptPlan;
|
||||
if (t.startsWith("/ask")) return scriptAsk;
|
||||
@@ -4460,7 +4477,7 @@ function registerAcpClientHandlers(app, bridge) {
|
||||
detail: tc.rawInput ?? void 0,
|
||||
options
|
||||
});
|
||||
const answer = await bridge.waitFor(requestId);
|
||||
const answer = await bridge.waitFor(requestId, ctx.signal);
|
||||
if (answer.cancelled) return { outcome: { outcome: "cancelled" } };
|
||||
const optionId = answer.optionId ?? options[0]?.id;
|
||||
if (!optionId) return { outcome: { outcome: "cancelled" } };
|
||||
@@ -4796,7 +4813,7 @@ var init_session3 = __esm({
|
||||
const app = client({ name: "magpie-agent-console" });
|
||||
registerAcpClientHandlers(app, {
|
||||
push: (ev) => this.q.push(ev),
|
||||
waitFor: (id2) => this.waitPerm(id2),
|
||||
waitFor: (id2, signal) => this.waitPerm(id2, signal),
|
||||
autoAcceptPermissions: () => this.cursorAutoReview
|
||||
});
|
||||
const stream = acpStreamFromChild(this.child);
|
||||
@@ -5009,11 +5026,21 @@ var init_session3 = __esm({
|
||||
await this.applySessionModel(this.o.model);
|
||||
await this.applyCursorAutoReviewConfig(false);
|
||||
}
|
||||
waitPerm(requestId) {
|
||||
waitPerm(requestId, signal) {
|
||||
return new Promise((resolve4) => {
|
||||
this.permPending.set(requestId, resolve4);
|
||||
if (signal?.aborted) this.cancelPerm(requestId);
|
||||
else signal?.addEventListener("abort", () => this.cancelPerm(requestId), { once: true });
|
||||
});
|
||||
}
|
||||
/** Close an open permission request as cancelled (answer the Agent's request and tell the manager) */
|
||||
cancelPerm(requestId) {
|
||||
const r = this.permPending.get(requestId);
|
||||
if (!r) return;
|
||||
this.permPending.delete(requestId);
|
||||
r({ cancelled: true });
|
||||
this.q.push({ type: "permission_resolved", requestId, cancelled: true });
|
||||
}
|
||||
respond(requestId, answer) {
|
||||
const r = this.permPending.get(requestId);
|
||||
if (r) {
|
||||
@@ -5071,6 +5098,7 @@ var init_session3 = __esm({
|
||||
});
|
||||
}
|
||||
endTurn(ev) {
|
||||
for (const id2 of [...this.permPending.keys()]) this.cancelPerm(id2);
|
||||
this.q.push(ev);
|
||||
this.activeTurnId = null;
|
||||
this.running = false;
|
||||
@@ -9169,6 +9197,7 @@ var AgentManager = class {
|
||||
rt.interruptTimer = null;
|
||||
}
|
||||
if (ev.turnId && ev.turnId !== "unknown") rt.endedTurnIds.add(ev.turnId);
|
||||
await this.cancelPending(threadId, rt, { tellSession: true });
|
||||
rt.coalescer.dispose();
|
||||
rt.coalescer = this.newCoalescer(threadId);
|
||||
await this.appendRaw(threadId, ev);
|
||||
@@ -9248,15 +9277,29 @@ var AgentManager = class {
|
||||
}
|
||||
return n;
|
||||
}
|
||||
/** Cancel every open permission/question: persisted as permission_resolved{cancelled} (the page marks the card
|
||||
* 已取消 and stops waiting). tellSession: also answer the provider's own waiter (an Agent that ended its turn without
|
||||
* withdrawing the request would otherwise keep a dangling promise); its echo is dropped because rt.pending is empty. */
|
||||
async cancelPending(threadId, rt, opts) {
|
||||
if (!rt.pending.size) return;
|
||||
const open = [...rt.pending.values()];
|
||||
rt.pending.clear();
|
||||
for (const p of open) {
|
||||
await this.appendRaw(threadId, { type: "permission_resolved", requestId: p.requestId, cancelled: true });
|
||||
p.resolve({ cancelled: true });
|
||||
if (opts.tellSession) {
|
||||
try {
|
||||
rt.session?.respond(p.requestId, { cancelled: true });
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// ---- interrupt ----
|
||||
async interrupt(threadId) {
|
||||
const rt = this.rt(threadId);
|
||||
if (!rt.session || rt.status !== "running") return;
|
||||
for (const [id2, p] of rt.pending) {
|
||||
await this.appendRaw(threadId, { type: "permission_resolved", requestId: id2, cancelled: true });
|
||||
p.resolve({ cancelled: true });
|
||||
}
|
||||
rt.pending.clear();
|
||||
await this.cancelPending(threadId, rt, { tellSession: false });
|
||||
await rt.session.interrupt();
|
||||
const turnId = rt.currentTurnId;
|
||||
rt.interruptTimer = setTimeout(() => {
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
@@ -491,6 +491,11 @@ export class AgentManager {
|
||||
rt.interruptTimer = null;
|
||||
}
|
||||
if (ev.turnId && ev.turnId !== "unknown") rt.endedTurnIds.add(ev.turnId);
|
||||
// A request the Agent left open when its turn ended (Cursor: the model stream died with "[canceled] http/2 stream
|
||||
// closed", the request was never answered or withdrawn) can no longer be answered: cancel it before the turn end
|
||||
// is written. Otherwise it stays in rt.pending, threads.get hands it to the page, and the top bar says 等待授权
|
||||
// with no card to click (the card itself shows 已取消 because the thread is idle).
|
||||
await this.cancelPending(threadId, rt, { tellSession: true });
|
||||
rt.coalescer.dispose();
|
||||
rt.coalescer = this.newCoalescer(threadId);
|
||||
await this.appendRaw(threadId, ev);
|
||||
@@ -578,16 +583,28 @@ export class AgentManager {
|
||||
return n;
|
||||
}
|
||||
|
||||
/** Cancel every open permission/question: persisted as permission_resolved{cancelled} (the page marks the card
|
||||
* 已取消 and stops waiting). tellSession: also answer the provider's own waiter (an Agent that ended its turn without
|
||||
* withdrawing the request would otherwise keep a dangling promise); its echo is dropped because rt.pending is empty. */
|
||||
private async cancelPending(threadId: string, rt: Runtime, opts: { tellSession: boolean }): Promise<void> {
|
||||
if (!rt.pending.size) return;
|
||||
const open = [...rt.pending.values()];
|
||||
rt.pending.clear();
|
||||
for (const p of open) {
|
||||
await this.appendRaw(threadId, { type: "permission_resolved", requestId: p.requestId, cancelled: true });
|
||||
p.resolve({ cancelled: true });
|
||||
if (opts.tellSession) {
|
||||
try { rt.session?.respond(p.requestId, { cancelled: true }); } catch { /* the session may be gone */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- interrupt ----
|
||||
async interrupt(threadId: string): Promise<void> {
|
||||
const rt = this.rt(threadId);
|
||||
if (!rt.session || rt.status !== "running") return;
|
||||
// Invalidate all pending requests
|
||||
for (const [id, p] of rt.pending) {
|
||||
await this.appendRaw(threadId, { type: "permission_resolved", requestId: id, cancelled: true });
|
||||
p.resolve({ cancelled: true });
|
||||
}
|
||||
rt.pending.clear();
|
||||
await this.cancelPending(threadId, rt, { tellSession: false });
|
||||
await rt.session.interrupt();
|
||||
const turnId = rt.currentTurnId;
|
||||
// No turn_ended within 1 second → append interrupted
|
||||
|
||||
@@ -7,7 +7,8 @@ import { tr } from "../../util/i18n.js";
|
||||
|
||||
export type PermBridge = {
|
||||
push(ev: ProviderEvent): void;
|
||||
waitFor(requestId: string): Promise<RespondAnswer>;
|
||||
/** signal: aborted when the Agent withdraws the request ($/cancel_request) or the connection closes */
|
||||
waitFor(requestId: string, signal?: AbortSignal): Promise<RespondAnswer>;
|
||||
/** Cursor Auto-review: no permission card, allow is chosen automatically */
|
||||
autoAcceptPermissions?: () => boolean;
|
||||
};
|
||||
@@ -42,7 +43,7 @@ export function registerAcpClientHandlers(app: ClientApp, bridge: PermBridge): v
|
||||
detail: tc.rawInput ?? undefined,
|
||||
options,
|
||||
});
|
||||
const answer = await bridge.waitFor(requestId);
|
||||
const answer = await bridge.waitFor(requestId, ctx.signal);
|
||||
if (answer.cancelled) return { outcome: { outcome: "cancelled" } };
|
||||
const optionId = answer.optionId ?? options[0]?.id;
|
||||
if (!optionId) return { outcome: { outcome: "cancelled" } };
|
||||
|
||||
@@ -113,7 +113,7 @@ export class AcpSession implements ProviderSession {
|
||||
const app = client({ name: "magpie-agent-console" });
|
||||
registerAcpClientHandlers(app, {
|
||||
push: (ev) => this.q.push(ev),
|
||||
waitFor: (id) => this.waitPerm(id),
|
||||
waitFor: (id, signal) => this.waitPerm(id, signal),
|
||||
autoAcceptPermissions: () => this.cursorAutoReview,
|
||||
});
|
||||
const stream = acpStreamFromChild(this.child);
|
||||
@@ -356,12 +356,24 @@ export class AcpSession implements ProviderSession {
|
||||
await this.applyCursorAutoReviewConfig(false);
|
||||
}
|
||||
|
||||
private waitPerm(requestId: string): Promise<RespondAnswer> {
|
||||
private waitPerm(requestId: string, signal?: AbortSignal): Promise<RespondAnswer> {
|
||||
return new Promise((resolve) => {
|
||||
this.permPending.set(requestId, resolve);
|
||||
// The Agent withdrew the request ($/cancel_request) or the connection closed: the card must not stay clickable
|
||||
if (signal?.aborted) this.cancelPerm(requestId);
|
||||
else signal?.addEventListener("abort", () => this.cancelPerm(requestId), { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
/** Close an open permission request as cancelled (answer the Agent's request and tell the manager) */
|
||||
private cancelPerm(requestId: string): void {
|
||||
const r = this.permPending.get(requestId);
|
||||
if (!r) return;
|
||||
this.permPending.delete(requestId);
|
||||
r({ cancelled: true });
|
||||
this.q.push({ type: "permission_resolved", requestId, cancelled: true });
|
||||
}
|
||||
|
||||
respond(requestId: string, answer: RespondAnswer): void {
|
||||
const r = this.permPending.get(requestId);
|
||||
if (r) {
|
||||
@@ -425,6 +437,10 @@ export class AcpSession implements ProviderSession {
|
||||
}
|
||||
|
||||
private endTurn(ev: ProviderEvent): void {
|
||||
// The prompt turn is over (end_turn, refusal, error, cancel): any request still open can't be answered any more.
|
||||
// Cursor ends a turn this way when its model stream dies ("[canceled] http/2 stream closed … CANCEL") right after
|
||||
// asking. Cancel those before the turn end so the timeline never keeps a request open past its turn.
|
||||
for (const id of [...this.permPending.keys()]) this.cancelPerm(id);
|
||||
this.q.push(ev);
|
||||
this.activeTurnId = null;
|
||||
this.running = false;
|
||||
|
||||
@@ -277,6 +277,25 @@ async function scriptPerm(ctx: Ctx): Promise<void> {
|
||||
emit({ type: "assistant_message", itemId: "pm", text: "测试通过了。" });
|
||||
}
|
||||
|
||||
// Like Cursor when its model stream dies ("http/2 stream closed … CANCEL"): it asks for permission, then ends the turn
|
||||
// itself without waiting for (or withdrawing) the answer. The manager must not keep the request pending afterwards.
|
||||
async function scriptPermAbandon(ctx: Ctx): Promise<void> {
|
||||
const { emit } = ctx;
|
||||
emit({
|
||||
type: "permission_request",
|
||||
requestId: "perm-" + rid(),
|
||||
title: "运行 git status",
|
||||
kind: "execute",
|
||||
detail: { command: "git status" },
|
||||
options: [
|
||||
{ id: "allow-once", label: tr("perm.allow"), kind: "allow_once" },
|
||||
{ id: "reject-once", label: tr("perm.deny"), kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
await sleepAbortable(200, ctx);
|
||||
emit({ type: "assistant_message", itemId: "pa", text: "Error: RetriableError: [canceled] http/2 stream closed with error code CANCEL (0x8)" });
|
||||
}
|
||||
|
||||
async function scriptPlan(ctx: Ctx): Promise<void> {
|
||||
const { emit } = ctx;
|
||||
emit({
|
||||
@@ -372,6 +391,7 @@ async function scriptExit(_ctx: Ctx): Promise<void> {
|
||||
|
||||
function pickScript(text: string): (ctx: Ctx) => Promise<void> {
|
||||
const t = text.trim();
|
||||
if (t.startsWith("/perm-abandon")) return scriptPermAbandon;
|
||||
if (t.startsWith("/perm")) return scriptPerm;
|
||||
if (t.startsWith("/plan")) return scriptPlan;
|
||||
if (t.startsWith("/ask")) return scriptAsk;
|
||||
|
||||
@@ -10,6 +10,15 @@
|
||||
// fresh session.js and opens the gate, which restarts the daemon and sends the frame here again with the new port.
|
||||
// - at most 3 automatic tries in 2 minutes (counted in ?ac_try=<start>.<n>, carried through b → boot.js → gate → here);
|
||||
// then a button, so a daemon that can't start doesn't loop forever.
|
||||
// - coming back to the page (visibilitychange → visible, or window focus) checks at once instead of waiting out the timers
|
||||
// that were pushed back while hidden: if the child never said alive within bootMs of loading, or its last real alive is
|
||||
// older than silentMs, it gets probeMs (two heartbeats) to speak up, then recover(); a child that is still alive is
|
||||
// never refreshed. If an end state with Reconnect is showing, coming back counts as the user clicking it (also when
|
||||
// the 3 automatic tries are used up), so the user never returns to a dead button.
|
||||
// - every disconnect / invalid-link end state shows a Reconnect button. A missing #b= is filled from sessionStorage
|
||||
// (last safe Magpie back URL written when this page first saw a valid b; read/write re-run safeBack). With a stored
|
||||
// back, recover navigates via go(false). With none, the button reloads and the copy tells the user to flip Magpie's
|
||||
// top-bar page and open Agent Console again if reload is not enough.
|
||||
//
|
||||
// Security: this page holds no secret of its own. The daemon token arrives only in its # fragment (as before, never sent to a
|
||||
// server, not in Referer) and is handed to the child in the child's fragment; the gate key is never here. The child is always
|
||||
@@ -35,7 +44,7 @@ export function parseTry(raw) {
|
||||
return m ? { start: Number(m[1]), n: Number(m[2]) } : null;
|
||||
}
|
||||
|
||||
export const WRAP_TIMING = { bootMs: 12000, afterLoadMs: 6000, silentMs: 15000, maxTries: 3, triesWindowMs: 120000 };
|
||||
export const WRAP_TIMING = { bootMs: 12000, afterLoadMs: 6000, silentMs: 15000, maxTries: 3, triesWindowMs: 120000, probeMs: 4000 };
|
||||
|
||||
const SCRIPT = String.raw`(function () {
|
||||
"use strict";
|
||||
@@ -44,7 +53,16 @@ const SCRIPT = String.raw`(function () {
|
||||
var frag = new URLSearchParams(location.hash.slice(1));
|
||||
var token = frag.get("t") || "";
|
||||
var port = Number(frag.get("p"));
|
||||
var BACK_KEY = "ac_wrap_back";
|
||||
function readStoredBack() {
|
||||
try { return safeBack(sessionStorage.getItem(BACK_KEY)); } catch (e) { return null; }
|
||||
}
|
||||
function writeStoredBack(v) {
|
||||
if (!v) return;
|
||||
try { sessionStorage.setItem(BACK_KEY, v); } catch (e) {}
|
||||
}
|
||||
var back = safeBack(frag.get("b"));
|
||||
if (back) writeStoredBack(back);
|
||||
var q = new URLSearchParams(location.search);
|
||||
var lang = (q.get("lang") || "").toLowerCase();
|
||||
var zh = !lang || lang.indexOf("zh") === 0;
|
||||
@@ -53,13 +71,34 @@ const SCRIPT = String.raw`(function () {
|
||||
var box = document.getElementById("m");
|
||||
var said = document.getElementById("s");
|
||||
var btn = document.getElementById("r");
|
||||
var RECONNECT = ["重新连接", "Reconnect"];
|
||||
function onReturn(fn) {
|
||||
document.addEventListener("visibilitychange", function () { if (document.visibilityState === "visible") fn(); });
|
||||
window.addEventListener("focus", function () { if (document.visibilityState !== "hidden") fn(); });
|
||||
}
|
||||
function msg(zhText, enText, button) {
|
||||
said.textContent = zh ? zhText : enText;
|
||||
box.hidden = false;
|
||||
if (button) { btn.textContent = zh ? button[0] : button[1]; btn.hidden = false; }
|
||||
}
|
||||
// The Reconnect action of the end state on screen (null while none is): coming back to the page runs it once
|
||||
var ended = null;
|
||||
function wireReconnect(targetBack) {
|
||||
ended = btn.onclick = function () {
|
||||
if (btn.disabled) return;
|
||||
btn.disabled = true;
|
||||
if (targetBack) location.replace(targetBack);
|
||||
else location.reload();
|
||||
};
|
||||
}
|
||||
if (!/^[0-9a-f]{32,128}$/i.test(token) || !(port > 0 && port < 65536 && Math.floor(port) === port)) {
|
||||
msg("链接已失效,请在 Magpie 里重新打开插件页。", "The link is no longer valid. Please reopen the Agent Console page in Magpie.");
|
||||
msg(
|
||||
"链接已失效。请点重新连接;若仍不行,可在 Magpie 顶栏先切到别的页再点回「Agent 控制台」。",
|
||||
"This link is no longer valid. Click Reconnect; if that fails, switch to another Magpie top-bar page, then open Agent Console again.",
|
||||
RECONNECT
|
||||
);
|
||||
wireReconnect(back || readStoredBack());
|
||||
onReturn(function () { if (ended) ended(); });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -71,10 +110,15 @@ const SCRIPT = String.raw`(function () {
|
||||
|
||||
var everAlive = false, lastAlive = 0, recovering = false;
|
||||
var loadedAt = Date.now(), lastTick = Date.now();
|
||||
// Unlike lastAlive / loadedAt these are never pushed back while hidden or asleep: what the return check compares against
|
||||
var heardAt = 0, bootAt = loadedAt, probeFrom = 0, probeUntil = 0;
|
||||
msg("正在连接本地服务…", "Connecting to the local service…");
|
||||
// A dead port shows the browser's error page, which also fires load: once loaded, the child gets T.afterLoadMs to say alive
|
||||
f.addEventListener("load", function () {
|
||||
if (!everAlive) loadedAt = Math.min(loadedAt, Date.now() - (T.bootMs - T.afterLoadMs));
|
||||
if (!everAlive) {
|
||||
loadedAt = Math.min(loadedAt, Date.now() - (T.bootMs - T.afterLoadMs));
|
||||
bootAt = Math.min(bootAt, Date.now() - (T.bootMs - T.afterLoadMs));
|
||||
}
|
||||
});
|
||||
|
||||
function recover(at) {
|
||||
@@ -84,8 +128,22 @@ const SCRIPT = String.raw`(function () {
|
||||
var now = Date.now();
|
||||
var t = (function (raw) { var m = /^(\d{10,15})\.([0-9])$/.exec(raw || ""); return m ? { start: +m[1], n: +m[2] } : null; })(q.get("ac_try"));
|
||||
if (!t || now - t.start > T.triesWindowMs || t.start > now) t = { start: now, n: 0 };
|
||||
// #b= missing (or unsafe): reuse the last safe Magpie back URL from this origin, then go(false) — not an auto try
|
||||
if (!back) {
|
||||
msg("本地服务已断开。请在 Magpie 里重新打开插件页。", "The local service disconnected. Please reopen the Agent Console page in Magpie.");
|
||||
back = readStoredBack();
|
||||
if (back) {
|
||||
msg("本地服务已断开,正在重新连接…", "The local service disconnected. Reconnecting…");
|
||||
var uStored = new URL(back);
|
||||
if (at > 0) uStored.searchParams.set("ac_lost", String(Math.floor(at)));
|
||||
location.replace(uStored.toString());
|
||||
return;
|
||||
}
|
||||
msg(
|
||||
"本地服务已断开。请点重新连接;若仍不行,可在 Magpie 顶栏先切到别的页再点回「Agent 控制台」。",
|
||||
"The local service disconnected. Click Reconnect; if that fails, switch to another Magpie top-bar page, then open Agent Console again.",
|
||||
RECONNECT
|
||||
);
|
||||
wireReconnect(null);
|
||||
return;
|
||||
}
|
||||
var go = function (auto) {
|
||||
@@ -95,8 +153,8 @@ const SCRIPT = String.raw`(function () {
|
||||
location.replace(u.toString());
|
||||
};
|
||||
if (t.n >= T.maxTries) {
|
||||
msg("本地服务多次重连失败。", "Reconnecting to the local service failed several times.", ["重新连接", "Reconnect"]);
|
||||
btn.onclick = function () { btn.disabled = true; go(false); };
|
||||
msg("本地服务多次重连失败。", "Reconnecting to the local service failed several times.", RECONNECT);
|
||||
ended = btn.onclick = function () { if (btn.disabled) return; btn.disabled = true; go(false); };
|
||||
return;
|
||||
}
|
||||
msg("本地服务已断开,正在重新连接…", "The local service disconnected. Reconnecting…");
|
||||
@@ -108,7 +166,8 @@ const SCRIPT = String.raw`(function () {
|
||||
if (!d || typeof d !== "object") return;
|
||||
if (e.source === f.contentWindow) {
|
||||
if (d.ac_console === "alive") {
|
||||
lastAlive = Date.now();
|
||||
lastAlive = heardAt = Date.now();
|
||||
probeUntil = 0;
|
||||
if (!everAlive) { everAlive = true; box.hidden = true; f.classList.add("on"); }
|
||||
return;
|
||||
}
|
||||
@@ -126,10 +185,25 @@ const SCRIPT = String.raw`(function () {
|
||||
}
|
||||
});
|
||||
|
||||
// The page is visible again: don't wait for the timers that were pushed back while hidden
|
||||
function checkOnReturn() {
|
||||
if (ended) { ended(); return; } // an end state is showing: same as clicking Reconnect (even with the auto tries used up)
|
||||
if (recovering || probeUntil) return;
|
||||
var now = Date.now();
|
||||
var stale = everAlive ? now - heardAt > T.silentMs : now - bootAt > T.bootMs;
|
||||
if (stale) { probeFrom = now; probeUntil = now + T.probeMs; } // a child that is still there answers with its next heartbeat
|
||||
}
|
||||
onReturn(checkOnReturn);
|
||||
|
||||
setInterval(function () {
|
||||
var now = Date.now();
|
||||
var gap = now - lastTick;
|
||||
var prevTick = lastTick, gap = now - lastTick;
|
||||
lastTick = now;
|
||||
if (probeUntil) {
|
||||
// Hidden or suspended again after the probe started: drop it (a gap that ended before it, e.g. the wake itself, is fine)
|
||||
if (document.visibilityState === "hidden" || (gap > 5000 && prevTick >= probeFrom)) probeUntil = 0;
|
||||
else if (now >= probeUntil) { probeUntil = 0; recover(everAlive ? heardAt : 0); return; }
|
||||
}
|
||||
// This page's own timers were held (sleep, a frozen or heavily throttled frame): give the child a fresh window
|
||||
if (gap > 5000 || document.visibilityState === "hidden") {
|
||||
if (everAlive) lastAlive = Math.max(lastAlive, now);
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.2",
|
||||
"version": "1.3.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.2",
|
||||
"version": "1.3.3",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "2.1.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.2",
|
||||
"version": "1.3.3",
|
||||
"description": "在 magpie 窗口里加一个「Agent 控制台」页面:用常驻本地服务驱动本机的 Agent CLI(Claude Code、Codex、Cursor 等),带结构化时间线。A Magpie page that drives local Agent CLIs (Claude Code, Codex, Cursor, and others) with a persistent local daemon and a structured timeline.",
|
||||
"author": "qingnian108 (https://github.com/qingnian108)",
|
||||
"homepage": "https://github.com/qingnian108/magpie-agent-console",
|
||||
|
||||
@@ -884,14 +884,52 @@ async function scenario15() {
|
||||
record("场景15 终端:echo→输出→刷新→历史仍在", true);
|
||||
}
|
||||
|
||||
async function scenario28() {
|
||||
// Nolan's 1.2.0 bug: Cursor asked for permission, its stream died and the turn ended with the request open; the top
|
||||
// bar kept 等待授权 and the composer stayed locked with no card to click. /perm-abandon does the same in the mock.
|
||||
await newThread();
|
||||
await send("/perm-abandon");
|
||||
await waitIdle();
|
||||
await sleep(300);
|
||||
const state = () => page.evaluate(() => ({
|
||||
wait: !!document.querySelector(".tb-pill.wait"),
|
||||
locked: !!document.querySelector(".cp-ta")?.disabled,
|
||||
pending: window.__tl?.getState?.().pending?.length ?? -1,
|
||||
}));
|
||||
const live = await state();
|
||||
await page.reload({ waitUntil: "domcontentloaded" });
|
||||
await page.waitForFunction(() => window.__ws && window.__ws.getState() === "open", { timeout: 10000 });
|
||||
await page.waitForSelector(".card.perm", { timeout: 10000 });
|
||||
await sleep(500);
|
||||
const reloaded = await state();
|
||||
const cancelled = await page.$eval(".card.perm", (e) => e.textContent.includes("已取消"));
|
||||
// A request that does wait: the 等待授权 pill brings its card into view from the top of a long conversation
|
||||
await send("/perm");
|
||||
await page.waitForSelector(`${sel.permCard} button:has-text("允许")`, { timeout: 15000 });
|
||||
await page.evaluate(() => { const el = document.querySelector(".tl-wrap") ?? document.querySelector("[data-index]")?.parentElement?.parentElement; if (el) el.scrollTop = 0; });
|
||||
const pillBtn = await page.$("button.tb-pill.wait");
|
||||
await pillBtn?.click();
|
||||
await sleep(400);
|
||||
const inView = await page.evaluate(() => {
|
||||
const cards = [...document.querySelectorAll(".card.perm")].filter((c) => c.querySelector(".perm-btns"));
|
||||
const r = cards[0]?.getBoundingClientRect();
|
||||
return !!r && r.bottom > 0 && r.top < window.innerHeight;
|
||||
});
|
||||
await page.click(`${sel.permCard} button:has-text("允许")`);
|
||||
await waitIdle();
|
||||
const ok = !live.wait && !live.locked && live.pending === 0 && !reloaded.wait && !reloaded.locked && reloaded.pending === 0 && cancelled && !!pillBtn && inView;
|
||||
record("场景28 Agent 自己结束了带着授权请求的一轮:不卡等待授权;等待授权胶囊可跳到卡片", ok,
|
||||
JSON.stringify({ live, reloaded, cancelled, pillBtn: !!pillBtn, inView }));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
await setup();
|
||||
try {
|
||||
await newProjectFlow();
|
||||
// E2E_ONLY_13=1 runs just the 1.3 scenarios (20–27) and the console-error check
|
||||
const all = [scenario2, scenario3, scenario4, scenario5, scenario6, scenario7, scenario8, scenario9, scenario10, scenario11,
|
||||
scenario12, scenario13, scenario14, scenario15, scenario16, scenario17, scenario18, scenario20, scenario21, scenario22, scenario23, scenario24, scenario25, scenario26, scenario27, scenario19];
|
||||
const only13 = new Set([scenario20, scenario21, scenario22, scenario23, scenario24, scenario25, scenario26, scenario27, scenario19]);
|
||||
scenario12, scenario13, scenario14, scenario15, scenario16, scenario17, scenario18, scenario20, scenario21, scenario22, scenario23, scenario24, scenario25, scenario26, scenario27, scenario28, scenario19];
|
||||
const only13 = new Set([scenario20, scenario21, scenario22, scenario23, scenario24, scenario25, scenario26, scenario27, scenario28, scenario19]);
|
||||
for (const f of all) if (!process.env.E2E_ONLY_13 || only13.has(f)) await f();
|
||||
} catch (e) {
|
||||
record("中途异常", false, String(e?.message ?? e).slice(0, 600) + " ||daemon:" + daemonErr.slice(-4).join("|").slice(0, 400));
|
||||
|
||||
@@ -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" });
|
||||
|
||||
@@ -60,7 +60,7 @@ export function App() {
|
||||
return (
|
||||
<Layout
|
||||
sidebar={<Sidebar pendingByThread={new Set(pending.map((p) => useTimeline.getState().threadId!).filter(Boolean))} />}
|
||||
topbar={<Topbar pendingCount={pending.length} />}
|
||||
topbar={<Topbar pendingCount={pending.length} pendingKey={pending[0]?.key} />}
|
||||
panel={<Panel />}
|
||||
>
|
||||
{state === "reconnecting" && <div className="connbar">{t("boot.reconnecting")}</div>}
|
||||
|
||||
@@ -28,6 +28,8 @@ const PATHS: Record<string, string> = {
|
||||
stopFill: "M8 8h8v8H8z",
|
||||
shield: "M12 3l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V6l8-3z",
|
||||
quote: "M5 7h5v5H7c0 2 1 3 3 4M14 7h5v5h-3c0 2 1 3 3 4",
|
||||
// 添加到对话 (selection pop-up): speech bubble + three dots
|
||||
chat: "M5 5h14v10H9l-4 4V5zM9 10h.01M12 10h.01M15 10h.01",
|
||||
pencil: "M4 20h4L19 9a2.1 2.1 0 0 0-3-3L5 17v3zM14 7l3 3",
|
||||
shieldCheck: "M12 3l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V6l8-3zM8.5 12.2l2.4 2.4 4.6-4.8",
|
||||
zap: "M13 2L4 14h7l-1 8 9-12h-7l1-8z",
|
||||
|
||||
@@ -124,7 +124,7 @@ export function QuoteSelect() {
|
||||
onPointerDown={(e) => e.preventDefault()}
|
||||
onClick={add}
|
||||
>
|
||||
<Icon name="quote" size={13} />
|
||||
<Icon name="chat" size={13} />
|
||||
<span>{t("quote.add")}</span>
|
||||
</button>,
|
||||
document.body,
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useUi } from "../stores/ui";
|
||||
import { ws } from "../main";
|
||||
import type { Project, ThreadMeta } from "../types/models";
|
||||
import { relTime } from "../util/format";
|
||||
import { threadDotClass } from "../util/threadDot";
|
||||
import { Menu, useMenu, type MenuItem } from "./Menu";
|
||||
import { Dialog, ConfirmDialog } from "./Dialog";
|
||||
import { Icon } from "./Icons";
|
||||
@@ -14,12 +15,7 @@ import { displayThreadTitle, errMsg, t as tr, tf } from "../i18n/index.js";
|
||||
|
||||
const THREAD_PAGE = 10;
|
||||
|
||||
function dotClass(t: ThreadMeta, pendingIds: Set<string>): string {
|
||||
if (pendingIds.has(t.id)) return "dot wait";
|
||||
if (t.status === "running" || t.status === "initializing") return "dot run";
|
||||
if (t.status === "error" || t.lastTurnStatus === "failed") return "dot err";
|
||||
return "dot";
|
||||
}
|
||||
const dotClass = threadDotClass;
|
||||
|
||||
export function Sidebar({ pendingByThread }: { pendingByThread: Set<string> }) {
|
||||
const { projects, threads } = useData();
|
||||
|
||||
@@ -25,7 +25,7 @@ function useNow(running: boolean): number {
|
||||
return now;
|
||||
}
|
||||
|
||||
export function Topbar({ pendingCount }: { pendingCount: number }) {
|
||||
export function Topbar({ pendingCount, pendingKey }: { pendingCount: number; pendingKey?: string }) {
|
||||
const { projects, threads } = useData();
|
||||
const ui = useUi();
|
||||
const { version } = useConnection();
|
||||
@@ -101,7 +101,11 @@ export function Topbar({ pendingCount }: { pendingCount: number }) {
|
||||
) : (
|
||||
<span className="tb-title ghost">{project ? t("topbar.pickThread") : t("app.title")}</span>
|
||||
)}
|
||||
{pill && <span className={`tb-pill ${pill.cls}`}>{pill.cls === "run" && <span className="tb-pill-dot" />}{pill.text}</span>}
|
||||
{pill && (pill.cls === "wait" && pendingKey
|
||||
// 等待授权 brings the card that waits into view (it may be far up a long conversation)
|
||||
? <button type="button" className={`tb-pill ${pill.cls}`} title={t("topbar.showRequest")}
|
||||
onClick={() => window.dispatchEvent(new CustomEvent("ac-show-item", { detail: { key: pendingKey } }))}>{pill.text}</button>
|
||||
: <span className={`tb-pill ${pill.cls}`}>{pill.cls === "run" && <span className="tb-pill-dot" />}{pill.text}</span>)}
|
||||
<div className="tb-right">
|
||||
{thread?.model && <span className="tb-model">{thread.model}</span>}
|
||||
{panelBtns.map((b) => (
|
||||
|
||||
@@ -23,7 +23,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
},
|
||||
topbar: {
|
||||
pickThread: "选择一个对话", sidebar: "侧栏(Ctrl+B)", clickRename: "点击改名",
|
||||
waitAuth: "等待授权", running: "运行中 {s}s", error: "出错",
|
||||
waitAuth: "等待授权", showRequest: "查看授权请求", running: "运行中 {s}s", error: "出错",
|
||||
closedResume: "已关闭 · 发送消息将续接", threadInfo: "对话信息",
|
||||
panelChanges: "改动(Ctrl+J)", panelFiles: "文件", panelTerminal: "终端",
|
||||
},
|
||||
@@ -241,7 +241,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
},
|
||||
topbar: {
|
||||
pickThread: "Select a conversation", sidebar: "Sidebar (Ctrl+B)", clickRename: "Click to rename",
|
||||
waitAuth: "Waiting for approval", running: "Running {s}s", error: "Error",
|
||||
waitAuth: "Waiting for approval", showRequest: "Show the request", running: "Running {s}s", error: "Error",
|
||||
closedResume: "Closed · send a message to resume", threadInfo: "Conversation info",
|
||||
panelChanges: "Changes (Ctrl+J)", panelFiles: "Files", panelTerminal: "Terminal",
|
||||
},
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
// Current conversation timeline: threads.get snapshot + thread:<id> channel increments → DisplayItem[].
|
||||
import { create } from "zustand";
|
||||
import type { TimelineEvent } from "../timeline/types";
|
||||
import { applyEvent, newTimelineState, reduceTimeline, type DisplayItem } from "../timeline/reducer";
|
||||
import { applyEvent, newTimelineState, pendingRequests, reduceTimeline, type DisplayItem } from "../timeline/reducer";
|
||||
import { ws } from "../main";
|
||||
import type { SlashCommand } from "../composer/slashMenu";
|
||||
import { Outbox, newClientId, withOutbox, type SendDisplay, type SendPayload } from "../timeline/outbox";
|
||||
|
||||
export type QueueItem = { id: string; text: string; attachments?: { path: string; mime: string }[] };
|
||||
export type PendingReq = { requestId: string; kind: "permission" | "question" };
|
||||
export type PendingReq = { requestId: string; kind: "permission" | "question"; key?: string };
|
||||
|
||||
type TlStore = {
|
||||
threadId: string | null;
|
||||
@@ -92,17 +92,16 @@ export const useTimeline = create<TlStore>((set, get) => {
|
||||
}
|
||||
applyEvent(st, ev);
|
||||
// pending is derived from timeline items (pending permission/question → composer waiting state)
|
||||
const pending = st.items
|
||||
.filter((i) => (i.kind === "permission" || i.kind === "question") && i.status === "pending")
|
||||
.map((i) => ({ requestId: (i as { requestId: string }).requestId, kind: i.kind as "permission" | "question" }));
|
||||
set({ ...view(threadId), pending });
|
||||
set({ ...view(threadId), pending: pendingRequests(st.items) });
|
||||
return;
|
||||
}
|
||||
if (data.type === "status" && data.status) {
|
||||
runtimeStatus = data.status;
|
||||
if (busyStatus(runtimeStatus) || runtimeStatus === "error" || runtimeStatus === "closed") outbox.busy(threadId);
|
||||
syncRuntimeFlags();
|
||||
set(view(threadId));
|
||||
// Going idle closes the open cards (syncRuntimeFlags): the waiting state follows them, or the top bar would
|
||||
// keep 等待授权 with no card to click
|
||||
set({ ...view(threadId), pending: pendingRequests(st.items) });
|
||||
return;
|
||||
}
|
||||
if (data.type === "queue" && data.queue) {
|
||||
@@ -110,7 +109,8 @@ export const useTimeline = create<TlStore>((set, get) => {
|
||||
return;
|
||||
}
|
||||
if (data.type === "pending" && data.pending) {
|
||||
set({ pending: data.pending });
|
||||
// Only requests the timeline shows a live card for
|
||||
set({ pending: pendingRequests(st.items).filter((p) => data.pending!.some((d) => d.requestId === p.requestId)) });
|
||||
return;
|
||||
}
|
||||
if (data.type === "commands" && data.commands) {
|
||||
@@ -158,7 +158,9 @@ export const useTimeline = create<TlStore>((set, get) => {
|
||||
syncRuntimeFlags();
|
||||
set({
|
||||
...view(threadId),
|
||||
queue: g.queue ?? [], pending: g.pending ?? [], lastUserText: r.lastUserText,
|
||||
// Not g.pending: the daemon's list could hold a request the timeline already closed (a 1.2 daemon kept
|
||||
// one whose turn had ended). Waiting follows the cards that show buttons.
|
||||
queue: g.queue ?? [], pending: pendingRequests(st.items), lastUserText: r.lastUserText,
|
||||
});
|
||||
// Subscribe only once the snapshot is ready: the server replays events after afterSeq=stSeqMax, joining the snapshot seamlessly
|
||||
if (get().threadId === threadId) subscribeChannel(threadId);
|
||||
|
||||
@@ -122,7 +122,10 @@ textarea.tinput { height: auto; min-height: 60px; padding: 6px 10px; resize: ver
|
||||
|
||||
/* Status dot */
|
||||
.dot { width: 6px; height: 6px; border-radius: 50%; flex: none; background: var(--muted); }
|
||||
.dot.run { background: var(--accent-2); animation: breathe 1.6s infinite; }
|
||||
.dot.ok { background: var(--ok); }
|
||||
/* Running: strong dark<->light blink so it reads at a glance in both themes. */
|
||||
.dot.run { background: var(--fg); animation: dot-blink 1s steps(1, end) infinite; box-shadow: 0 0 0 1px color-mix(in oklab, var(--fg) 45%, transparent); }
|
||||
@keyframes dot-blink { 50% { background: var(--bg); } }
|
||||
.dot.err { background: var(--danger); }
|
||||
.dot.wait { background: var(--warn); animation: breathe 1.6s infinite; }
|
||||
@keyframes breathe { 50% { opacity: .35; } }
|
||||
|
||||
@@ -66,7 +66,7 @@
|
||||
.t-item.on::before { content: ""; position: absolute; left: -1px; top: 7px; bottom: 7px; width: 2px; border-radius: 2px; background: var(--accent-2); }
|
||||
.t-item.archived { opacity: 0.55; }
|
||||
.t-item.archived .t-title { font-style: italic; }
|
||||
.t-item .dot { width: 5px; height: 5px; }
|
||||
.t-item .dot { width: 6px; height: 6px; }
|
||||
.t-pin { width: 12px; flex: none; display: inline-flex; color: var(--muted); }
|
||||
.t-pin svg { width: 10px; height: 10px; }
|
||||
.t-title { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
@@ -124,6 +124,7 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; }
|
||||
.tb-pill.run { background: var(--run-bg); color: var(--run-fg); }
|
||||
.tb-pill-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent-2); box-shadow: 0 0 0 3px color-mix(in oklab, var(--accent-2) 20%, transparent); animation: breathe 1.6s infinite; }
|
||||
.tb-pill.wait { color: var(--warn); }
|
||||
button.tb-pill { border: 0; font-family: inherit; cursor: pointer; }
|
||||
.tb-pill.err { color: var(--danger); }
|
||||
.tb-right { margin-left: auto; display: flex; align-items: center; gap: 2px; }
|
||||
.tb-model { font-size: var(--fs-s); color: var(--muted); margin-right: 4px; white-space: nowrap; max-width: 160px; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
@@ -237,6 +237,8 @@ export function applyEvent(st: State, ev: TimelineEvent): void {
|
||||
it.status = ev.cancelled ? "cancelled" : "resolved";
|
||||
it.choice = ev.optionId;
|
||||
if (ev.auto) it.auto = true;
|
||||
} else if (it?.kind === "question" && ev.cancelled && it.status === "pending") {
|
||||
it.status = "cancelled"; // the daemon cancels open questions with permission_resolved{cancelled} too
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -270,6 +272,10 @@ export function applyEvent(st: State, ev: TimelineEvent): void {
|
||||
return;
|
||||
case "turn_ended":
|
||||
breakGroup(st);
|
||||
// A request still open when its turn ends can't be answered any more: the Agent moved on. Daemons before the fix
|
||||
// left such a request open in the timeline (Cursor 1.2.0: "[canceled] http/2 stream closed" right after asking),
|
||||
// and the page kept "等待授权" for a card showing 已取消. Close it here so replayed history never waits on it.
|
||||
closeOpenRequests(st);
|
||||
st.items.push({
|
||||
kind: "turnend", key: `te:${ev.seq}`, status: ev.status,
|
||||
durationMs: ev.durationMs ?? (st.turnStart.has(ev.turnId) ? Math.max(0, ev.ts - st.turnStart.get(ev.turnId)!) : undefined),
|
||||
@@ -291,6 +297,28 @@ export function applyEvent(st: State, ev: TimelineEvent): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** Requests still waiting for the user are always ones whose turn is still running (see turn_ended) */
|
||||
function closeOpenRequests(st: State): void {
|
||||
for (const idx of st.reqLoc.values()) {
|
||||
const it = st.items[idx];
|
||||
if ((it?.kind === "permission" || it?.kind === "question") && it.status === "pending") it.status = "cancelled";
|
||||
}
|
||||
}
|
||||
|
||||
export type PendingRequest = { requestId: string; kind: "permission" | "question"; key: string };
|
||||
|
||||
/** The requests the page waits on (top bar 等待授权, composer locked): exactly the cards that show buttons, so the
|
||||
* page never waits on a request it has no card for (the daemon's own list may hold one the timeline already closed) */
|
||||
export function pendingRequests(items: DisplayItem[]): PendingRequest[] {
|
||||
const out: PendingRequest[] = [];
|
||||
for (const it of items) {
|
||||
if ((it.kind === "permission" || it.kind === "question") && it.status === "pending") {
|
||||
out.push({ requestId: it.requestId, kind: it.kind, key: it.key });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// snapshot + live events -> display items. When runtimeStatus is not running, unresolved permissions/questions are marked cancelled.
|
||||
export function reduceTimeline(
|
||||
events: TimelineEvent[],
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { threadDotClass } from "./threadDot";
|
||||
|
||||
const t = (status: any, lastTurnStatus: any = null, id = "a") => ({ id, status, lastTurnStatus }) as any;
|
||||
|
||||
describe("threadDotClass", () => {
|
||||
it("maps states with priority wait > run > err > ok > idle", () => {
|
||||
expect(threadDotClass(t("running", "completed"), new Set(["a"]))).toBe("dot wait");
|
||||
expect(threadDotClass(t("running", "failed"), new Set())).toBe("dot run");
|
||||
expect(threadDotClass(t("initializing"), new Set())).toBe("dot run");
|
||||
expect(threadDotClass(t("idle", "failed"), new Set())).toBe("dot err");
|
||||
expect(threadDotClass(t("error", "completed"), new Set())).toBe("dot err");
|
||||
expect(threadDotClass(t("idle", "completed"), new Set())).toBe("dot ok");
|
||||
expect(threadDotClass(t("idle", "interrupted"), new Set())).toBe("dot");
|
||||
expect(threadDotClass(t("idle", null), new Set())).toBe("dot");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { ThreadMeta } from "../types/models";
|
||||
|
||||
/** Sidebar status dot class. Priority: wait > run > err > ok (completed) > idle grey. */
|
||||
export function threadDotClass(
|
||||
t: Pick<ThreadMeta, "id" | "status" | "lastTurnStatus">,
|
||||
pendingIds: Set<string>,
|
||||
): string {
|
||||
if (pendingIds.has(t.id)) return "dot wait";
|
||||
if (t.status === "running" || t.status === "initializing") return "dot run";
|
||||
if (t.status === "error" || t.lastTurnStatus === "failed") return "dot err";
|
||||
if (t.lastTurnStatus === "completed") return "dot ok";
|
||||
return "dot";
|
||||
}
|
||||
Reference in New Issue
Block a user