Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(extensions): retire SDK operations with their invocation

Jack5894a7c5830b
diff --cc apps/desktop/electron/main/agent-extensions.ts
index 39920f598,39920f598..2885ad1e3
--- a/apps/desktop/electron/main/agent-extensions.ts
+++ b/apps/desktop/electron/main/agent-extensions.ts
@@@ -42,6 -42,6 +42,7 @@@ type SessionState =
};
type PendingPrompt = {
++ prompt: TrustedExtensionUiPrompt;
sessionId: string;
kind: "confirm" | "select" | "input";
resolve: (response: TrustedExtensionUiResponse) => void;
@@@ -59,7 -59,7 +60,7 @@@ export type AgentExtensionBridgeOption
};
function dismissedResponse(kind: PendingPrompt["kind"]): TrustedExtensionUiResponse {
-- return kind === "confirm" ? { kind, value: false } : { kind, value: undefined };
++ return kind === "confirm" ? { kind, value: false, cancelled: true } : { kind, value: undefined, cancelled: true };
}
export class AgentExtensionBridge {
@@@ -68,6 -68,6 +69,7 @@@
private readonly pending = new Map<string, PendingPrompt>();
/** One interactive prompt per session at a time (spec §9). */
private readonly promptQueues = new Map<string, Promise<unknown>>();
++ private readonly uiRequests = new Map<string, { sessionId: string; controller: AbortController }>();
constructor(options: AgentExtensionBridgeOptions) {
this.options = options;
@@@ -141,6 -141,6 +143,11 @@@
async requestUi(envelope: TrustedExtensionUiRequestEnvelope): Promise<TrustedExtensionUiResponse> {
const { request } = envelope;
switch (request.kind) {
++ case "cancel": {
++ const key = JSON.stringify([envelope.sessionId, envelope.extensionId, request.requestId]);
++ this.uiRequests.get(key)?.controller.abort();
++ return { kind: "cancel" };
++ }
case "notify":
this.options.onToast(`${envelope.extensionLabel}: ${request.message}`, request.level);
return { kind: "notify" };
@@@ -170,10 -170,10 +177,30 @@@
errorCode: ErrorCodes.UNSUPPORTED,
});
}
++ const key = JSON.stringify([envelope.sessionId, envelope.extensionId, envelope.requestId ?? randomUUID()]);
++ if (this.uiRequests.has(key)) throw new Error("Duplicate extension UI request");
++ const controller = new AbortController();
++ this.uiRequests.set(key, { sessionId: envelope.sessionId, controller });
const previous = this.promptQueues.get(envelope.sessionId) ?? Promise.resolve();
-- const run = previous.then(() => this.showPrompt(envelope, request));
-- this.promptQueues.set(envelope.sessionId, run.catch(() => undefined));
-- return run;
++ const run = previous.then(() => controller.signal.aborted
++ ? dismissedResponse(request.kind)
++ : this.showPrompt(envelope, request, controller.signal));
++ const tail = run.catch(() => undefined);
++ this.promptQueues.set(envelope.sessionId, tail);
++ let retire!: () => void;
++ const cancelled = new Promise<TrustedExtensionUiResponse>((resolve) => {
++ retire = () => resolve(dismissedResponse(request.kind));
++ controller.signal.addEventListener("abort", retire, { once: true });
++ if (controller.signal.aborted) retire();
++ });
++ try { return await Promise.race([run, cancelled]); }
++ finally {
++ controller.signal.removeEventListener("abort", retire);
++ this.uiRequests.delete(key);
++ void tail.then(() => {
++ if (this.promptQueues.get(envelope.sessionId) === tail) this.promptQueues.delete(envelope.sessionId);
++ });
++ }
}
respond(promptId: string, value: string | boolean | undefined): boolean {
@@@ -185,6 -185,6 +212,9 @@@
/** Aborting a turn dismisses that session's open prompts (spec §9). */
cancelPrompts(sessionId: string): void {
++ for (const entry of this.uiRequests.values()) {
++ if (entry.sessionId === sessionId) entry.controller.abort();
++ }
for (const [promptId, pending] of this.pending) {
if (pending.sessionId === sessionId) this.settle(promptId, dismissedResponse(pending.kind));
}
@@@ -199,26 -199,26 +229,27 @@@
private showPrompt(
envelope: TrustedExtensionUiRequestEnvelope,
request: TrustedExtensionUiPrompt["request"],
++ signal: AbortSignal,
): Promise<TrustedExtensionUiResponse> {
return new Promise((resolvePrompt) => {
const promptId = randomUUID();
++ const prompt = { promptId, sessionId: envelope.sessionId, extensionId: envelope.extensionId,
++ extensionLabel: envelope.extensionLabel, request };
++ const abort = () => this.settle(promptId, dismissedResponse(request.kind));
const timer = setTimeout(
() => this.settle(promptId, dismissedResponse(request.kind)),
this.options.promptTimeoutMs ?? TRUSTED_EXTENSION_PROMPT_TIMEOUT_MS,
);
this.pending.set(promptId, {
++ prompt,
sessionId: envelope.sessionId,
kind: request.kind,
-- resolve: resolvePrompt,
++ resolve: (response) => { signal.removeEventListener("abort", abort); resolvePrompt(response); },
timer,
});
-- this.options.onPrompt({
-- promptId,
-- sessionId: envelope.sessionId,
-- extensionId: envelope.extensionId,
-- extensionLabel: envelope.extensionLabel,
-- request,
-- });
++ signal.addEventListener("abort", abort, { once: true });
++ this.options.onPrompt(prompt);
++ if (signal.aborted) abort();
});
}
@@@ -227,6 -227,6 +258,7 @@@
if (!pending) return;
clearTimeout(pending.timer);
this.pending.delete(promptId);
++ this.options.onPrompt({ ...pending.prompt, cancelled: true });
pending.resolve(response);
}
diff --cc apps/desktop/src/components/ExtensionPromptDialog.tsx
index 27747279f,27747279f..7bd1a8c28
--- a/apps/desktop/src/components/ExtensionPromptDialog.tsx
+++ b/apps/desktop/src/components/ExtensionPromptDialog.tsx
@@@ -21,6 -21,6 +21,10 @@@ export function ExtensionPromptHost()
useEffect(() => {
const offPrompt = api.onExtensionPrompt((prompt) => {
++ if (prompt.cancelled) {
++ setQueue((prev) => prev.filter((item) => item.promptId !== prompt.promptId));
++ return;
++ }
setQueue((prev) => (prev.some((p) => p.promptId === prompt.promptId) ? prev : [...prev, prompt]));
});
const offStatus = api.onExtensionStatus((event) => {
diff --cc apps/desktop/test/agent-extensions.test.mjs
index 0e2846c1d,0e2846c1d..3cde138f7
--- a/apps/desktop/test/agent-extensions.test.mjs
+++ b/apps/desktop/test/agent-extensions.test.mjs
@@@ -243,21 -243,21 +243,43 @@@ test("ui requests: notify and status pa
assert.equal(b.respond(events.prompts[0].promptId, true), true);
assert.deepEqual(await confirm, { kind: "confirm", value: true });
await new Promise((r) => setTimeout(r, 0));
-- b.respond(events.prompts[1].promptId, "b");
++ b.respond(events.prompts.filter((prompt) => !prompt.cancelled)[1].promptId, "b");
assert.deepEqual(await select, { kind: "select", value: "b" });
-- assert.deepEqual(await b.requestUi(envelope({ kind: "input", title: "Name" })), { kind: "input", value: undefined });
++ assert.deepEqual(await b.requestUi(envelope({ kind: "input", title: "Name" })), { kind: "input", value: undefined, cancelled: true });
const aborted = b.requestUi(envelope({ kind: "confirm", title: "x", message: "" }, "s9"));
await new Promise((r) => setTimeout(r, 0));
b.cancelPrompts("s9");
-- assert.deepEqual(await aborted, { kind: "confirm", value: false });
++ assert.deepEqual(await aborted, { kind: "confirm", value: false, cancelled: true });
assert.equal(b.pendingPromptCount(), 0);
const { b: headless } = bridge({ hasRenderer: () => false });
await assert.rejects(headless.requestUi(envelope({ kind: "input", title: "x" })), (err) => err.errorCode === "UNSUPPORTED");
});
++test("cancellation retires only the matching request and drops queued prompts", async () => {
++ const { b, events } = bridge();
++ const envelope = (requestId, extensionId = "one", request = { kind: "confirm", title: requestId, message: "" }) =>
++ ({ sessionId: "session", extensionId, extensionLabel: extensionId, requestId, request });
++ const first = b.requestUi(envelope("first"));
++ const queued = b.requestUi(envelope("queued"));
++ await Promise.resolve();
++ await b.requestUi(envelope(undefined, "two", { kind: "cancel", requestId: "first" }));
++ assert.equal(b.pendingPromptCount(), 1, "another extension cannot cancel this request");
++ await b.requestUi(envelope(undefined, "one", { kind: "cancel", requestId: "queued" }));
++ b.cancelPrompts("session");
++ assert.deepEqual(await first, { kind: "confirm", value: false, cancelled: true });
++ assert.deepEqual(await queued, { kind: "confirm", value: false, cancelled: true });
++ assert.equal(events.prompts.filter((p) => !p.cancelled).length, 1);
++ assert.equal(events.prompts.at(-1).cancelled, true);
++ const fresh = b.requestUi(envelope("fresh"));
++ await Promise.resolve();
++ await b.requestUi(envelope(undefined, "one", { kind: "cancel", requestId: "first" }));
++ assert.equal(b.respond(events.prompts.at(-1).promptId, true), true);
++ assert.deepEqual(await fresh, { kind: "confirm", value: true });
++});
++
test("importing a pi extension directory or file generates a plugin holding agent.extension", () => {
const root = mkdtempSync(join(tmpdir(), "pi-ax-import-"));
const importRoot = join(root, "imported");
diff --cc apps/desktop/test/e2e/trusted-extensions/drive.mjs
index 93c833dba,93c833dba..907e0746d
--- a/apps/desktop/test/e2e/trusted-extensions/drive.mjs
+++ b/apps/desktop/test/e2e/trusted-extensions/drive.mjs
@@@ -1,5 -1,5 +1,6 @@@
// MCP-control driver for the trusted extensions E2E run.
--import { readFileSync, existsSync } from "node:fs";
++import { readFileSync, existsSync, writeFileSync } from "node:fs";
++import { connectRenderer } from "./renderer.mjs";
import { join } from "node:path";
const root = process.env.E2E_ROOT || "/tmp/pi-ext-e2e";
@@@ -48,6 -48,6 +49,19 @@@ async function waitForTurn(sessionId, t
throw new Error("turn did not finish");
}
++async function waitForReply(sessionId, userText) {
++ const deadline = Date.now() + 10_000;
++ while (Date.now() < deadline) {
++ const detail = await tool("pi_session_get", { id: sessionId });
++ const messages = detail?.session?.messages ?? [];
++ const index = messages.findLastIndex((message) => message.role === "user" && message.content === userText);
++ const reply = index < 0 ? undefined : messages.slice(index + 1).find((message) => message.role === "assistant");
++ if (reply?.content) return reply;
++ await sleep(50);
++ }
++ throw new Error("Current turn reply was not persisted");
++}
++
await rpc("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "e2e", version: "0" } });
await tool("pi_project_open", { path: project });
const created = await tool("pi_session_create", { title: "ext e2e", projectPath: project, mode: "agent" });
@@@ -145,26 -145,26 +159,22 @@@ for (let i = 0; i < 40; i++)
const now = readFileSync(logPath, "utf8").split("\n").filter((l) => l.includes("extension prompt")).length;
if (now > before6) break;
}
--// The open input prompt resolves undefined on abort; the handler's later
--// prompts open normally and are answered here like the dialog would.
++// Abort retires the command itself, including later UI and exec calls.
++const renderer = await connectRenderer(process.env.E2E_CDP_PORT);
++await renderer.waitForDialog(true);
++writeFileSync(join(root, "prompt-active.png"), Buffer.from(await renderer.screenshot(), "base64"));
const seen6 = new Set(readFileSync(logPath, "utf8").split("\n").map((l) => /"promptId":"([^"]+)"/.exec(l)?.[1]).filter(Boolean));
await tool("pi_agent_abort", { sessionId });
--for (let i = 0; i < 40; i++) {
-- await sleep(250);
-- for (const line of readFileSync(logPath, "utf8").split("\n").filter((l) => l.includes("extension prompt"))) {
-- const m = /"promptId":"([^"]+)".*?"kind":"(input|select|confirm)"/.exec(line);
-- if (!m || seen6.has(m[1])) continue;
-- seen6.add(m[1]);
-- await tool("pi_desktop_invoke", { operation: "extensions/ui/respond", args: [{ promptId: m[1], value: answers[m[2]] }], confirm: true });
-- }
-- if (readFileSync(join(root, "hooks.log"), "utf8").includes("args=aborted")) break;
--}
++await renderer.waitForDialog(false);
++writeFileSync(join(root, "prompt-retired.png"), Buffer.from(await renderer.screenshot(), "base64"));
++renderer.close();
++check("Stop removes the extension dialog from the real renderer", true);
let abortResult;
try { abortResult = await Promise.race([abortRun, sleep(20000).then(() => "timeout")]); } catch (e) { abortResult = String(e); }
const hooksAfterAbort = readFileSync(join(root, "hooks.log"), "utf8");
--// The handler's own log line is the product evidence; the command's reply can
--// trail it when the MCP session is busy, so it is reported but not asserted.
--check("abort dismissed the open prompt and the command finished", /greet undefined blue true args=aborted exec=exec-ok/.test(hooksAfterAbort), JSON.stringify(abortResult) + " " + hooksAfterAbort.split("\n").filter((l) => l.includes("args=aborted")).join(" | "));
++check("abort retires the command before later prompts and exec", abortResult?.ok === true && !hooksAfterAbort.includes("args=aborted"), JSON.stringify(abortResult));
++const after6 = readFileSync(logPath, "utf8").split("\n").map((l) => /"promptId":"([^"]+)"/.exec(l)?.[1]).filter(Boolean);
++check("aborted command publishes no additional prompts", after6.every((id) => seen6.has(id)));
// 7) sendUserMessage goes through the Host-owned queue (D386) and runs a turn
const queued = await invoke("extensions/commands/run", { sessionId, name: "queue", args: "" });
@@@ -205,8 -205,8 +215,7 @@@ check("the session binding is persiste
// transport instead of a host adapter.
await tool("pi_agent_prompt", { sessionId, content: "say hi through your own transport" });
await waitForTurn(sessionId);
--const pluginTurn = await tool("pi_session_get", { id: sessionId });
--const pluginAssistant = [...(pluginTurn?.session?.messages ?? [])].reverse().find((m) => m.role === "assistant");
++const pluginAssistant = await waitForReply(sessionId, "say hi through your own transport");
check("the plugin's own stream served the turn", /plugin-transport-ok/.test(pluginAssistant?.content ?? ""), pluginAssistant?.content);
// registerProvider is the upstream compatibility alias: the same plugin-owned
@@@ -217,8 -217,8 +226,7 @@@ const aliasLine = lastLine("agent_mode
check("the alias registers the same plugin-owned shape", /setModel=true model=cc-alias-1 provider=extension-agent:/.test(aliasLine), aliasLine);
await tool("pi_agent_prompt", { sessionId, content: "say hi through the alias" });
await waitForTurn(sessionId);
--const aliasTurn = await tool("pi_session_get", { id: sessionId });
--const aliasAssistant = [...(aliasTurn?.session?.messages ?? [])].reverse().find((m) => m.role === "assistant");
++const aliasAssistant = await waitForReply(sessionId, "say hi through the alias");
check("the alias provider's transport served the turn", /alias-transport-ok/.test(aliasAssistant?.content ?? ""), aliasAssistant?.content);
console.log("RESULTS " + JSON.stringify(results));
diff --cc apps/desktop/test/e2e/trusted-extensions/renderer.mjs
index 000000000,000000000..30b20c3ee
new file mode 100644
--- /dev/null
+++ b/apps/desktop/test/e2e/trusted-extensions/renderer.mjs
@@@ -1,0 -1,0 +1,41 @@@
++/** Inspect the real renderer; assertions wait on observable dialog state. */
++export async function connectRenderer(port) {
++ const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
++ const target = targets.find((entry) => entry.type === "page" && entry.webSocketDebuggerUrl);
++ if (!target) throw new Error("Missing Electron renderer target");
++ const socket = new WebSocket(target.webSocketDebuggerUrl);
++ await new Promise((resolve, reject) => {
++ socket.addEventListener("open", resolve, { once: true });
++ socket.addEventListener("error", reject, { once: true });
++ });
++ let sequence = 0;
++ const pending = new Map();
++ socket.addEventListener("message", ({ data }) => {
++ const reply = JSON.parse(String(data));
++ const waiter = pending.get(reply.id);
++ if (!waiter) return;
++ pending.delete(reply.id);
++ clearTimeout(waiter.timer);
++ if (reply.error) waiter.reject(new Error(reply.error.message));
++ else waiter.resolve(reply.result);
++ });
++ const call = (method, params) => new Promise((resolve, reject) => {
++ const id = ++sequence;
++ const timer = setTimeout(() => { pending.delete(id); reject(new Error(`${method} timed out`)); }, 10_000);
++ pending.set(id, { resolve, reject, timer });
++ socket.send(JSON.stringify({ id, method, params }));
++ });
++ return {
++ async waitForDialog(present) {
++ const deadline = Date.now() + 10_000;
++ while (Date.now() < deadline) {
++ const reply = await call("Runtime.evaluate", { expression: "Boolean(document.querySelector('[aria-labelledby^=\"extension-prompt-\"]'))", returnByValue: true });
++ if (reply.result?.value === present) return;
++ await new Promise((resolve) => setTimeout(resolve, 50));
++ }
++ throw new Error(`Extension dialog did not become ${present ? "visible" : "absent"}`);
++ },
++ async screenshot() { return (await call("Page.captureScreenshot", { format: "png" })).data; },
++ close() { socket.close(); },
++ };
++}
diff --cc apps/desktop/test/extension-cancellation.test.mjs
index 000000000,000000000..ec253f1bc
new file mode 100644
--- /dev/null
+++ b/apps/desktop/test/extension-cancellation.test.mjs
@@@ -1,0 -1,0 +1,75 @@@
++import assert from "node:assert/strict";
++import test from "node:test";
++import { register } from "node:module";
++import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
++import { tmpdir } from "node:os";
++import { join } from "node:path";
++
++register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
++const { AgentExtensionBridge } = await import("../electron/main/agent-extensions.ts");
++const { TrustedExtensionRunner, clearTrustedExtensionCache } = await import("../../../packages/agent-runtime/src/extensions/runner.ts");
++const { requestExtensionUi } = await import("../../../packages/agent-runtime/src/extensions/ui-request.ts");
++
++test("Main cancellation crosses the real UI bridge and retires only the old command", async () => {
++ const root = mkdtempSync(join(tmpdir(), "pi-ext-cancel-path-"));
++ const entry = join(root, "fixture.ts");
++ writeFileSync(entry, `export default function(pi) {
++ pi.registerCommand("old", { handler: async (_args, ctx) => {
++ try { await ctx.ui.input("Old prompt"); } catch {}
++ await ctx.ui.select("Stale followup", ["x"]);
++ pi.sendUserMessage("stale");
++ }});
++ pi.registerCommand("fresh", { handler: async (_args, ctx) => {
++ if (await ctx.ui.confirm("New prompt", "Continue?")) await pi.sendUserMessage("fresh");
++ }});
++ }`);
++ const prompts = [];
++ const messages = [];
++ let shown;
++ let ready = new Promise((resolve) => { shown = resolve; });
++ const broker = new AgentExtensionBridge({
++ hasRenderer: () => true, onChanged() {}, onToast() {}, onStatus() {},
++ onPrompt(prompt) { prompts.push(prompt); if (!prompt.cancelled) shown(prompt); },
++ });
++ const runner = new TrustedExtensionRunner({
++ specs: [{ id: entry, entry, label: "Fixture", root, source: "plugin" }],
++ bridge: {
++ sessionId: "session", cwd: root,
++ getModel: () => ({}), setModel: async () => false,
++ getThinkingLevel: () => "off", setThinkingLevel() {},
++ isIdle: () => true, abort() {}, hasPendingMessages: () => false,
++ getContextUsage: () => undefined, compact() {}, getSystemPrompt: () => "",
++ getActiveTools: () => [], getAllTools: () => [], setActiveTools() {},
++ getSessionName: () => "fixture", setSessionName() {},
++ sendUserMessage: (text) => messages.push(text), waitForIdle: async () => {},
++ newSession: async () => ({ cancelled: false }), fork: async () => ({ cancelled: false }),
++ requestUi: (extension, request, signal) => requestExtensionUi(
++ (envelope) => broker.requestUi(envelope),
++ { sessionId: "session", extensionId: extension.id, extensionLabel: extension.label, request }, signal),
++ publishCommands() {}, publishDiagnostics() {},
++ },
++ });
++ try {
++ await runner.load();
++ const old = runner.runCommand("old", "");
++ const oldPrompt = await ready;
++ broker.cancelPrompts("session");
++ await old;
++ assert.equal(prompts.filter((prompt) => !prompt.cancelled).length, 1);
++ assert.deepEqual(messages, []);
++ assert.equal(prompts.at(-1).cancelled, true);
++ ready = new Promise((resolve) => { shown = resolve; });
++ const fresh = runner.runCommand("fresh", "");
++ const freshPrompt = await ready;
++ assert.equal(broker.respond(oldPrompt.promptId, true), false);
++ assert.equal(broker.respond(freshPrompt.promptId, true), true);
++ await fresh;
++ assert.deepEqual(messages, ["fresh"]);
++ assert.equal(broker.pendingPromptCount(), 0);
++ } finally {
++ broker.cancelPrompts("session");
++ await runner.dispose();
++ clearTrustedExtensionCache();
++ rmSync(root, { recursive: true, force: true });
++ }
++});
diff --cc docs/adr/README.md
index 9d1c8a5c4,4293dffbe..b23a5c1f5
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@@ -20,6 -20,6 +20,7 @@@ Each ADR includes
| ID | Title | Status |
|---|---|---|
++| trusted-extension-operation-ownership | [Trusted extension operation ownership](trusted-extension-operation-ownership.md) | Implemented candidate |
| scheduled-desktop-automations | [Desktop automation scheduling](scheduled-desktop-automations.md) | Accepted for implementation |
| subagent-model-fallback | [Ordered subagent model fallback](subagent-model-fallback.md) | Accepted for implementation |
| subagent-model-opt-in | [Separate Subagent Model Opt-In from Definition Pins](subagent-model-opt-in.md) | Accepted for implementation |
diff --cc docs/adr/trusted-extension-operation-ownership.md
index 000000000,000000000..48011e617
new file mode 100644
--- /dev/null
+++ b/docs/adr/trusted-extension-operation-ownership.md
@@@ -1,0 -1,0 +1,40 @@@
++# ADR: Trusted extension operation ownership
++
++- Status: Implemented candidate
++- Related: #816, #788, ADR 0214, ADR 0215, spec 07-plugins/16
++
++## Context
++
++Retiring a hook wait alone leaves SDK subprocesses and UI requests alive.
++Commands and tools can resume after Stop and publish work into the next turn.
++Trusted modules run in-process, so a deadline cannot terminate arbitrary JS.
++
++## Decision
++
++Give each factory, event handler, command and tool execution an invocation
++scope propagated through async context. Retire the scope on completion,
++timeout, cancellation and disposal. Guard SDK calls against their original
++scope; pass a cooperative signal to contexts and tools. Own and terminate
++SDK subprocess groups and address UI cancellation by session, extension and
++request ID. Copy result-bearing event payloads and commit timely header edits.
++
++Preserve the 30-second event/load budget, but do not impose it on commands
++or tools: legitimate long tasks continue until explicitly stopped. Calls
++already admitted to Host persistence are not transactions that can be undone
++by cancelling a JavaScript wait. Suppress subsequent local continuation.
++
++## Alternatives
++
++A fixed 30-second limit for all tools would break legitimate long jobs.
++Keeping session-wide cancellation alone could retire a new invocation's UI.
++Executing every trusted module in a separate process would change the extension
++contract and is outside this focused fix.
++
++## Consequences
++
++SDK work detached from a completed callback must move into an awaited command
++or tool. Cancelled commands stop instead of continuing through dismissed prompts.
++Direct Node operations, escaped process groups and synchronous JS remain outside
++the cancellation guarantee. No new sandbox, permissions or persistence migration
++is introduced. The UI wire contract gains optional request identity and prompt
++retirement; older requests still support whole-session cancellation.
diff --cc docs/project/unreleased.md
index 12f7e73bd,ef6cbdb5b..39116754c
--- a/docs/project/unreleased.md
+++ b/docs/project/unreleased.md
@@@ -1,14 -1,10 +1,23 @@@
# Unreleased changes
++- Trusted extension cancellation now retires SDK commands, tool updates,
++ subprocesses and queued or visible prompts. Late hook payload mutations are
++ isolated; legitimate long commands and tools retain their runtime budget.
++
+- A stored hosted web-search record that cannot be replayed no longer fails every
+ later request in that conversation: the message continues without search replay,
+ so histories written before the contract change stay usable.
+
+- Hosted web search now has a complete replay and estimation contract, including
+ tool/Task continuation and restart recovery. Context rebuilding preserves
+ system-prefix semantics, and structured local preparation failures no longer
+ masquerade as retryable provider failures. Existing search histories need no migration.
+
+ - Trusted extension startup, shutdown, and notification handlers now have
+ bounded waits. Stop cancels pending hook waits before a model request, and
+ disposal ignores late results and runs shutdown once. Deferred event
+ registrations now appear in plugin diagnostics.
+
- The Composer reasoning slider now moves smoothly to clicked or
keyboard-selected levels, follows dragging immediately, and respects
reduced-motion settings. Rapid clicks redirect the animation; failed saves
diff --cc docs/spec/06-delivery/04-e2e-test-plan.md
index 6c6930488,5382665db..47e63b1b8
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@@ -14508,60 -14394,21 +14508,86 @@@ the latest destination. These assertion
cover ownership, deletion, repeated/bounded forks, retained checkpoint paths,
expired inputs, rollback, and symlink rejection.
+### E2E-SCHEDULED-dispatch
+
+- **Scenario:** Independent task dispatch.
+- **Expected:** The Electron runner admits independent due tasks without awaiting another task's prompt setup. Local in-flight ownership is keyed by task ID and Host instance until setup settles; Host remains authoritative for enabled, due and overlap checks. A replaced Host's completion cannot clear its successor's local ownership. Stop prevents new polls; admitted work keeps the existing execution/failure lifecycle. Failures remain observable and the 90-second late policy is unchanged.
+- **Automation:** `node --experimental-strip-types scripts/e2e-scheduled-dispatch.mjs` uses an isolated real Host and SQLite profile. Inference is not sent to a live provider.
+### E2E-SCHEDULED-project-removal
+
+- **Scenario:** Project removal and automations.
+- **Expected:** Removing a project pauses its bound scheduled tasks without deleting their definitions, schedule, workspace binding or run history. Session references in history may become null when the project's conversations are removed. Already admitted task runs block removal even before a conversation turn starts. Tasks belonging to other projects and unbound legacy tasks are unaffected. Explicit resume or Run now may recreate a project from the preserved path; automatic polling cannot do so while paused.
+- **Automation:** `node --experimental-strip-types scripts/e2e-scheduled-project-removal.mjs` uses an isolated real Host and SQLite profile. Inference is not sent to a live provider.
+### E2E-SCHEDULED-legacy-pause
+
+- **Scenario:** Legacy task maintenance.
+- **Expected:** Agent tools allow title, prompt and pause updates on legacy automatic tasks without a schedule, including an echoed unchanged cadence. These edits do not arm the task or capture the foreground workspace. Explicit enabling, a cadence change or a supplied schedule still follows schedule validation. Resume requires an explicit valid schedule; Manual-to-Hourly retains its existing default interval behavior.
+- **Automation:** `node --experimental-strip-types scripts/e2e-scheduled-legacy-maintenance.mjs` uses an isolated real Host and SQLite profile. Inference is not sent to a live provider.
+### E2E-SCHEDULED-calendar-intent
+
+- **Scenario:** Calendar intent.
+- **Expected:** The optional config_json.calendarConfigured boolean distinguishes an explicitly configured Daily/Weekly calendar from Hourly's internal schedule placeholder. Without the key, legacy Daily/Weekly schedules are treated as configured; legacy Hourly schedules retain their values but require an explicit schedule when converting to Daily/Weekly. Known calendar intent survives Hourly and restart, including midnight. Clearing or replacing the calendar with a different non-calendar placeholder clears intent. This additive extension needs no table/schema migration; older versions ignore it and cannot enforce the new conversion guard. Metadata-only edits and Manual-to-Hourly remain unchanged.
+- **Automation:** `node --experimental-strip-types scripts/e2e-scheduled-calendar-intent.mjs` uses an isolated real Host and SQLite profile. Inference is not sent to a live provider.
+### E2E-SCHEDULED-paths
+
+- **Scenario:** Workspace identity.
+- **Expected:** Stored workspace bindings use the existing project canonicalization contract on both write and read. On Windows, slash direction, case, trailing separators and extended path prefixes do not hide a task from its own project's conversation. The distinction between missing legacy bindings and explicit null remains unchanged. Foreign-project tools cannot list or mutate bound tasks.
+- **Automation:** `node --experimental-strip-types scripts/e2e-scheduled-paths.mjs` uses an isolated real Host and SQLite profile. Inference is not sent to a live provider.
+
+## Hosted-search continuation contract (offline sidecar)
+
+**Scope:** ADR 0297; provider-hosted search content, estimation, local tools,
+Task delegation, and saved-history recovery. No real model or search service.
+
+**Entry:** `pnpm test:e2e:hosted-search`, which rebuilds the shared
+package and `@pi-desktop/agent-runtime` sidecar bundle. The test starts that
+bundle over its ordinary stdio RPC interface, with an isolated data root,
+a synthetic Host and a loopback-only Responses endpoint. Source-only mocks
+or an already installed desktop application do not satisfy this test.
+
+| Case | Required observation |
+| --- | --- |
+| Search then new user prompt | Valid search item is replayed and the second turn completes. |
+| Search then ordinary local tool | A real tool round completes and the next provider request is prepared without type/estimation failure. |
+| Search then Task | Actual delegation orchestration runs against a synthetic provider; parent continuation finishes without repeated local errors. |
+| Saved search history restored | A fresh runtime preserves search replay without adding fake tool fields or rewriting the original record. |
+| Usage invalidated by a real prefix change | The isolated sidecar changes instructions during a real Read round; the prior nonzero usage no longer covers that prefix, and continuation succeeds. |
+| Invalid saved replay container | Restore returns safe INTERNAL/context-validation, sends no provider request or persistence Host RPC, and keeps the process healthy. In-memory immutability is checked by the replay unit tests. |
+| Unknown saved search phase | The same explicit rejection is observed without silently discarding the search record. |
+
+**Companion gates:** Responses/Azure/Anthropic adapter contracts; typed search
+phases; zero/valid/stale usage; changed/unchanged system prefix and tool ledger;
+search content growth and CJK output budgets; structured local preparation
+failures without retry/fetch, ordinary transport retry and cancellation. Dependency upgrades must run
+these gates against the locked dependency version and record the tested bundle.
+
+**Evidence:** record build and test exit codes, baseline SHA, dependency versions,
+artifact identity and independent review in
+`docs/project/hosted-search-contract-verification.md`. Never record private
+conversation content or credentials. A skipped test remains NOT RUN, not PASS.
++
+ ### E2E-HOOKS-cancel-and-dispose
+
++- **Issue #816 extension:** Cancel a command while its prompt is visible and
++ verify the real renderer removes the dialog, no later prompts or exec occur,
++ and the next command/turn succeeds. The trusted-extension Electron driver
++ checks the DOM via CDP. Runner tests cover long commands, stopped context waits,
++ tool cancellation and late updates, detached header payloads and recovery;
++ process tests use a real parent/child tree with readiness synchronization.
++
+ - **Preconditions:** An isolated Desktop profile, deterministic local provider,
+ and a trusted plugin with a waiting preflight handler.
+ - **Steps:** Start a prompt; stop while the handler waits; release the old
+ handler; send another prompt. Repeat with runtime disposal. Load another
+ fixture with stalled startup/shutdown handlers and a deferred event.
+ - **Expected:** No provider request starts for the stopped/disposed prompt;
+ the next prompt completes. Late results cannot restart work. Shutdown runs
+ once, waits time out per handler, and deferred registrations are diagnosed
+ without disabling supported handlers.
+ - **Specs:** 07-plugins/16 §6.
+ - **Acceptance:** Responsive cancellation and bounded extension lifecycle waits.
+ - **Milestone:** Hooks P0.
+ - **Status:** Runner and real Runtime/local-HTTP integration automated in
+ `extensions/runner.test.ts` and `extensions/runtime-lifecycle.test.ts`.
- Electron wiring is covered by the existing trusted-extension E2E suite;
- this stop/dispose scenario is not yet driven through the renderer.
++ The trusted-extension Electron driver exercises the Stop path through the
++ real renderer via CDP and records the visible and retired dialog states.
diff --cc docs/spec/07-plugins/16-trusted-extensions.md
index feba79e98,7f8139a48..94fcffaa8
--- a/docs/spec/07-plugins/16-trusted-extensions.md
+++ b/docs/spec/07-plugins/16-trusted-extensions.md
@@@ -318,9 -318,36 +318,54 @@@ are honored where the event type define
| `input` | v1 note: not emitted; Host queue admission is not wired yet | n/a |
| `user_bash`, `session_before_switch`, `session_before_tree`, `session_tree`, `ui_prompt_start`, `ui_prompt_end` | Not emitted in v1 | n/a |
- A handler that throws is logged as a diagnostic and treated as returning
- `undefined`. A handler that exceeds 30 s for a result-bearing event is
- abandoned with a diagnostic and the turn proceeds with the unmodified value.
+ Desktop event capabilities are maintained in
+ `packages/agent-runtime/src/extensions/event-capabilities.ts`: result,
+ mutation, notification, or deferred. Registering a deferred event remains
+ accepted but emits an `unsupported_api` diagnostic in the existing plugin
+ diagnostics; it does not prevent supported handlers from loading.
+
+ Every event handler, including startup, shutdown, and notifications, has a
+ 30-second **per-handler** wait budget. Module loading and factory initialization
+ also have separate 30-second wait budgets, reported as load/factory errors.
+ A handler that throws or times out produces a diagnostic and counts as
+ `undefined`; subsequent handlers still run in registration order. Existing
+ result folding and fail-open semantics are unchanged. This is not a mandatory
+ security-check mechanism. Multiple stalled handlers can each consume their budget.
+
+ Abort retires pending event dispatches. Disposal first rejects new dispatches
+ and cancels existing waits, then runs shutdown once even under concurrent
+ disposal. Old dispatches return no result and never invoke their remaining
+ handlers; late settlements do not add diagnostics or overwrite results. A
+ factory finishing after disposal cannot publish tools or commands. Runtime
+ shutdown cancels agent work before waiting for extension shutdown. Stopping
+ during preflight hooks prevents the provider request and retains the user
+ message; a later prompt can run normally.
+
-These are bounds on waiting, not forced execution isolation: an in-process
-handler can still block the JS thread or perform external side effects after
-timeout/cancellation. No new public cancellation parameter is added. Slash
-commands and extension tool execution retain their existing lifecycle. Native
-Pi sessions use the upstream SDK lifecycle and are outside this Desktop change.
++Each invocation now owns an abort signal exposed as `ctx.signal`. Finishing,
++timing out, stopping or disposing retires that invocation. SDK calls from its
++late callbacks are rejected, including commands waiting for idle, session creation,
++fork or queue admission. An already admitted Host transaction is not rolled back;
++late completion cannot start a subsequent queue-priority update or mutate runtime
++model state. Commands and tool executions have no event-style 30-second limit:
++they may run until completion, their supplied signal aborts, Stop, or disposal.
++Tool updates/results after retirement are discarded; accepted updates and results
++are detached before publication so later extension mutations cannot rewrite them.
++SDK `exec` owns its process group/tree and terminates it on scope retirement or
++its explicit timeout;
++disposal waits for tracked process cleanup, with cleanup failures diagnosed.
++Processes deliberately escaping the group and direct Node API spawns are outside
++this ownership contract.
++
++Result-bearing hook inputs and outputs are detached copies. Header mutations
++are committed only after a handler succeeds within its budget. Late in-place
++mutations cannot alter the caller's payload or another handler's input.
++
++These are cooperative lifecycle boundaries, not forced execution isolation:
++trusted code may still block the JS thread or use direct Node APIs for external
++side effects. Native Pi sessions use the upstream SDK lifecycle and are outside
++this Desktop change. See ADR `trusted-extension-operation-ownership`.
+ The 30-second event budget also applies when a handler waits for a UI prompt;
+ the UI broker's own prompt timeout does not extend that budget.
## 7. Tools
@@@ -370,6 -397,6 +415,11 @@@ Rules
- One pending interactive prompt per session. A second call queues behind
the first.
- Aborting the turn cancels pending prompts with the abort values above.
++- Every new sidecar UI request has an invocation-owned request ID. Cancellation
++ targets that ID plus the session/extension identity, drops queued requests,
++ and sends retirement for the exact visible prompt to the renderer. Stale
++ cancellation cannot close a later request. Legacy requests without IDs retain
++ session-wide cancellation. Settled queue tails are released.
- Under remote control (Post-MVP) the prompt fails immediately with
`UNSUPPORTED` until the remote protocol routes it; that routing is v3.
- Prompts show the extension label and source path so the user knows who is
diff --cc docs/spec/08-meta/decisions-log.md
index 4cc7e2031,b5c514218..5b53c9982
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@@ -6557,41 -6557,16 +6557,55 @@@ that was sitting at the bottom — incl
- An entry that still fails to decode costs itself, not the array: the readable entries survive in their stored order, and the failure is reported on the host log with the provider id, the entry's index and the reason, so it is locatable rather than silent. An absent `models` key, an empty array, and an array whose every entry was unreadable all still read as the legacy binding, so a provider stays selectable whatever its stored shape; only the third is reported, because an empty array is a legal state and an absent one predates bindings.
- Nothing is rewritten on disk and the write path remains explicit: `providers.update` still persists exactly the bindings the client sends. Before accepting an explicit model-array replacement, the host checks the stored value and rejects it with `MODEL_BINDINGS_DEGRADED` when the value is degraded, so a partial settings view cannot erase unreadable entries; unrelated provider fields remain updatable. See `03-runtime/12-provider-config-schema.md` §2.
+## 2026-09-21 — A hand-typed custom model id is seeded from the model library (D611)
+
+- Adding a custom model by id gave every binding the generic 128,000 / 8,192
+ seed and no thinking levels, even when the model library already published
+ that id, so the user had to retype limits the app could have known.
+- The settings picker now matches the typed id against models.dev through a new
+ snapshot-only renderer channel, `providers.lookupModel`, and seeds the binding
+ the way a picked model is seeded — published context window, max output
+ tokens, and thinking levels — while the stored id stays exactly what the user
+ typed. The row is written first with the generic seed and upgraded in place
+ when the answer arrives, so a slow, failed, or unpublished lookup still leaves
+ exactly one usable row, and an edit or delete made meanwhile is never
+ overwritten.
+- No provider network request, host call, schema, or persisted-data change; a
+ miss behaves exactly as before. See `03-runtime/12-provider-config-schema.md`
+ §2 and §9.
+
+## 2026-09-21 — Adding a provider never takes over an app default (D612)
+
+- The provider add flow wrote `defaultProviderId`/`defaultModelId`, and the
+ image flow wrote `imageGeneration`, whether or not the app already had one, so
+ configuring a second service silently moved the default away from the model
+ the user was running.
+- The add flow now follows the rule editing already followed: a stored default
+ survives while it still resolves, and only an unresolvable one is replaced.
+ For the model default that means the default provider row still exists and
+ still offers the model — the same resolution the settings summary renders
+ through — so an id left behind by a deleted provider is not a default and a
+ newly added provider may fill what would otherwise render as unset. The image
+ default uses the mirrored rule against its stored binding, and its candidate
+ list still accumulates the new provider's image models, so nothing vanishes
+ from the picker.
+- Settings are written only when no default resolves; the explicit "make
+ default" action, the edit path, and the fallback to the first remaining
+ binding after removing the selected model are unchanged. Behaviour is pinned
+ by `apps/desktop/test/default-model-display.test.mjs` and
+ `apps/desktop/test/image-generation-default.test.mjs`, with
+ `provider-model-config.test.mjs` asserting the add branch consults them.
++
+ ## 2026-09-21 — Bound Desktop trusted-extension lifecycle waits
+
+ - Apply the existing 30-second handler budget to notification, startup and
+ shutdown handlers as well as result handlers; module loading and factory
+ initialization each use the same budget. This changes previously unbounded
+ waits, including event handlers waiting for a UI answer.
+ - Abort retires current waits; disposal rejects new dispatches and runs shutdown
+ once. Late settlements cannot supply results to the retired dispatch. Existing
+ fail-open error handling, result folding, plugin ownership and permissions
+ remain unchanged. In-process code is not forcibly terminated.
+ - Deferred events remain registrable and now appear in existing diagnostics.
+ See `07-plugins/16-trusted-extensions.md` §6 and
+ `E2E-HOOKS-cancel-and-dispose`.
diff --cc docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index e25fb7794,1ea91e79b..31d466579
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@@ -8600,77 -8551,16 +8600,96 @@@ the latest destination. These assertion
覆盖附件归属、删除、重复与截断分支、保留的压缩检查点引用、过期输入、失败回滚
及符号链接拒绝。
+### E2E-011f 补充:入队确认前的操作锁定
+
+- **前提**:会话正在回复,可控制 Host 入队请求的完成时刻。
+- **步骤**:发送一条后续消息,暂停入队;尝试编辑或删除;释放入队后再次编辑或删除,
+ 然后刷新队列。用带文件引用的草稿重复;让本地 Host 入队请求超过现有 RPC 超时后重试。
+- **预期**:未确认时五个行操作都禁用且提示正在保存,立即发送按钮也显示正在保存,
+ 条目不消失,也不回填第二份草稿;
+ 确认后删除能移除持久化条目,编辑完整回填草稿及文件引用,刷新不会恢复已移除条目。
+ 本地 Host 超时后移除未确认行、显示错误并恢复被拒绝的草稿,重试可正常入队。
+- **规格**:`04-ux/08-component-spec.md`、`04-ux/09-interaction-patterns.md`。
+- **验收 / 里程碑**:C、Quality / M6+。
+- **状态**:组件与状态层用户路径由 `queue-pending-actions.test.mjs` 覆盖。
+
+### E2E-SCHEDULED-dispatch
+
+- **场景**:独立分发到期任务。
+- **预期**:Electron runner 无需等待其他任务的提示词准备即可准入彼此独立的
+ 到期任务;本地所有权按任务 ID 和 Host 实例保留,Host 继续负责 enabled、
+ due 和重叠检查。停止只阻止新轮询,错误仍可观察,迟到 90 秒的规则不变。
+- **自动化**:`node --experimental-strip-types scripts/e2e-scheduled-dispatch.mjs`
+### E2E-SCHEDULED-project-removal
+
+- **场景**:删除项目与自动任务。
+- **预期**:删除项目会暂停其绑定任务,并保留任务定义、schedule、工作区绑定和
+ 运行历史;已准入的任务会阻止删除。其他项目和未绑定旧任务不受影响。用户显式
+ 恢复或 Run now 可以重新创建项目,暂停状态下的自动轮询不会这样做。
+- **自动化**:`node --experimental-strip-types scripts/e2e-scheduled-project-removal.mjs`
+### E2E-SCHEDULED-legacy-pause
+
+- **场景**:旧任务维护。
+- **预期**:Agent 工具可对缺少 schedule 的旧版自动任务修改标题、提示词或暂停,
+ 包括回传未变化的 cadence;维护不会启用任务或捕获前台工作区。显式启用、改变
+ cadence 或提供 schedule 时仍执行校验,Manual 转 Hourly 的默认间隔行为不变。
+- **自动化**:`node --experimental-strip-types scripts/e2e-scheduled-legacy-maintenance.mjs`
+### E2E-SCHEDULED-calendar-intent
+
+- **场景**:日历配置意图。
+- **预期**:可选的 `config_json.calendarConfigured` 区分明确设置的每日/每周
+ 日历时间与 Hourly 内部占位 schedule。旧版 Daily/Weekly 保留日历语义;
+ 旧版 Hourly 转换时必须明确提供 schedule。已知配置可跨 Hourly 与重启保留,
+ 包括午夜;仅修改元数据以及 Manual 转 Hourly 的行为不变。
+- **自动化**:`node --experimental-strip-types scripts/e2e-scheduled-calendar-intent.mjs`
+### E2E-SCHEDULED-paths
+
+- **场景**:工作区身份。
+- **预期**:保存和读取工作区绑定时统一使用现有项目路径规范化规则。Windows
+ 路径的斜杠方向、大小写、末尾分隔符和扩展路径前缀差异不影响同项目会话;
+ 缺失的旧版绑定与显式 null 保持不同语义,其他项目不能查询或修改绑定任务。
+- **自动化**:`node --experimental-strip-types scripts/e2e-scheduled-paths.mjs`
+ 使用隔离的真实 Host 与 SQLite 配置,不向真实提供商发送推理请求。
+
+## 原生搜索续跑契约(离线 sidecar)
+
+**范围:** ADR 0297;供应商原生搜索内容、估算、本地工具、Task 委派及历史恢复。不调用真实模型或搜索服务。
+
+**入口:** `pnpm test:e2e:hosted-search` 自行重建 shared 与 agent-runtime sidecar。
+通过普通 stdio RPC 驱动该产物,使用隔离数据目录、合成 Host 与仅回环地址的 Responses 服务。
+只测源码或使用已有桌面安装包不满足本测试。
+
+| 场景 | 必须观察到的结果 |
+| --- | --- |
+| 搜索后新用户消息 | 合法搜索项被回放,第二轮正常结束。 |
+| 搜索后普通本地工具 | 真实工具轮完成,下一模型请求准备无类型或估算错误。 |
+| 搜索后 Task | 实际委派流程使用合成模型,父代理继续且不重复报告本地错误。 |
+| 保存搜索历史后恢复 | 新运行时保留搜索回放,不添加假工具字段或改写原记录。 |
+| 真实前缀变化使 usage 失效 | 隔离 sidecar 在真实 Read 轮中更新指令;此前非零 usage 不再覆盖该前缀,续跑正常结束。 |
+| 非法历史回放容器 | 恢复返回安全的 INTERNAL/context-validation;不发送模型请求或持久化 Host RPC,进程仍健康。内存中输入不变性由回放单元测试验证。 |
+| 未知历史搜索阶段 | 明确拒绝该记录,而不是静默丢弃搜索内容;其余断言同上。 |
+
+**配套检查:** Responses/Azure/Anthropic 请求契约、搜索阶段类型、有效/零/失效 usage、
+真实与无变化的系统前缀及工具增删、搜索数据增长、中文输出预算;结构化本地准备失败不重试、不 fetch,普通传输重试与取消保持正确。依赖升级必须对锁定版本运行这些检查,记录测试的 bundle。
+
+**证据:** 记录构建和测试退出码、基线 SHA、依赖版本、产物标识及独立评审,报告位于
+`docs/project/hosted-search-contract-verification.md`。不得记录真实会话或凭据。未执行明确标为 NOT RUN,不得标为 PASS。
++
+ ### E2E-HOOKS-cancel-and-dispose
+
++- **#816 扩展验收:** 命令弹窗显示期间 Stop,真实渲染层移除弹窗,后续弹窗和 exec
++ 不再发生,下一命令或回合正常。Electron 驱动通过 CDP 检查 DOM;Runner 测试覆盖
++ 长命令、上下文等待取消、工具进度退役及头部副本;进程测试通过就绪信号同步真实父子进程。
++
+ - **前置条件:** 隔离 Desktop 配置、本地确定性模型,以及含等待型请求前处理器的可信插件。
+ - **步骤:** 发送消息,在处理器等待时停止,释放旧处理器后再次发送。另测等待时销毁
+ Runtime,并加载启动/关闭挂起以及注册未接通事件的夹具。
+ - **预期:** 被停止或销毁的请求不调用模型,后续消息正常完成。迟到结果不能重启工作。
+ 关闭只执行一次,各处理器等待有界,未接通事件产生诊断但不禁用正常处理器。
+ - **规范:** 07-plugins/16 §6。
+ - **验收:** 取消及时生效,扩展生命周期等待有界。
+ - **里程碑:** Hooks P0。
+ - **状态:** Runner 与真实 Runtime/本地 HTTP 集成通过
+ `extensions/runner.test.ts`、`extensions/runtime-lifecycle.test.ts` 自动验证。
- 现有可信扩展 E2E 覆盖 Electron 接线;本停止/销毁场景尚未由渲染层驱动。
++ 可信扩展 Electron 驱动通过 CDP 在真实渲染层执行 Stop 路径,并记录弹窗显示和
++ 退役后的状态。
diff --cc docs/zh-CN/spec/07-plugins/16-trusted-extensions.md
index 387262a64,113cf8097..d03cb8851
--- a/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md
+++ b/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md
@@@ -195,8 -195,25 +195,37 @@@ main、渲染层或插件宿主进程�
| `input` | v1 说明:不触发;Host 队列准入尚未接入 | 不适用 |
| `user_bash`、`session_before_switch`、`session_before_tree`、`session_tree`、`ui_prompt_start`、`ui_prompt_end` | v1 不触发 | 不适用 |
- 抛出异常的处理器记为诊断并视为返回 `undefined`。带返回结果的事件若处理器超过
- 30 秒,则放弃并记诊断,回合以未修改的值继续。
+ Desktop 事件能力由 `packages/agent-runtime/src/extensions/event-capabilities.ts`
+ 维护,分为返回值、原地修改、通知和未接通。未接通事件仍可注册,但会在现有插件诊断中
+ 显示 `unsupported_api`,不妨碍其他已支持的处理器加载。
+
+ 所有事件处理器(包括启动、关闭和通知)均有每个处理器 30 秒的等待上限。模块加载和
+ 工厂初始化分别有 30 秒上限,失败归入加载或工厂诊断。处理器异常或超时记诊断并视为
+ 返回 `undefined`,后续处理器按注册顺序继续。既有结果归并和失败继续策略保持不变,
+ 不能将其作为强制安全检查。多个挂起处理器可能分别耗尽各自的时间预算。
+
+ 中止会使等待中的事件派发失效。销毁先拒绝新派发并取消已有等待,再执行关闭处理器;
+ 并发销毁只关闭一次。旧派发不返回结果、不再执行剩余处理器,迟到的完成或异常不会覆盖
+ 结果或增加诊断。销毁后完成的工厂不能发布工具和命令。Runtime 在等待扩展关闭前先停止
+ Agent 工作。在请求前 hook 等待期间停止,不会继续请求模型,并保留用户消息;之后可正常
+ 发送下一条消息。
+
-这些限制只约束等待,不是强制执行隔离:进程内处理器仍可能同步阻塞 JS,或在超时、取消
-后产生外部副作用。不新增公开取消参数。扩展命令和工具保留原有生命周期;Native Pi
-会话由上游 SDK 管理,不属于本次 Desktop 变更。事件处理器等待 UI 提示时也受 30 秒限制,
++每次调用拥有独立的 `ctx.signal`,完成、超时、Stop 或销毁后失效。旧回调再调用 SDK
++会被拒绝,包括等待空闲、创建会话、fork 和发送消息的后续步骤。已提交给 Host 的事务
++不回滚,但迟到返回不再触发队列优先级更新或修改 Runtime 模型状态。命令与工具不套用
++事件的 30 秒上限,可运行至完成、传入信号取消、Stop 或销毁;迟到的工具进度和结果被丢弃。
++已采纳的工具进度和结果会先复制再发布,扩展之后的原地修改不能改写它们。`pi.exec`
++创建的进程树随作用域退出或显式超时终止,销毁等待已登记进程清理并报告失败。
++主动逃离进程组或通过 Node API 直接创建的进程不在此所有权范围。
++
++带返回值的 Hook 输入输出使用独立副本,头部修改仅在处理器及时成功后提交。
++迟到的原地修改不会影响宿主或下一处理器。UI 请求按请求 ID、会话和扩展身份取消,
++排队请求被丢弃,已显示的弹窗向渲染层发送精确退役通知;旧取消不会关闭新请求。
++
++这些是协作式生命周期约束,不是强制执行隔离:可信代码仍可同步阻塞 JS 或直接使用
++Node API 产生外部副作用。Native Pi 会话由上游 SDK 管理,不属于本次 Desktop 变更。
++事件处理器等待 UI 提示时也受 30 秒限制,
+ UI broker 自身的提示超时不会延长该预算。
## 7. 工具
diff --cc docs/zh-CN/spec/08-meta/decisions-log.md
index cb3a1f969,d925ea846..209daa2b5
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@@ -4650,30 -4650,11 +4650,39 @@@ that amendment are retired by ADR 0268
- 仍然解码失败的条目只损失自己,不损失整个数组:可读条目按存储顺序保留,失败会在宿主日志里上报,带上提供商 id、条目下标与原因,因此可定位而不是静默。缺失的 `models` 键、空数组、以及所有条目都不可读的数组,都仍旧读作 legacy 绑定,使提供商无论存储形态如何都保持可选;只有第三种会被上报,因为空数组是合法状态,而缺失键则是早于绑定机制的记录。
- 不改写磁盘上的任何内容,写路径仍是显式的:`providers.update` 依旧只持久化客户端发来的绑定。接受显式模型数组替换前,host 会检查存储值;若已降级则以 `MODEL_BINDINGS_DEGRADED` 拒绝,避免设置页的部分视图擦除不可读条目;不涉及模型数组的提供商字段仍可更新。见 `03-runtime/12-provider-config-schema.md` §2。
+## 2026-09-21 —— 手输的自定义模型 id 从模型库播种(D611)
+
+- 通过 id 新增自定义模型时,即便模型库已经发布了该 id,每条绑定仍只得到通用的
+ 128,000 / 8,192 种子值与空思考等级,用户不得不重新输入本可以自动获得的限额。
+- 设置选择器现在通过新的只读快照渲染器通道 `providers.lookupModel` 把输入的 id 与
+ models.dev 匹配,并按拾取模型的口径播种绑定——已发布的上下文窗口、最大输出 token
+ 与思考等级——同时存储的 id 仍保持用户输入的原文。记录先以通用种子值落下,答案返回
+ 后再原地升级;因此查询慢、失败或未发布时仍然只留一行可用记录,期间的编辑或删除也
+ 不会被覆盖。
+- 不访问提供商网络、不调用主机、不改 schema、不改持久化数据;未命中时行为与之前完全
+ 一致。参见 `03-runtime/12-provider-config-schema.md` §2 与 §9。
+
+## 2026-09-21 —— 新增提供商不再抢走应用默认值(D612)
+
+- 新增提供商的流程无条件写入 `defaultProviderId`/`defaultModelId`,画图流程也无条件
+ 写入 `imageGeneration`,于是配置第二个服务会把用户正在使用的默认模型、默认画图模型
+ 悄悄换掉。
+- 新增流程改为与编辑一致的规则:已存储的默认值只要能解析就保留,只有无法解析时才被
+ 替换。模型默认值的“能解析”指默认提供商行仍存在且仍提供该模型——与设置页摘要行渲染
+ 用的是同一套解析——因此提供商被删除后残留的 id 不算默认值,新增的提供商可以填补那
+ 个本来显示为未设置的位置。画图默认值用镜像规则判断其存储绑定,候选列表仍会累积新提
+ 供商的图片模型,选择器里不会少行。
+- 只有在没有任何默认值可解析时才写设置;显式的“设为默认”操作、编辑路径,以及删除已
+ 选模型后回落到首个剩余绑定的行为都不变。行为由
+ `apps/desktop/test/default-model-display.test.mjs` 与
+ `apps/desktop/test/image-generation-default.test.mjs` 固定,
+ `provider-model-config.test.mjs` 断言新增分支会走这两个判断。
++
+ ## 2026-09-21 — 限制 Desktop 可信扩展生命周期等待
+
+ - 现有 30 秒处理器预算扩展到通知、启动和关闭事件;模块加载、工厂初始化分别使用
+ 同一预算。此前无界的等待变为有界,事件内等待 UI 回答也受此限制。
+ - 中止使当前等待失效;销毁拒绝新派发且只执行一次关闭。迟到完成不能向旧派发提供
+ 结果。既有失败继续、结果归并、插件归属和权限不变,不强制终止进程内代码。
+ - 未接通事件仍可注册,并在现有诊断中显示。参见
+ `07-plugins/16-trusted-extensions.md` §6 与 `E2E-HOOKS-cancel-and-dispose`。
diff --cc packages/agent-runtime/src/extensions/handler-lifecycle.ts
index 000000000,cb555f7e7..3dc462354
mode 000000,100644..100644
--- a/packages/agent-runtime/src/extensions/handler-lifecycle.ts
+++ b/packages/agent-runtime/src/extensions/handler-lifecycle.ts
@@@ -1,0 -1,39 +1,56 @@@
++import { AsyncLocalStorage } from "node:async_hooks";
++
+ /** Owns waits, not arbitrary JavaScript or external side effects of trusted code. */
+ export class HandlerLifecycle {
+ private controller = new AbortController();
++ private readonly operations = new AsyncLocalStorage<{ signal: AbortSignal; cancel: () => void }>();
++
++ get operationSignal(): AbortSignal {
++ return this.operations.getStore()?.signal ?? this.signal;
++ }
++
++ cancelOperation(): void {
++ this.operations.getStore()?.cancel();
++ }
+
+ get signal(): AbortSignal {
+ return this.controller.signal;
+ }
+
+ cancel(): void {
+ const previous = this.controller;
+ this.controller = new AbortController();
+ previous.abort();
+ }
+
- async run<T>(work: () => T | PromiseLike<T>, signal: AbortSignal, timeoutMs: number): Promise<T> {
++ async run<T>(work: () => T | PromiseLike<T>, signal: AbortSignal, timeoutMs?: number): Promise<T> {
+ signal.throwIfAborted();
++ const owner = new AbortController();
++ const operation = AbortSignal.any([signal, owner.signal]);
+ return new Promise<T>((resolve, reject) => {
++ let settled = false;
+ const finish = (settle: () => void) => {
++ if (settled) return;
++ settled = true;
+ clearTimeout(timer);
- signal.removeEventListener("abort", abort);
++ operation.removeEventListener("abort", abort);
++ owner.abort();
+ settle();
+ };
- const abort = () => finish(() => reject(signal.reason));
- const timer = setTimeout(
++ const abort = () => finish(() => reject(operation.reason));
++ const timer = timeoutMs === undefined ? undefined : setTimeout(
+ () => finish(() => reject(new Error(`handler exceeded ${timeoutMs}ms`))),
+ timeoutMs,
+ );
- signal.addEventListener("abort", abort, { once: true });
++ operation.addEventListener("abort", abort, { once: true });
+ try {
- Promise.resolve(work()).then(
++ Promise.resolve(this.operations.run({ signal: operation, cancel: () => owner.abort() }, work)).then(
+ (value) => finish(() => resolve(value)),
+ (error: unknown) => finish(() => reject(error)),
+ );
+ } catch (error) {
+ finish(() => reject(error));
+ }
+ });
+ }
+ }
diff --cc packages/agent-runtime/src/extensions/managed-exec.test.ts
index 000000000,000000000..b41a6beeb
new file mode 100644
--- /dev/null
+++ b/packages/agent-runtime/src/extensions/managed-exec.test.ts
@@@ -1,0 -1,0 +1,36 @@@
++import { mkdtempSync, readFileSync, existsSync, rmSync } from "node:fs";
++import { tmpdir } from "node:os";
++import { join } from "node:path";
++import { expect, it } from "vitest";
++import { managedExec } from "./managed-exec.js";
++
++it("cancels an owned process tree after an explicit readiness signal", async () => {
++ const root = mkdtempSync(join(tmpdir(), "pi-owned-exec-"));
++ const ready = join(root, "ready.json");
++ const owner = new AbortController();
++ const childSource = `require('node:fs').writeFileSync(${JSON.stringify(ready)}, JSON.stringify([process.ppid,process.pid])); setInterval(()=>{},1000);`;
++ const parentSource = `require('node:child_process').spawn(process.execPath,['-e',${JSON.stringify(childSource)}],{stdio:'inherit'}); setInterval(()=>{},1000);`;
++ const pending = managedExec(process.execPath, ["-e", parentSource], root, owner.signal);
++ try {
++ await expect.poll(() => existsSync(ready)).toBe(true);
++ const pids: number[] = JSON.parse(readFileSync(ready, "utf8"));
++ owner.abort();
++ expect((await pending).killed).toBe(true);
++ for (const pid of pids) await expect.poll(() => {
++ try { process.kill(pid, 0); return true; } catch { return false; }
++ }).toBe(false);
++ } finally {
++ owner.abort();
++ await pending;
++ rmSync(root, { recursive: true, force: true });
++ }
++});
++
++it("never starts an already-cancelled exec and keeps normal command output", async () => {
++ const owner = new AbortController();
++ expect(await managedExec(process.execPath, ["-e", "process.stdout.write('ok')"], tmpdir(), owner.signal))
++ .toMatchObject({ stdout: "ok", code: 0, killed: false });
++ owner.abort();
++ expect(() => managedExec(process.execPath, ["-e", "process.exit(9)"], tmpdir(), owner.signal))
++ .toThrow();
++});
diff --cc packages/agent-runtime/src/extensions/managed-exec.ts
index 000000000,000000000..471c0b549
new file mode 100644
--- /dev/null
+++ b/packages/agent-runtime/src/extensions/managed-exec.ts
@@@ -1,0 -1,0 +1,68 @@@
++import { spawn } from "node:child_process";
++import type { ExtensionExecOptions, ExtensionExecResult } from "./runner.js";
++
++/** Own the process group created through pi.exec; direct Node spawns are unowned. */
++export function managedExec(command: string, args: string[], cwd: string,
++ owner: AbortSignal, options?: ExtensionExecOptions): Promise<ExtensionExecResult> {
++ const signal = options?.signal ? AbortSignal.any([owner, options.signal]) : owner;
++ signal.throwIfAborted();
++ return new Promise((resolve, reject) => {
++ const child = spawn(command, args, {
++ cwd: options?.cwd ?? cwd,
++ env: options?.env ? { ...process.env, ...options.env } : process.env,
++ stdio: ["ignore", "pipe", "pipe"],
++ detached: process.platform !== "win32",
++ windowsHide: true,
++ });
++ const maxBuffer = options?.maxBuffer ?? 10 * 1024 * 1024;
++ let stdout = "";
++ let stderr = "";
++ let killed = false;
++ let settled = false;
++ let killTimer: ReturnType<typeof setTimeout> | undefined;
++ let timeout: ReturnType<typeof setTimeout> | undefined;
++ const finish = (error?: unknown, code?: number | null) => {
++ if (settled) return;
++ settled = true;
++ clearTimeout(timeout);
++ clearTimeout(killTimer);
++ signal.removeEventListener("abort", kill);
++ if (error) reject(error);
++ else resolve({ stdout, stderr, code: code ?? (killed ? 143 : 0), killed });
++ };
++ const kill = () => {
++ if (killed || settled) return;
++ killed = true;
++ killTimer = setTimeout(() => finish(new Error("Extension process cleanup timed out")), 5_000);
++ if (!child.pid) return;
++ if (process.platform === "win32") {
++ const killer = spawn("taskkill", ["/PID", String(child.pid), "/T", "/F"], {
++ stdio: "ignore", windowsHide: true,
++ });
++ killer.once("error", (error) => { child.kill(); finish(error); });
++ killer.once("exit", (code) => {
++ if (code !== 0 && child.exitCode === null) {
++ child.kill();
++ finish(new Error(`Extension process-tree cleanup failed (${code})`));
++ }
++ });
++ } else {
++ try { process.kill(-child.pid, "SIGKILL"); }
++ catch (error) {
++ if (!(error instanceof Error && "code" in error && error.code === "ESRCH")) finish(error);
++ }
++ }
++ };
++ signal.addEventListener("abort", kill, { once: true });
++ if (signal.aborted) kill();
++ if (options?.timeout) timeout = setTimeout(kill, options.timeout);
++ child.stdout.on("data", (chunk: Buffer) => {
++ stdout += chunk.toString("utf8").slice(0, Math.max(0, maxBuffer - stdout.length));
++ });
++ child.stderr.on("data", (chunk: Buffer) => {
++ stderr += chunk.toString("utf8").slice(0, Math.max(0, maxBuffer - stderr.length));
++ });
++ child.once("error", (error) => finish(error));
++ child.once("close", (code) => finish(undefined, code));
++ });
++}
diff --cc packages/agent-runtime/src/extensions/operation.ts
index 000000000,000000000..fe7aad777
new file mode 100644
--- /dev/null
+++ b/packages/agent-runtime/src/extensions/operation.ts
@@@ -1,0 -1,0 +1,12 @@@
++/** Await an SDK operation without keeping a retired invocation alive. */
++export function waitForOperation<T>(work: PromiseLike<T>, signal: AbortSignal): Promise<T> {
++ return new Promise((resolve, reject) => {
++ const abort = () => { signal.removeEventListener("abort", abort); reject(signal.reason); };
++ signal.addEventListener("abort", abort, { once: true });
++ if (signal.aborted) abort();
++ Promise.resolve(work).then(
++ (value) => { signal.removeEventListener("abort", abort); if (!signal.aborted) resolve(value); },
++ (error: unknown) => { signal.removeEventListener("abort", abort); reject(error); },
++ );
++ });
++}
diff --cc packages/agent-runtime/src/extensions/runner.test.ts
index 1164ce990,3902e1d89..1d2d079cd
--- a/packages/agent-runtime/src/extensions/runner.test.ts
+++ b/packages/agent-runtime/src/extensions/runner.test.ts
@@@ -84,6 -85,148 +85,326 @@@ function fakeBridge
const flush = () => new Promise((r) => setTimeout(r, 0));
describe("TrustedExtensionRunner", () => {
++ it("retires the command when Main cancels a prompt before the runtime abort arrives", async () => {
++ const ext = spec("main-cancel", `export default function (pi) {
++ pi.registerCommand("cancel", { handler: async (_args, ctx) => {
++ try { await ctx.ui.input("First"); } catch {}
++ await ctx.ui.select("Must not appear", ["x"]);
++ pi.sendUserMessage("stale");
++ }});
++ }`);
++ const { bridge, log } = fakeBridge({ input: { kind: "input", value: undefined, cancelled: true } });
++ const runner = new TrustedExtensionRunner({ specs: [ext], bridge });
++ await runner.load();
++ await runner.runCommand("cancel", "");
++ expect(log.ui.map((request) => request.kind)).toEqual(["input"]);
++ expect(log.userMessages).toEqual([]);
++ expect(runner.getDiagnostics()).toEqual([]);
++ await runner.dispose();
++ });
++
++ it("retires a command without imposing the event timeout and blocks its late SDK calls", async () => {
++ const ext = spec("long-command", `export default function (pi) {
++ pi.registerCommand("long", { handler: async (_args, ctx) => {
++ await ctx.modelRegistry.wait;
++ pi.sendUserMessage("stale");
++ }});
++ pi.registerCommand("next", { handler: () => pi.sendUserMessage("fresh") });
++ }`);
++ const { bridge, log } = fakeBridge();
++ let release!: () => void;
++ bridge.modelRegistry = { wait: new Promise<void>((resolve) => { release = resolve; }) };
++ const runner = new TrustedExtensionRunner({ specs: [ext], bridge });
++ await runner.load();
++ vi.useFakeTimers();
++ let settled = false;
++ const running = runner.runCommand("long", "").then(() => { settled = true; });
++ await vi.advanceTimersByTimeAsync(60_000);
++ expect(settled).toBe(false);
++ runner.cancelPending();
++ await running;
++ await runner.runCommand("next", "");
++ release();
++ await vi.advanceTimersByTimeAsync(0);
++ expect(log.userMessages).toEqual(["fresh"]);
++ await runner.dispose();
++ });
++
++ it.each(["waitForIdle", "newSession", "fork"] as const)("cancels command context %s waits", async (method) => {
++ const ext = spec("context-wait", `export default function (pi) {
++ pi.registerCommand("wait", { handler: async (_args, ctx) => {
++ await ctx.${method}("entry");
++ pi.sendUserMessage("late");
++ }});
++ }`);
++ const { bridge, log } = fakeBridge();
++ const wait = new Promise<never>(() => {});
++ bridge[method] = () => wait;
++ const runner = new TrustedExtensionRunner({ specs: [ext], bridge });
++ await runner.load();
++ const running = runner.runCommand("wait", "");
++ runner.cancelPending();
++ await running;
++ expect(log.userMessages).toEqual([]);
++ await runner.dispose();
++ });
++
++ it("discards late in-place header mutations after the handler times out", async () => {
++ const ext = spec("late-headers", `export default function (pi) {
++ pi.on("before_provider_headers", async (event, ctx) => {
++ event.headers.early = "uncommitted";
++ await ctx.modelRegistry.wait;
++ event.headers.late = "stale";
++ });
++ pi.on("before_provider_headers", (event) => { event.headers.fresh = "yes"; });
++ }`);
++ const { bridge } = fakeBridge();
++ let release!: () => void;
++ bridge.modelRegistry = { wait: new Promise<void>((resolve) => { release = resolve; }) };
++ const runner = new TrustedExtensionRunner({ specs: [ext], bridge });
++ await runner.load();
++ vi.useFakeTimers();
++ const headers = { original: "yes" };
++ const pending = runner.emit("before_provider_headers", { headers });
++ await vi.advanceTimersByTimeAsync(30_000);
++ await pending;
++ release();
++ await vi.advanceTimersByTimeAsync(0);
++ expect(headers).toEqual({ original: "yes", fresh: "yes" });
++ await runner.dispose();
++ });
++
++ it("cancels extension tools and suppresses late progress and results", async () => {
++ const ext = spec("late-tool", `export default function (pi) {
++ pi.registerTool({ name: "waiting", description: "wait", parameters: { type: "object" },
++ execute: async (_id, _args, _signal, update, ctx) => {
++ await ctx.modelRegistry.wait;
++ update({ content: [{ type: "text", text: "late" }], details: {} });
++ return { content: [], details: {} };
++ }
++ });
++ }`);
++ const { bridge } = fakeBridge();
++ let release!: () => void;
++ bridge.modelRegistry = { wait: new Promise<void>((resolve) => { release = resolve; }) };
++ const runner = new TrustedExtensionRunner({ specs: [ext], bridge });
++ await runner.load();
++ const tool = runner.getAgentTools()[0];
++ if (!tool) throw new Error("Missing fixture tool");
++ const controller = new AbortController();
++ const updates = vi.fn();
++ const result = tool.execute("call", {}, controller.signal, updates);
++ const rejected = expect(result).rejects.toMatchObject({ name: "AbortError" });
++ controller.abort();
++ await rejected;
++ release();
++ await Promise.resolve();
++ expect(updates).not.toHaveBeenCalled();
++ await runner.dispose();
++ });
++
++ it("keeps a legitimate extension tool alive beyond the event budget", async () => {
++ const ext = spec("long-tool", `export default function (pi) {
++ pi.registerTool({ name: "long_tool", description: "wait", parameters: { type: "object" },
++ execute: async (_id, _args, _signal, _update, ctx) => {
++ await ctx.modelRegistry.wait;
++ return { content: [{ type: "text", text: "done" }], details: {} };
++ }
++ });
++ }`);
++ const { bridge } = fakeBridge();
++ let release!: () => void;
++ bridge.modelRegistry = { wait: new Promise<void>((resolve) => { release = resolve; }) };
++ const runner = new TrustedExtensionRunner({ specs: [ext], bridge });
++ await runner.load();
++ const tool = runner.getAgentTools()[0];
++ if (!tool) throw new Error("Missing fixture tool");
++ vi.useFakeTimers();
++ let settled = false;
++ const running = tool.execute("call", {}, undefined).then((result) => {
++ settled = true;
++ return result;
++ });
++ await vi.advanceTimersByTimeAsync(60_000);
++ expect(settled).toBe(false);
++ release();
++ await expect(running).resolves.toMatchObject({ content: [{ text: "done" }] });
++ await runner.dispose();
++ });
++
++ it("detaches published tool updates and results from extension-owned objects", async () => {
++ const ext = spec("detached-tool", `export default function (pi) {
++ pi.registerTool({ name: "detached", description: "detached", parameters: { type: "object" },
++ execute: async (_id, _args, _signal, update, ctx) => {
++ const partial = { content: [{ type: "text", text: "progress" }], details: { phase: "running" } };
++ const result = { content: [{ type: "text", text: "done" }], details: { phase: "complete" } };
++ update(partial);
++ ctx.modelRegistry.partial = partial;
++ ctx.modelRegistry.result = result;
++ return result;
++ }
++ });
++ }`);
++ const { bridge } = fakeBridge();
++ const owned: Record<string, unknown> = {};
++ bridge.modelRegistry = owned;
++ const runner = new TrustedExtensionRunner({ specs: [ext], bridge });
++ await runner.load();
++ const tool = runner.getAgentTools()[0];
++ if (!tool) throw new Error("Missing fixture tool");
++ let update: unknown;
++ const result = await tool.execute("call", {}, undefined, (value) => { update = value; });
++ const partial = owned.partial as { details: { phase: string } };
++ const ownedResult = owned.result as { details: { phase: string } };
++ partial.details.phase = "late";
++ ownedResult.details.phase = "late";
++ expect(update).toMatchObject({ details: { phase: "running" } });
++ expect(result).toMatchObject({ details: { phase: "complete" } });
++ await runner.dispose();
++ });
++
+ it("bounds startup and shutdown waits and reports the stalled event", async () => {
+ const ext = spec("stalled", `export default function (pi) {
+ pi.on("session_start", (_event, ctx) => { pi.setSessionName("starting"); return new Promise(() => {}); });
+ pi.on("session_shutdown", () => { pi.setSessionName("closing"); return new Promise(() => {}); });
+ }`);
+ const { bridge, log } = fakeBridge();
+ const runner = new TrustedExtensionRunner({ specs: [ext], bridge });
+ vi.useFakeTimers();
+ const loading = runner.load();
+ await vi.waitFor(() => expect(log.sessionName).toBe("starting"));
+ await vi.advanceTimersByTimeAsync(30_000);
+ await loading;
+ const closing = runner.dispose();
+ await vi.waitFor(() => expect(log.sessionName).toBe("closing"));
+ await vi.advanceTimersByTimeAsync(30_000);
+ await closing;
+ expect(runner.getDiagnostics()).toEqual(expect.arrayContaining([
+ expect.objectContaining({ kind: "handler_timeout", member: "session_start" }),
+ expect.objectContaining({ kind: "handler_timeout", member: "session_shutdown" }),
+ ]));
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("retires pending dispatches before shutdown and ignores their late results", async () => {
+ const ext = spec("late", `export default function (pi) {
+ pi.on("tool_call", async (_event, ctx) => {
+ pi.setSessionName("waiting");
+ await ctx.ui.confirm("wait", "release");
+ return { block: true, reason: "late" };
+ });
+ pi.on("tool_call", () => { pi.setSessionName("stale handler"); });
+ pi.on("session_shutdown", () => { pi.setSessionName("closed"); });
+ }`);
+ const { bridge, log } = fakeBridge();
+ let release!: (value: TrustedExtensionUiResponse) => void;
+ bridge.requestUi = () => new Promise((resolve) => { release = resolve; });
+ const runner = new TrustedExtensionRunner({ specs: [ext], bridge });
+ await runner.load();
+ const pending = runner.emit("tool_call", { type: "tool_call" });
+ await runner.dispose();
+ release({ kind: "confirm", value: true });
+ expect(await pending).toBeUndefined();
+ expect(log.sessionName).toBe("closed");
+ expect(runner.getDiagnostics()).toEqual([]);
+ });
+
+ it("runs shutdown once when two owners dispose concurrently", async () => {
+ const ext = spec("shutdown", `export default function (pi) {
+ pi.on("session_shutdown", async (_event, ctx) => {
+ await ctx.ui.confirm("closing", "release");
+ });
+ }`);
+ const { bridge } = fakeBridge();
+ const request = vi.fn(async () => ({ kind: "confirm" as const, value: true }));
+ bridge.requestUi = request;
+ const runner = new TrustedExtensionRunner({ specs: [ext], bridge });
+ await runner.load();
+ await Promise.all([runner.dispose(), runner.dispose()]);
+ expect(request).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not publish a factory that is still loading when disposed", async () => {
+ const ext = spec("factory", `export default async function (pi) {
+ pi.registerCommand("late", { handler: () => {} });
+ pi.setSessionName("factory entered");
+ await new Promise(() => {});
+ }`);
+ const { bridge, log } = fakeBridge();
+ const runner = new TrustedExtensionRunner({ specs: [ext], bridge });
+ const loading = runner.load();
+ await vi.waitFor(() => expect(log.sessionName).toBe("factory entered"));
+ await runner.dispose();
+ await loading;
+ expect(log.commands.flat()).toEqual([]);
+ expect(runner.getLoadReports()).toEqual([]);
+ });
+
+ it("times out one result handler, ignores its late failure, and preserves the next result", async () => {
+ const ext = spec("timeout", `export default function (pi) {
+ pi.on("tool_call", async (_event, ctx) => {
+ await ctx.ui.confirm("wait", "release");
+ throw new Error("late failure");
+ });
+ pi.on("tool_call", () => ({ block: true, reason: "second handler" }));
+ }`);
+ const { bridge } = fakeBridge();
+ let release!: (value: TrustedExtensionUiResponse) => void;
+ bridge.requestUi = () => new Promise((resolve) => { release = resolve; });
+ const runner = new TrustedExtensionRunner({ specs: [ext], bridge });
+ await runner.load();
+ vi.useFakeTimers();
+ const pending = runner.emit("tool_call", { type: "tool_call" });
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(await pending).toEqual({ block: true, reason: "second handler" });
+ release({ kind: "confirm", value: true });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(runner.getDiagnostics()).toEqual([
+ expect.objectContaining({ kind: "handler_timeout", member: "tool_call", count: 1 }),
+ ]);
+ await runner.dispose();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("reports deferred events without preventing supported handlers from loading", async () => {
+ const ext = spec("capabilities", `export default function (pi) {
+ pi.on("input", () => {});
+ pi.on("resources_discover", () => {});
+ pi.on("before_agent_start", () => ({ systemPrompt: "supported" }));
+ }`);
+ const { bridge } = fakeBridge();
+ const runner = new TrustedExtensionRunner({ specs: [ext], bridge });
+ await runner.load();
+ expect(runner.getDiagnostics().map((entry) => entry.member)).toEqual([
+ "on:input", "on:resources_discover",
+ ]);
+ expect(await runner.emit("before_agent_start", {})).toEqual({ systemPrompt: "supported" });
+ await runner.dispose();
+ });
+
+ it("skips a stalled factory and still loads a healthy extension", async () => {
+ const stalled = spec("stalled-factory", `export default async function (pi) {
+ pi.setSessionName("factory waiting");
+ await new Promise(() => {});
+ }`);
+ const healthy = spec("healthy", `export default function (pi) {
+ pi.on("before_agent_start", () => ({ systemPrompt: "healthy" }));
+ }`);
+ const { bridge, log } = fakeBridge();
+ const runner = new TrustedExtensionRunner({ specs: [stalled, healthy], bridge });
+ vi.useFakeTimers();
+ const loading = runner.load();
+ await vi.waitFor(() => expect(log.sessionName).toBe("factory waiting"));
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect((await loading).map((report) => report.state)).toEqual(["error", "loaded"]);
+ expect(await runner.emit("before_agent_start", {})).toEqual({ systemPrompt: "healthy" });
+ expect(runner.getDiagnostics()).toEqual([
+ expect.objectContaining({ kind: "factory_error", message: "handler exceeded 30000ms" }),
+ ]);
+ await runner.dispose();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
it("loads a TypeScript extension, registers its tool, and runs hooks", async () => {
const ext = spec(
"fx",
diff --cc packages/agent-runtime/src/extensions/runner.ts
index 83744e6aa,61ec33158..c624fbbd4
--- a/packages/agent-runtime/src/extensions/runner.ts
+++ b/packages/agent-runtime/src/extensions/runner.ts
@@@ -9,7 -9,7 +9,7 @@@
* handlers. Every unsupported member is inert and reports a diagnostic; it
* never throws into extension code.
*/
--import { spawn } from "node:child_process";
++import { managedExec } from "./managed-exec.js";
import type { AgentTool, AgentToolResult } from "@earendil-works/pi-agent-core";
import {
createAssistantMessageEventStream,
@@@ -42,67 -42,13 +42,14 @@@ import
type TrustedExtensionUiResponse,
} from "./types.js";
- /** Events the desktop runtime emits in v1 (spec §6). */
- export const TRUSTED_EXTENSION_EVENTS = [
- "session_start",
- "session_shutdown",
- "session_info_changed",
- "project_trust",
- "resources_discover",
- "before_agent_start",
- "context",
- "before_provider_request",
- "before_provider_headers",
- "after_provider_response",
- "agent_start",
- "agent_end",
- "agent_settled",
- "turn_start",
- "turn_end",
- "message_start",
- "message_update",
- "message_end",
- "tool_call",
- "tool_execution_start",
- "tool_execution_update",
- "tool_execution_end",
- "tool_result",
- "model_select",
- "thinking_level_select",
- "session_before_compact",
- "session_compact",
- "session_compact_failed",
- "session_before_fork",
- "input",
- ] as const;
-
- export type TrustedExtensionEventName = (typeof TRUSTED_EXTENSION_EVENTS)[number];
-
- /** Upstream events the runtime never emits in v1; handlers register silently. */
- const NOT_EMITTED_EVENTS = new Set([
- "user_bash",
- "session_before_switch",
- "session_before_tree",
- "session_tree",
- "ui_prompt_start",
- "ui_prompt_end",
- ]);
-
- /** Events whose handler result is honored, and therefore time-limited. */
- const RESULT_EVENTS = new Set<string>([
- "resources_discover",
- "before_agent_start",
- "context",
- "before_provider_request",
- "before_provider_headers",
- "message_end",
- "tool_call",
- "tool_result",
- "session_before_compact",
- "session_before_fork",
- "input",
- "project_trust",
- ]);
+ import { HandlerLifecycle } from "./handler-lifecycle.js";
++import { waitForOperation } from "./operation.js";
+ import {
+ isKnownExtensionEvent,
+ TRUSTED_EXTENSION_EVENT_CAPABILITIES,
+ type TrustedExtensionEventName,
+ } from "./event-capabilities.js";
+ export { TRUSTED_EXTENSION_EVENTS, type TrustedExtensionEventName } from "./event-capabilities.js";
/** ExtensionAPI members deferred to v2 or unsupported in v1. */
const INERT_API_MEMBERS = [
@@@ -192,7 -138,7 +139,7 @@@ export interface TrustedExtensionBridg
sessionId: string;
cwd: string;
getModel(): unknown;
-- setModel(model: unknown): Promise<boolean>;
++ setModel(model: unknown, signal?: AbortSignal): Promise<boolean>;
getThinkingLevel(): string;
setThinkingLevel(level: string): void;
isIdle(): boolean;
@@@ -205,10 -151,10 +152,11 @@@
getAllTools(): ExtensionToolInfo[];
setActiveTools(names: string[]): void;
getSessionName(): string | undefined;
-- setSessionName(name: string): void | Promise<void>;
++ setSessionName(name: string, signal?: AbortSignal): void | Promise<void>;
sendUserMessage(
content: string | unknown[],
options?: { deliverAs?: "steer" | "followUp" },
++ signal?: AbortSignal,
): void | Promise<void>;
waitForIdle(): Promise<void>;
newSession(): Promise<{ cancelled: boolean }>;
@@@ -216,6 -162,6 +164,7 @@@
requestUi(
extension: TrustedExtensionSpec,
request: TrustedExtensionUiRequest,
++ signal?: AbortSignal,
): Promise<TrustedExtensionUiResponse>;
publishCommands(commands: TrustedExtensionCommand[]): void;
publishDiagnostics(diagnostics: TrustedExtensionDiagnostic[]): void;
@@@ -377,6 -307,9 +310,10 @@@ export class TrustedExtensionRunner
private readonly reports = new Map<string, TrustedExtensionLoadReport>();
private publishScheduled = false;
private disposed = false;
+ private closing = false;
+ private disposal?: Promise<void>;
+ private readonly lifecycle = new HandlerLifecycle();
++ private readonly processes = new Set<Promise<ExtensionExecResult>>();
constructor(options: TrustedExtensionRunnerOptions) {
this.bridge = options.bridge;
@@@ -449,11 -393,25 +397,26 @@@
return this.getLoadReports();
}
- async dispose(): Promise<void> {
- if (this.disposed) return;
- await this.emit("session_shutdown", { type: "session_shutdown", reason: "quit" });
- this.disposed = true;
- this.bridge.publishCommands([]);
+ /** Retire current dispatches; subsequent turns use a fresh generation. */
+ cancelPending(): void {
+ if (!this.closing) this.lifecycle.cancel();
+ }
+
+ dispose(): Promise<void> {
+ if (this.disposal) return this.disposal;
+ this.closing = true;
+ this.lifecycle.cancel();
+ this.disposal = Promise.resolve().then(async () => {
+ try {
+ await this.dispatch("session_shutdown", { type: "session_shutdown", reason: "quit" });
+ } finally {
+ this.disposed = true;
+ this.lifecycle.cancel();
++ await Promise.allSettled([...this.processes]);
+ this.bridge.publishCommands([]);
+ }
+ });
+ return this.disposal;
}
getLoadReports(): TrustedExtensionLoadReport[] {
@@@ -505,8 -463,8 +468,17 @@@
parameters: def.parameters as AgentTool["parameters"],
executionMode: def.executionMode ?? "sequential",
...(def.prepareArguments ? { prepareArguments: def.prepareArguments } : {}),
-- execute: (toolCallId, params, signal, onUpdate) =>
-- def.execute(toolCallId, params, signal, onUpdate, this.createContext(extension)),
++ execute: (toolCallId, params, signal, onUpdate) => {
++ if (this.closing) throw new DOMException("Extension disposed", "AbortError");
++ const parent = signal ? AbortSignal.any([signal, this.lifecycle.signal]) : this.lifecycle.signal;
++ return this.lifecycle.run(async () => {
++ const operation = this.lifecycle.operationSignal;
++ const result = await def.execute(toolCallId, structuredClone(params), operation,
++ onUpdate ? (partial) => { if (!operation.aborted) onUpdate(structuredClone(partial)); } : undefined,
++ this.createContext(extension));
++ return structuredClone(result);
++ }, parent);
++ },
} as AgentTool);
}
}
@@@ -533,10 -492,10 +506,13 @@@
for (const extension of this.loaded.values()) {
const command = extension.commands.get(name);
if (!command) continue;
++ const signal = this.lifecycle.signal;
try {
-- await command.handler(args, this.createCommandContext(extension));
++ await this.lifecycle.run(() => command.handler(args, this.createCommandContext(extension)), signal);
} catch (err) {
-- this.report(extension.spec.id, "handler_error", errorMessage(err), `command:${name}`, errorStack(err));
++ if (!signal.aborted && !(err instanceof Error && err.name === "AbortError")) {
++ this.report(extension.spec.id, "handler_error", errorMessage(err), `command:${name}`, errorStack(err));
++ }
}
return true;
}
@@@ -558,18 -526,19 +543,28 @@@
for (const extension of this.loaded.values()) {
const handlers = extension.handlers.get(event);
if (!handlers?.length) continue;
-- const ctx = this.createContext(extension);
for (const handler of handlers) {
+ if (signal.aborted || this.disposed) return undefined;
try {
- const run = Promise.resolve(handler(payload, ctx));
- const result = (await (timed
- ? withTimeout(run, TRUSTED_EXTENSION_HANDLER_TIMEOUT_MS)
- : run)) as R | undefined;
++ // Result/mutation events operate on detached data. Only a timely
++ // headers mutation is committed; late handlers retain their own copy.
++ const isolate = TRUSTED_EXTENSION_EVENT_CAPABILITIES[event] === "result" ||
++ TRUSTED_EXTENSION_EVENT_CAPABILITIES[event] === "mutation";
++ const input = isolate ? structuredClone(payload) : payload;
+ const result = await this.lifecycle.run(
- () => handler(payload, ctx), signal, TRUSTED_EXTENSION_HANDLER_TIMEOUT_MS,
++ () => handler(input, this.createContext(extension)), signal, TRUSTED_EXTENSION_HANDLER_TIMEOUT_MS,
+ ) as R | undefined;
+ if (signal.aborted || this.disposed) return undefined;
++ if (event === "before_provider_headers" && payload.headers && typeof payload.headers === "object") {
++ for (const key of Object.keys(payload.headers)) Reflect.deleteProperty(payload.headers, key);
++ Object.assign(payload.headers, structuredClone(input.headers));
++ }
if (result !== undefined && result !== null) {
-- acc = fold ? fold(acc, result) : result;
++ const detached = isolate ? structuredClone(result) : result;
++ acc = fold ? fold(acc, detached) : detached;
}
} catch (err) {
+ if (signal.aborted || this.disposed) return undefined;
const kind: TrustedExtensionDiagnosticKind = /exceeded \d+ms/.test(errorMessage(err))
? "handler_timeout"
: "handler_error";
@@@ -633,49 -602,49 +628,38 @@@
}
private exec(
++ extension: LoadedExtension,
command: string,
args: string[],
options?: ExtensionExecOptions,
): Promise<ExtensionExecResult> {
-- return new Promise((resolve, reject) => {
-- const child = spawn(command, args, {
-- cwd: options?.cwd ?? this.bridge.cwd,
-- env: options?.env ? { ...process.env, ...options.env } : process.env,
-- stdio: ["ignore", "pipe", "pipe"],
-- });
-- const maxBuffer = options?.maxBuffer ?? 10 * 1024 * 1024;
-- let stdout = "";
-- let stderr = "";
-- let killed = false;
-- const kill = () => {
-- killed = true;
-- child.kill("SIGTERM");
-- };
-- const timer = options?.timeout ? setTimeout(kill, options.timeout) : undefined;
-- options?.signal?.addEventListener("abort", kill, { once: true });
-- child.stdout?.on("data", (chunk: Buffer) => {
-- if (stdout.length < maxBuffer) stdout += chunk.toString("utf8");
-- });
-- child.stderr?.on("data", (chunk: Buffer) => {
-- if (stderr.length < maxBuffer) stderr += chunk.toString("utf8");
-- });
-- child.on("error", (err) => {
-- if (timer) clearTimeout(timer);
-- reject(err);
-- });
-- child.on("close", (code) => {
-- if (timer) clearTimeout(timer);
-- resolve({ stdout, stderr, code: code ?? (killed ? 143 : 0), killed });
-- });
++ if (this.disposed) return Promise.reject(new DOMException("Extension disposed", "AbortError"));
++ const pending = managedExec(command, args, this.bridge.cwd, this.lifecycle.operationSignal, options);
++ this.processes.add(pending);
++ void pending.then(() => this.processes.delete(pending), (error: unknown) => {
++ this.processes.delete(pending);
++ this.report(extension.spec.id, "handler_error", errorMessage(error), "exec");
});
++ return pending;
}
private createUi(extension: LoadedExtension): Record<string, unknown> {
-- const request = (req: TrustedExtensionUiRequest) =>
-- this.bridge.requestUi(extension.spec, req);
++ const signal = this.lifecycle.operationSignal;
++ const request = (req: TrustedExtensionUiRequest) => {
++ signal.throwIfAborted();
++ return waitForOperation(this.bridge.requestUi(extension.spec, req, signal), signal).then((response) => {
++ if ("cancelled" in response && response.cancelled) {
++ this.lifecycle.cancelOperation();
++ signal.throwIfAborted();
++ }
++ return response;
++ });
++ };
const ui: Record<string, unknown> = {
notify: (message: string, level: "info" | "warning" | "error" = "info") => {
-- void request({ kind: "notify", message: String(message), level });
++ void request({ kind: "notify", message: String(message), level }).catch((error: unknown) => {
++ if (!signal.aborted) this.report(extension.spec.id, "handler_error", errorMessage(error), "ui.notify");
++ });
},
confirm: async (title: string, message: string) => {
const res = await request({ kind: "confirm", title: String(title), message: String(message ?? "") });
@@@ -698,10 -667,10 +682,14 @@@
return res.kind === "input" ? res.value : undefined;
},
setStatus: (key: string, text: string | undefined) => {
-- void request({ kind: "setStatus", key: String(key), text: text ?? undefined });
++ void request({ kind: "setStatus", key: String(key), text: text ?? undefined }).catch((error: unknown) => {
++ if (!signal.aborted) this.report(extension.spec.id, "handler_error", errorMessage(error), "ui.setStatus");
++ });
},
setWorkingMessage: (text?: string) => {
-- void request({ kind: "setWorkingMessage", text: text ?? undefined });
++ void request({ kind: "setWorkingMessage", text: text ?? undefined }).catch((error: unknown) => {
++ if (!signal.aborted) this.report(extension.spec.id, "handler_error", errorMessage(error), "ui.setWorkingMessage");
++ });
},
};
for (const member of INERT_UI_MEMBERS) {
@@@ -711,8 -680,8 +699,9 @@@
}
private createContext(extension: LoadedExtension): Record<string, unknown> {
-- const bridge = this.bridge;
++ const bridge = this.operationBridge(this.lifecycle.operationSignal);
return {
++ signal: this.lifecycle.operationSignal,
ui: this.createUi(extension),
hasUI: true,
cwd: bridge.cwd,
@@@ -739,7 -708,7 +728,7 @@@
}
private createCommandContext(extension: LoadedExtension): Record<string, unknown> {
-- const bridge = this.bridge;
++ const bridge = this.operationBridge(this.lifecycle.operationSignal);
return {
...this.createContext(extension),
getSystemPromptOptions: () => ({}),
@@@ -806,7 -775,7 +795,7 @@@
}
private createApi(extension: LoadedExtension): Record<string, unknown> {
-- const bridge = this.bridge;
++ const bridge = this.operationBridge();
const api: Record<string, unknown> = {
on: (event: string, handler: Handler) => {
if (typeof handler !== "function") return;
@@@ -921,7 -890,7 +910,7 @@@
},
getFlag: (name: string) => extension.flags.get(String(name))?.default,
exec: (command: string, args: string[], options?: ExtensionExecOptions) =>
-- this.exec(command, Array.isArray(args) ? args.map(String) : [], options),
++ this.exec(extension, command, Array.isArray(args) ? args.map(String) : [], options),
getActiveTools: () => bridge.getActiveTools(),
getAllTools: () => bridge.getAllTools(),
setActiveTools: (names: string[]) => bridge.setActiveTools(Array.isArray(names) ? names.map(String) : []),
@@@ -936,7 -905,7 +925,10 @@@
getThinkingLevel: () => bridge.getThinkingLevel(),
setThinkingLevel: (level: string) => bridge.setThinkingLevel(String(level)),
setSessionName: (name: string) => {
-- void bridge.setSessionName(String(name));
++ const signal = this.lifecycle.operationSignal;
++ void Promise.resolve(bridge.setSessionName(String(name))).catch((error: unknown) => {
++ if (!signal.aborted) this.report(extension.spec.id, "handler_error", errorMessage(error), "setSessionName");
++ });
},
getSessionName: () => bridge.getSessionName(),
sendUserMessage: (content: string | unknown[], options?: { deliverAs?: "steer" | "followUp" }) =>
@@@ -949,6 -918,6 +941,42 @@@
for (const member of INERT_API_MEMBERS) {
api[member] = this.inert(extension, member);
}
-- return api;
++ return new Proxy(api, {
++ get: (target, key) => {
++ const member: unknown = Reflect.get(target, key);
++ if (typeof member !== "function") return member;
++ return (...args: unknown[]) => {
++ this.lifecycle.operationSignal.throwIfAborted();
++ if (this.disposed) throw new DOMException("Extension disposed", "AbortError");
++ return Reflect.apply(member, target, args);
++ };
++ },
++ });
++ }
++
++ /** AsyncLocalStorage preserves the original invocation even in late callbacks. */
++ private operationBridge(boundSignal?: AbortSignal): TrustedExtensionBridge {
++ return new Proxy(this.bridge, {
++ get: (target, key, receiver) => {
++ const value: unknown = Reflect.get(target, key, receiver);
++ if (typeof value !== "function") return value;
++ return (...args: unknown[]) => {
++ const signal = boundSignal ?? this.lifecycle.operationSignal;
++ signal.throwIfAborted();
++ if (this.disposed) throw new DOMException("Extension disposed", "AbortError");
++ const callArgs = key === "sendUserMessage" ? [args[0], args[1], signal]
++ : key === "setModel" || key === "setSessionName" ? [args[0], signal] : args;
++ const result: unknown = Reflect.apply(value, target, callArgs);
++ if (!(result instanceof Promise)) return result;
++ const waiting = waitForOperation(result, signal);
++ // Some upstream SDK setters are fire-and-forget. Observe rejection
++ // without changing the promise seen by an awaiting extension.
++ void waiting.catch(() => {
++ if (!signal.aborted) console.error(`[extensions] SDK operation failed: ${String(key)}`);
++ });
++ return waiting;
++ };
++ },
++ });
}
}
diff --cc packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts
index 000000000,f840b6333..4c214a899
mode 000000,100644..100644
--- a/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts
+++ b/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts
@@@ -1,0 -1,97 +1,128 @@@
+ import { createServer } from "node:http";
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+ import { tmpdir } from "node:os";
+ import { join } from "node:path";
+ import { afterEach, describe, expect, it } from "vitest";
+ import type { AgentEventEnvelope } from "@pi-desktop/shared";
+ import { DesktopAgentRuntime } from "../runtime.js";
+ import { clearTrustedExtensionCache } from "./runner.js";
+
+ afterEach(() => clearTrustedExtensionCache());
+
+ function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => { resolve = done; });
+ return { promise, resolve };
+ }
+
+ describe("Desktop extension lifecycle", () => {
++ it("does not apply a session rename locally after its invocation is cancelled", async () => {
++ const rename = deferred<Record<string, never>>();
++ const runtime = new DesktopAgentRuntime({
++ host: {
++ call: async (method: string) => method === "session.rename" ? rename.promise : {},
++ onNotification: () => () => {},
++ } as never,
++ sessionId: "hooks-test",
++ mode: "agent",
++ thinkingLevel: "off",
++ provider: {
++ id: "fixture", name: "Fixture", apiKey: "", authKind: "none",
++ baseUrl: "http://127.0.0.1:1/v1", modelId: "fixture",
++ supportsReasoning: false, supportedThinkingLevels: ["off"],
++ },
++ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
++ onEvent: () => {},
++ });
++ const bridge = (runtime as unknown as {
++ createExtensionBridge(): { setSessionName(name: string, signal?: AbortSignal): Promise<void> };
++ extensionSessionName?: string;
++ }).createExtensionBridge();
++ const operation = new AbortController();
++ const pending = bridge.setSessionName("stale", operation.signal);
++ operation.abort();
++ rename.resolve({});
++ await pending;
++ expect((runtime as unknown as { extensionSessionName?: string }).extensionSessionName).toBeUndefined();
++ await runtime.dispose();
++ });
++
+ it.each([
+ { action: "abort", event: "before_agent_start" },
+ { action: "dispose", event: "before_agent_start" },
+ { action: "abort", event: "before_provider_headers" },
+ { action: "dispose", event: "before_provider_headers" },
+ ] as const)("$action during $event prevents a provider request", async ({ action, event }) => {
+ const root = mkdtempSync(join(tmpdir(), "pi-hooks-lifecycle-"));
+ const entered = deferred<void>();
+ const answer = deferred<{ kind: "confirm"; value: boolean }>();
+ let requests = 0;
+ let wait = true;
+ const server = createServer((_request, response) => {
+ requests += 1;
+ response.writeHead(200, { "content-type": "text/event-stream" });
+ response.end([
+ `data: ${JSON.stringify({ id: "test", choices: [{ index: 0, delta: { role: "assistant", content: "Recovered" }, finish_reason: null }] })}`,
+ `data: ${JSON.stringify({ id: "test", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })}`,
+ "data: [DONE]",
+ ].join("\n\n") + "\n\n");
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("Missing fixture address");
+ const entry = join(root, "extension.ts");
+ writeFileSync(entry, `export default function (pi) {
+ pi.on("${event}", async (_event, ctx) => {
+ await ctx.ui.confirm("Check", "Continue?");
+ return { systemPrompt: "Late prompt" };
+ });
+ }`);
+ const events: AgentEventEnvelope[] = [];
+ const runtime = new DesktopAgentRuntime({
+ host: {
+ call: async (method: string) => {
+ if (method === "extensions.ui.request") {
+ entered.resolve();
+ return wait ? answer.promise : { kind: "confirm", value: true };
+ }
+ return {};
+ },
+ onNotification: () => () => {},
+ } as never,
+ sessionId: "hooks-test",
+ projectPath: root,
+ mode: "agent",
+ thinkingLevel: "off",
+ provider: {
+ id: "fixture", name: "Fixture", apiKey: "", authKind: "none",
+ baseUrl: `http://127.0.0.1:${address.port}/v1`, modelId: "fixture",
+ supportsReasoning: false, supportedThinkingLevels: ["off"],
+ },
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ trustedExtensions: [{ id: entry, entry, label: "Lifecycle", root, source: "plugin" }],
+ onEvent: (event) => events.push(event),
+ });
+ try {
+ await runtime.loadTrustedExtensions();
+ const prompting = runtime.prompt("First");
+ const rejected = expect(prompting).rejects.toMatchObject({ name: "AbortError" });
+ await entered.promise;
+ await runtime[action]();
+ await rejected;
+ expect(requests).toBe(0);
+ answer.resolve({ kind: "confirm", value: true });
+ if (action === "abort") {
+ wait = false;
+ await runtime.prompt("Try again");
+ expect(requests).toBe(1);
+ expect(JSON.stringify(events)).toContain("Recovered");
+ }
+ } finally {
+ answer.resolve({ kind: "confirm", value: true });
+ await runtime.dispose();
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+ });
diff --cc packages/agent-runtime/src/extensions/ui-request.test.ts
index 000000000,000000000..6434db2d4
new file mode 100644
--- /dev/null
+++ b/packages/agent-runtime/src/extensions/ui-request.test.ts
@@@ -1,0 -1,0 +1,20 @@@
++import { expect, it } from "vitest";
++import type { TrustedExtensionUiRequestEnvelope, TrustedExtensionUiResponse } from "@pi-desktop/shared";
++import { requestExtensionUi } from "./ui-request.js";
++
++it("retires the exact admitted request on abort and removes its listener after settlement", async () => {
++ const sent: TrustedExtensionUiRequestEnvelope[] = [];
++ let release!: (response: TrustedExtensionUiResponse) => void;
++ const owner = new AbortController();
++ const pending = requestExtensionUi(async (envelope) => {
++ sent.push(envelope);
++ if (envelope.request.kind === "cancel") return { kind: "cancel" };
++ return new Promise((resolve) => { release = resolve; });
++ }, { sessionId: "s", extensionId: "e", extensionLabel: "E", request: { kind: "confirm", title: "?", message: "" } }, owner.signal);
++ owner.abort();
++ expect(sent[1]).toMatchObject({ sessionId: "s", extensionId: "e",
++ request: { kind: "cancel", requestId: sent[0]?.requestId } });
++ release({ kind: "confirm", value: false });
++ expect(await pending).toEqual({ kind: "confirm", value: false });
++ expect(sent).toHaveLength(2);
++});
diff --cc packages/agent-runtime/src/extensions/ui-request.ts
index 000000000,000000000..f1eec648c
new file mode 100644
--- /dev/null
+++ b/packages/agent-runtime/src/extensions/ui-request.ts
@@@ -1,0 -1,0 +1,22 @@@
++import { randomUUID } from "node:crypto";
++import type { TrustedExtensionUiRequestEnvelope, TrustedExtensionUiResponse } from "@pi-desktop/shared";
++
++/** Request identity scopes cancellation to one invocation, including queued prompts. */
++export async function requestExtensionUi(
++ send: (envelope: TrustedExtensionUiRequestEnvelope) => Promise<TrustedExtensionUiResponse>,
++ envelope: TrustedExtensionUiRequestEnvelope,
++ signal?: AbortSignal,
++): Promise<TrustedExtensionUiResponse> {
++ signal?.throwIfAborted();
++ const requestId = randomUUID();
++ const cancel = () => {
++ void send({ ...envelope, request: { kind: "cancel", requestId } }).catch(() => {
++ console.error("[extensions] failed to retire an extension UI request");
++ });
++ };
++ const response = send({ ...envelope, requestId });
++ signal?.addEventListener("abort", cancel, { once: true });
++ if (signal?.aborted) cancel();
++ try { return await response; }
++ finally { signal?.removeEventListener("abort", cancel); }
++}
diff --cc packages/agent-runtime/src/runtime.ts
index d9a19eb80,844ba7c28..3e17e3c53
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@@ -1,5 -1,3 +1,6 @@@
+import { restoreHostedSearchReplay } from "./hosted-search-replay.js";
++import { requestExtensionUi } from "./extensions/ui-request.js";
+import { readLocalRequestErrorDetails } from "./local-request-errors.js";
import { imageGenerationDescription, imageGenerationParameters } from "./image-generation/tool.js";
import { scheduledToolParameters, scheduledToolDescriptions } from "./scheduled-tools.js";
import { randomUUID } from "node:crypto";
@@@ -52,7 -50,7 +53,6 @@@ import
type TrustedExtensionCommand,
type TrustedExtensionDiagnostic,
type TrustedExtensionSpec,
-- type TrustedExtensionUiRequest,
type TrustedExtensionUiResponse,
} from "@pi-desktop/shared";
import {
@@@ -2421,7 -2402,7 +2421,7 @@@ Delegation rules
return true;
}
-- private async setExtensionModel(model: unknown): Promise<boolean> {
++ private async setExtensionModel(model: unknown, signal?: AbortSignal): Promise<boolean> {
if (!this.extensionRunner || !this.isIdle()) return false;
const agent = this.extensionRunner.findAgentModel(model);
if (!agent) return false;
@@@ -2438,7 -2419,7 +2438,7 @@@
modelId: candidate.id,
thinkingLevel: this.thinkingLevel,
});
-- if (result?.ok === false) return false;
++ if (signal?.aborted || this.disposed || result?.ok === false) return false;
this.applyExtensionAgent(agent, candidate);
return true;
} catch {
@@@ -2480,7 -2461,7 +2480,7 @@@
sessionId: this.sessionId,
cwd: this.projectPath ?? process.cwd(),
getModel: () => runtime.model,
-- setModel: (model) => runtime.setExtensionModel(model),
++ setModel: (model, signal) => runtime.setExtensionModel(model, signal),
modelRegistry: runtime.extensionModelRegistry(),
getThinkingLevel: () => agentThinkingLevel(runtime.thinkingLevel),
setThinkingLevel: (level) => {
@@@ -2518,18 -2499,18 +2518,19 @@@
if (wanted.has(name)) runtime.activeDeferredToolNames.add(name);
else runtime.activeDeferredToolNames.delete(name);
}
- runtime.agent.state.tools = runtime.activeTools();
+ runtime.setAgentTools(runtime.activeTools());
},
getSessionName: () => runtime.extensionSessionName,
-- setSessionName: async (name) => {
-- runtime.extensionSessionName = name;
++ setSessionName: async (name, signal) => {
await runtime.host.call("session.rename", { id: runtime.sessionId, title: name });
++ if (signal?.aborted || runtime.disposed) return;
++ runtime.extensionSessionName = name;
void runtime.extensionRunner?.emit("session_info_changed", {
type: "session_info_changed",
name,
});
},
-- sendUserMessage: async (content, options) => {
++ sendUserMessage: async (content, options, signal) => {
const text = Array.isArray(content)
? content
.map((part) => (isRecord(part) && typeof part.text === "string" ? part.text : ""))
@@@ -2543,7 -2524,7 +2544,7 @@@
idempotencyKey: randomUUID(),
content: text,
});
-- if (options?.deliverAs === "steer" && pushed?.id) {
++ if (!signal?.aborted && !runtime.disposed && options?.deliverAs === "steer" && pushed?.id) {
await runtime.host
.call("session.queuePrioritize", { sessionId: runtime.sessionId, id: pushed.id })
.catch(() => undefined);
@@@ -2572,18 -2553,18 +2573,13 @@@
return { cancelled: true };
}
},
-- requestUi: (extension, request) =>
-- runtime.host.call<TrustedExtensionUiResponse>("extensions.ui.request", {
++ requestUi: (extension, request, signal) => requestExtensionUi(
++ (envelope) => runtime.host.call<TrustedExtensionUiResponse>("extensions.ui.request", envelope), {
sessionId: runtime.sessionId,
extensionId: extension.id,
extensionLabel: extension.label,
request,
-- } satisfies {
-- sessionId: string;
-- extensionId: string;
-- extensionLabel: string;
-- request: TrustedExtensionUiRequest;
-- }),
++ }, signal),
publishCommands: (commands: TrustedExtensionCommand[]) => {
void runtime.host
.call("extensions.commands.publish", { sessionId: runtime.sessionId, commands })
diff --cc packages/shared/src/trusted-extensions.ts
index c639124af,c639124af..0064e3d4b
--- a/packages/shared/src/trusted-extensions.ts
+++ b/packages/shared/src/trusted-extensions.ts
@@@ -61,6 -61,6 +61,7 @@@ export type TrustedExtensionLoadReport
/** Interactive and status calls the sidecar sends to the desktop (spec §9). */
export type TrustedExtensionUiRequest =
++ | { kind: "cancel"; requestId: string }
| { kind: "notify"; message: string; level: "info" | "warning" | "error" }
| { kind: "confirm"; title: string; message: string }
| { kind: "select"; title: string; options: string[] }
@@@ -69,15 -69,15 +70,17 @@@
| { kind: "setWorkingMessage"; text: string | undefined };
export type TrustedExtensionUiResponse =
++ | { kind: "cancel" }
| { kind: "notify" }
-- | { kind: "confirm"; value: boolean }
-- | { kind: "select"; value: string | undefined }
-- | { kind: "input"; value: string | undefined }
++ | { kind: "confirm"; value: boolean; cancelled?: boolean }
++ | { kind: "select"; value: string | undefined; cancelled?: boolean }
++ | { kind: "input"; value: string | undefined; cancelled?: boolean }
| { kind: "setStatus" }
| { kind: "setWorkingMessage" };
/** Envelope for `extensions.ui.request` (sidecar → main). */
export type TrustedExtensionUiRequestEnvelope = {
++ requestId?: string;
sessionId: string;
extensionId: string;
extensionLabel: string;
@@@ -86,6 -86,6 +89,8 @@@
/** Modal prompt shown to the user (main → renderer). */
export type TrustedExtensionUiPrompt = {
++ /** Main retires this exact prompt after cancellation or timeout. */
++ cancelled?: boolean;
promptId: string;
sessionId: string;
extensionId: string;
diff --cc scripts/e2e-trusted-extensions.mjs
index 4e80db6cc,4e80db6cc..7100238e6
--- a/scripts/e2e-trusted-extensions.mjs
+++ b/scripts/e2e-trusted-extensions.mjs
@@@ -244,6 -244,6 +244,7 @@@ async function main()
rmSync(requestLog, { force: true });
const stubPort = await freePort();
const mcpPort = await freePort();
++ const cdpPort = await freePort();
if (stubPort === mcpPort) throw new Error("allocated duplicate E2E ports");
await runCommand(
@@@ -273,7 -273,7 +274,7 @@@
const electron = spawnChild(
"trusted-extension-electron",
electronBin,
-- ["."],
++ [`--user-data-dir=${join(runRoot, "profile")}`, `--remote-debugging-port=${cdpPort}`, "."],
{
cwd: join(root, "apps", "desktop"),
env: isolatedEnv({
@@@ -305,7 -305,7 +306,7 @@@
process.execPath,
[join(harness, "drive.mjs")],
{
-- env: isolatedEnv({ E2E_ROOT: runRoot, E2E_PROJECT: resolve(project) }),
++ env: isolatedEnv({ E2E_ROOT: runRoot, E2E_PROJECT: resolve(project), E2E_CDP_PORT: String(cdpPort) }),
timeoutMs,
forwardStdout: true,
forwardStderr: true,