Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(agent-runtime): bound trusted extension lifecycle waits
Jack7e1e3dbf6a7e
diff --git a/docs/project/unreleased.md b/docs/project/unreleased.mdindex bc12e7a45..ef6cbdb5b 100644--- a/docs/project/unreleased.md+++ b/docs/project/unreleased.md@@ -1,5 +1,10 @@# Unreleased changes+- 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 orkeyboard-selected levels, follows dragging immediately, and respectsreduced-motion settings. Rapid clicks redirect the animation; failed savesdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 8802f17a2..9af2c591e 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -7979,7 +7979,7 @@ identify the platform validation still needed.| Post-MVP | E2E-022A, E2E-022B, E2E-022C, E2E-024I, E2E-024J, E2E-024K, E2E-024L, E2E-024M (plugin roadmap R2/R3/R6) || Post-baseline local automation | E2E-220 || Post-MVP remote control | E2E-221, E2E-222, E2E-223, E2E-224, E2E-225, E2E-226, E2E-227, E2E-228, E2E-229, E2E-230, E2E-231, E2E-232 |-| Trusted extensions (R7 v1) | E2E-DIALOG-long-text-boundaries, E2E-241, E2E-242, E2E-TRUSTED-EXTENSION-custom-agent-stream-and-binding, E2E-243, E2E-244, E2E-245, E2E-PLUGIN-imported-pi-package-skills, E2E-PLUGIN-import-extension-installs-dependencies, E2E-PLUGIN-import-extension-reports-missing-dependency, E2E-PLUGIN-declared-provider-appears-in-the-native-provider-list |+| Trusted extensions (R7 v1) | E2E-DIALOG-long-text-boundaries, E2E-241, E2E-242, E2E-HOOKS-cancel-and-dispose, E2E-TRUSTED-EXTENSION-custom-agent-stream-and-binding, E2E-243, E2E-244, E2E-245, E2E-PLUGIN-imported-pi-package-skills, E2E-PLUGIN-import-extension-installs-dependencies, E2E-PLUGIN-import-extension-reports-missing-dependency, E2E-PLUGIN-declared-provider-appears-in-the-native-provider-list || Trusted extensions (R7 v1 npm recovery) | E2E-PLUGIN-import-extension-recovers-missing-npm || Post-MVP regression coverage (plugin tool dispatch) | E2E-PLUGIN-slow-tool-is-not-cut-off-by-host-dispatch || M6+ (Project delete) | E2E-PROJECT-delete-removes-project-and-owned-sessions |@@ -14226,9 +14226,29 @@ the latest destination. These assertions measure work counts, not device FPS.focused component-render validation; no live IDA process required.+#### E2E-CHAT-parenthesized-url: Complete URLs in user messages- **Steps**: Send `https://en.wikipedia.org/wiki/React_(software)` in a user message and click its link. Repeat with the URL wrapped in prose parentheses, followed by a sentence-ending period, and followed immediately by another link or file reference.- **Expected**: The complete URL, including `(software)`, opens the React software article. The outer prose closing parenthesis and sentence-ending punctuation after the URL parenthesis are not part of the link. Adjacent references remain independently clickable. Nested parentheses, query/fragment parentheses and percent-encoded parentheses remain intact.- **Coverage**: `chat-links.test.mjs`; native desktop click-through with the normal browser destination.- **Specs linked**: `04-ux/08-component-spec.md` §8.3.++### E2E-HOOKS-cancel-and-dispose++- **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.diff --git a/docs/spec/07-plugins/16-trusted-extensions.md b/docs/spec/07-plugins/16-trusted-extensions.mdindex feba79e98..7f8139a48 100644--- a/docs/spec/07-plugins/16-trusted-extensions.md+++ b/docs/spec/07-plugins/16-trusted-extensions.md@@ -303,9 +303,9 @@ are honored where the event type defines a result.| `session_info_changed` | Session rename through `setSessionName` | No || `project_trust` | v1 note: not emitted; enablement per project is the trust decision | No || `resources_discover` | v1 note: not emitted; skills and prompt discovery stay in Electron main | n/a |-| `before_agent_start` | Before the first provider request of a turn | Yes, system prompt and message edits |+| `before_agent_start` | Before the first provider request of a turn | Yes, system prompt replacement only || `context` | `prepareNextTurn` | Yes, replacement message list |-| `before_provider_request`, `before_provider_headers`, `after_provider_response` | Provider call wrapper | Yes for request and headers |+| `before_provider_request`, `before_provider_headers`, `after_provider_response` | Provider call wrapper | Request return value; headers mutate the payload in place || `agent_start`, `agent_end`, `agent_settled` | Agent loop boundaries | No || `turn_start`, `turn_end` | Turn boundaries | No || `message_start`, `message_update`, `message_end` | Agent message events | v1 note: no, pi-agent-core offers no post-hoc replacement |@@ -318,9 +318,36 @@ are honored where the event type defines a result.| `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.+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. Toolsdiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex cd2031143..90b63fd86 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -6530,3 +6530,17 @@ that was sitting at the bottom — including after the turn had finished.new is persisted and no permission or API surface changes; the existing`plugin.stdio` audit stream is otherwise unchanged.- See `07-plugins/05-plugin-lifecycle.md` §3.1.++## 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 --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex b736bd847..4c8d2699b 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -5265,7 +5265,7 @@ eleven-tool-round desktop paths are verified by| 后MVP | E2E-022A、E2E-022B、E2E-022C、E2E-024I、E2E-024J、E2E-024K、E2E-024L、E2E-024M(插件路线图 R2/R3/R6) || 基线后本地自动化 | E2E-220 || MVP 后远程控制 | E2E-221、E2E-222、E2E-223、E2E-224、E2E-225、E2E-226、E2E-227、E2E-228、E2E-229、E2E-230、E2E-231、E2E-232 |-| 受信任扩展(R7 v1) | E2E-DIALOG-long-text-boundaries、E2E-241、E2E-242、E2E-243、E2E-244、E2E-245、E2E-PLUGIN-imported-pi-package-skills、E2E-PLUGIN-import-extension-installs-dependencies、E2E-PLUGIN-import-extension-reports-missing-dependency、E2E-PLUGIN-declared-provider-appears-in-the-native-provider-list |+| 受信任扩展(R7 v1) | E2E-DIALOG-long-text-boundaries、E2E-241、E2E-242、E2E-HOOKS-cancel-and-dispose、E2E-243、E2E-244、E2E-245、E2E-PLUGIN-imported-pi-package-skills、E2E-PLUGIN-import-extension-installs-dependencies、E2E-PLUGIN-import-extension-reports-missing-dependency、E2E-PLUGIN-declared-provider-appears-in-the-native-provider-list || 受信任扩展(R7 v1 npm 恢复) | E2E-PLUGIN-import-extension-recovers-missing-npm || Post-MVP 回归覆盖(插件工具调度) | E2E-PLUGIN-slow-tool-is-not-cut-off-by-host-dispatch || M6+(删除项目) | E2E-PROJECT-delete-removes-project-and-owned-sessions |@@ -8398,9 +8398,24 @@ the latest destination. These assertions measure work counts, not device FPS.- **状态:** 运行时层已自动化;无 UI 驱动读取插件页的错误文本。+#### E2E-CHAT-parenthesized-url:用户消息中的完整网址- **步骤**:在用户消息中发送 `https://en.wikipedia.org/wiki/React_(software)` 并点击链接,再验证正文用圆括号包裹该网址、网址后跟句号及紧接另一链接或文件引用的情况。- **预期**:打开包含 `(software)` 的完整网址,进入 React 软件词条;正文外层的右括号和紧跟 URL 右括号的句末标点不属于链接,相邻引用仍能独立点击。嵌套圆括号、查询和片段内的圆括号、百分号编码的圆括号均保持完整。- **覆盖**:`chat-links.test.mjs`;桌面端通过正常浏览器目标实际点击验证。- **链接规格**:`04-ux/08-component-spec.md` §8.3。++### E2E-HOOKS-cancel-and-dispose++- **前置条件:** 隔离 Desktop 配置、本地确定性模型,以及含等待型请求前处理器的可信插件。+- **步骤:** 发送消息,在处理器等待时停止,释放旧处理器后再次发送。另测等待时销毁+ Runtime,并加载启动/关闭挂起以及注册未接通事件的夹具。+- **预期:** 被停止或销毁的请求不调用模型,后续消息正常完成。迟到结果不能重启工作。+ 关闭只执行一次,各处理器等待有界,未接通事件产生诊断但不禁用正常处理器。+- **规范:** 07-plugins/16 §6。+- **验收:** 取消及时生效,扩展生命周期等待有界。+- **里程碑:** Hooks P0。+- **状态:** Runner 与真实 Runtime/本地 HTTP 集成通过+ `extensions/runner.test.ts`、`extensions/runtime-lifecycle.test.ts` 自动验证。+ 现有可信扩展 E2E 覆盖 Electron 接线;本停止/销毁场景尚未由渲染层驱动。diff --git a/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md b/docs/zh-CN/spec/07-plugins/16-trusted-extensions.mdindex 387262a64..113cf8097 100644--- a/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md+++ b/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md@@ -180,9 +180,9 @@ main、渲染层或插件宿主进程中。| `session_info_changed` | 经 `setSessionName` 的会话改名 | 否 || `project_trust` | v1 说明:不触发;按项目启用即信任决定 | 否 || `resources_discover` | v1 说明:不触发;skills 与提示发现留在 Electron main | 不适用 |-| `before_agent_start` | 回合内首个 provider 请求之前 | 是,系统提示与消息编辑 |+| `before_agent_start` | 回合内首个 provider 请求之前 | 是,仅替换系统提示词 || `context` | `prepareNextTurn` | 是,替换消息列表 |-| `before_provider_request`、`before_provider_headers`、`after_provider_response` | provider 调用包装 | 请求与头部为是 |+| `before_provider_request`、`before_provider_headers`、`after_provider_response` | provider 调用包装 | 请求采纳返回值;头部原地修改 payload || `agent_start`、`agent_end`、`agent_settled` | Agent 循环边界 | 否 || `turn_start`、`turn_end` | 回合边界 | 否 || `message_start`、`message_update`、`message_end` | Agent 消息事件 | v1 说明:否,pi-agent-core 不提供事后替换 |@@ -195,8 +195,25 @@ 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 秒限制,+UI broker 自身的提示超时不会延长该预算。## 7. 工具diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex 63cffb59f..1e9f84665 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -4629,3 +4629,12 @@ that amendment are retired by ADR 0268; the upstream work-panel lifecycle stays.- 插件 stdout/stderr 不复制进加载错误、崩溃审计记录或崩溃日志负载,因为其中可能包含工作区数据或敏感信息。不新增任何持久化,权限与 API 面不变;既有的 `plugin.stdio` 审计流保持不变。- 见 `07-plugins/05-plugin-lifecycle.md` §3.1。++## 2026-09-21 — 限制 Desktop 可信扩展生命周期等待++- 现有 30 秒处理器预算扩展到通知、启动和关闭事件;模块加载、工厂初始化分别使用+ 同一预算。此前无界的等待变为有界,事件内等待 UI 回答也受此限制。+- 中止使当前等待失效;销毁拒绝新派发且只执行一次关闭。迟到完成不能向旧派发提供+ 结果。既有失败继续、结果归并、插件归属和权限不变,不强制终止进程内代码。+- 未接通事件仍可注册,并在现有诊断中显示。参见+ `07-plugins/16-trusted-extensions.md` §6 与 `E2E-HOOKS-cancel-and-dispose`。diff --git a/packages/agent-runtime/src/extensions/event-capabilities.ts b/packages/agent-runtime/src/extensions/event-capabilities.tsnew file mode 100644index 000000000..3df7bc45f--- /dev/null+++ b/packages/agent-runtime/src/extensions/event-capabilities.ts@@ -0,0 +1,80 @@+/** Recognized Desktop events. Deferred names remain accepted for compatibility. */+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];+++/** Result means the Desktop caller consumes the returned value; mutation edits the payload. */+export const TRUSTED_EXTENSION_EVENT_CAPABILITIES = {+ session_start: "notification",+ session_shutdown: "notification",+ session_info_changed: "notification",+ project_trust: "deferred",+ resources_discover: "deferred",+ before_agent_start: "result",+ context: "result",+ before_provider_request: "result",+ before_provider_headers: "mutation",+ after_provider_response: "notification",+ agent_start: "notification",+ agent_end: "notification",+ agent_settled: "notification",+ turn_start: "notification",+ turn_end: "notification",+ message_start: "notification",+ message_update: "notification",+ message_end: "notification",+ tool_call: "result",+ tool_execution_start: "notification",+ tool_execution_update: "notification",+ tool_execution_end: "notification",+ tool_result: "result",+ model_select: "deferred",+ thinking_level_select: "deferred",+ session_before_compact: "result",+ session_compact: "notification",+ session_compact_failed: "notification",+ session_before_fork: "deferred",+ input: "deferred",+ user_bash: "deferred",+ session_before_switch: "deferred",+ session_before_tree: "deferred",+ session_tree: "deferred",+ ui_prompt_start: "deferred",+ ui_prompt_end: "deferred",+} as const;++export function isKnownExtensionEvent(event: string): event is keyof typeof TRUSTED_EXTENSION_EVENT_CAPABILITIES {+ return Object.hasOwn(TRUSTED_EXTENSION_EVENT_CAPABILITIES, event);+}diff --git a/packages/agent-runtime/src/extensions/handler-lifecycle.ts b/packages/agent-runtime/src/extensions/handler-lifecycle.tsnew file mode 100644index 000000000..cb555f7e7--- /dev/null+++ b/packages/agent-runtime/src/extensions/handler-lifecycle.ts@@ -0,0 +1,39 @@+/** Owns waits, not arbitrary JavaScript or external side effects of trusted code. */+export class HandlerLifecycle {+ private controller = new AbortController();++ 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> {+ signal.throwIfAborted();+ return new Promise<T>((resolve, reject) => {+ const finish = (settle: () => void) => {+ clearTimeout(timer);+ signal.removeEventListener("abort", abort);+ settle();+ };+ const abort = () => finish(() => reject(signal.reason));+ const timer = setTimeout(+ () => finish(() => reject(new Error(`handler exceeded ${timeoutMs}ms`))),+ timeoutMs,+ );+ signal.addEventListener("abort", abort, { once: true });+ try {+ Promise.resolve(work()).then(+ (value) => finish(() => resolve(value)),+ (error: unknown) => finish(() => reject(error)),+ );+ } catch (error) {+ finish(() => reject(error));+ }+ });+ }+}diff --git a/packages/agent-runtime/src/extensions/runner.test.ts b/packages/agent-runtime/src/extensions/runner.test.tsindex 1164ce990..3902e1d89 100644--- a/packages/agent-runtime/src/extensions/runner.test.ts+++ b/packages/agent-runtime/src/extensions/runner.test.ts@@ -1,7 +1,7 @@import { mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { clearTrustedExtensionCache, TrustedExtensionRunner } from "./runner.js";import type {TrustedExtensionBridge,@@ -20,6 +20,7 @@ beforeEach(() => {});afterEach(() => {+ vi.useRealTimers();rmSync(root, { recursive: true, force: true });});@@ -84,6 +85,148 @@ function fakeBridge(const flush = () => new Promise((r) => setTimeout(r, 0));describe("TrustedExtensionRunner", () => {+ 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",@@ -239,6 +382,7 @@ export default function (pi: any) {"unsupported_api:sendMessage": 2,"unsupported_api:ui.setWidget": 1,"unsupported_api:on:made_up_event": 1,+ "unsupported_api:on:user_bash": 1,});expect(log.ui).toEqual([{ kind: "setStatus", key: "k", text: "busy" },diff --git a/packages/agent-runtime/src/extensions/runner.ts b/packages/agent-runtime/src/extensions/runner.tsindex 83744e6aa..61ec33158 100644--- a/packages/agent-runtime/src/extensions/runner.ts+++ b/packages/agent-runtime/src/extensions/runner.ts@@ -42,67 +42,13 @@ 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 {+ 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 = [@@ -345,22 +291,6 @@ function errorStack(err: unknown): string | undefined {return err instanceof Error ? err.stack : undefined;}-function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {- return new Promise<T>((resolve, reject) => {- const timer = setTimeout(() => reject(new Error(`handler exceeded ${ms}ms`)), ms);- promise.then(- (value) => {- clearTimeout(timer);- resolve(value);- },- (err) => {- clearTimeout(timer);- reject(err);- },- );- });-}-export type TrustedExtensionRunnerOptions = {specs: TrustedExtensionSpec[];bridge: TrustedExtensionBridge;@@ -377,6 +307,9 @@ 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();constructor(options: TrustedExtensionRunnerOptions) {this.bridge = options.bridge;@@ -390,7 +323,9 @@ export class TrustedExtensionRunner {/** Load every entry. A failing entry is reported and skipped (spec §4.4). */async load(): Promise<TrustedExtensionLoadReport[]> {+ const signal = this.lifecycle.signal;for (const spec of this.specs) {+ if (this.closing || signal.aborted) break;const extension: LoadedExtension = {spec,tools: new Map(),@@ -413,8 +348,11 @@ export class TrustedExtensionRunner {if (factory) for (const symbol of knownStubSymbols(spec.id)) reportStub(symbol);if (!factory) {try {- factory = await loadExtensionFactory(spec.entry, virtualModules);+ factory = await this.lifecycle.run(+ () => loadExtensionFactory(spec.entry, virtualModules), signal, TRUSTED_EXTENSION_HANDLER_TIMEOUT_MS,+ );} catch (err) {+ if (signal.aborted) break;this.report(spec.id, "load_error", errorMessage(err), undefined, errorStack(err));this.reports.set(spec.id, this.errorReport(spec.id));continue;@@ -427,12 +365,17 @@ export class TrustedExtensionRunner {factoryCache.set(spec.id, factory);}try {- await factory(this.createApi(extension));+ const loadedFactory = factory;+ await this.lifecycle.run(+ () => loadedFactory(this.createApi(extension)), signal, TRUSTED_EXTENSION_HANDLER_TIMEOUT_MS,+ );} catch (err) {+ if (signal.aborted) break;this.report(spec.id, "factory_error", errorMessage(err), undefined, errorStack(err));this.reports.set(spec.id, this.errorReport(spec.id));continue;}+ if (this.closing || signal.aborted) break;this.loaded.set(spec.id, extension);this.reports.set(spec.id, {extensionId: spec.id,@@ -443,17 +386,32 @@ export class TrustedExtensionRunner {eventNames: [...extension.handlers.keys()],});}+ if (this.closing || signal.aborted) return this.getLoadReports();this.bridge.publishCommands(this.getCommands());this.flushDiagnostics();await this.emit("session_start", { type: "session_start", reason: "startup" });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();+ this.bridge.publishCommands([]);+ }+ });+ return this.disposal;}getLoadReports(): TrustedExtensionLoadReport[] {@@ -530,6 +488,7 @@ export class TrustedExtensionRunner {/** Run `/<name> <args>` in this session (spec §8). Returns false when unknown. */async runCommand(name: string, args: string): Promise<boolean> {+ if (this.closing) return false;for (const extension of this.loaded.values()) {const command = extension.commands.get(name);if (!command) continue;@@ -553,23 +512,33 @@ export class TrustedExtensionRunner {payload: Record<string, unknown>,fold?: (acc: R | undefined, next: R) => R,): Promise<R | undefined> {- if (this.disposed) return undefined;+ if (this.closing) return undefined;+ return this.dispatch(event, payload, fold);+ }++ private async dispatch<R>(+ event: TrustedExtensionEventName,+ payload: Record<string, unknown>,+ fold?: (acc: R | undefined, next: R) => R,+ ): Promise<R | undefined> {+ const signal = this.lifecycle.signal;let acc: R | undefined;- const timed = RESULT_EVENTS.has(event);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;+ const result = await this.lifecycle.run(+ () => handler(payload, ctx), signal, TRUSTED_EXTENSION_HANDLER_TIMEOUT_MS,+ ) as R | undefined;+ if (signal.aborted || this.disposed) return undefined;if (result !== undefined && result !== null) {acc = fold ? fold(acc, result) : result;}} catch (err) {+ if (signal.aborted || this.disposed) return undefined;const kind: TrustedExtensionDiagnosticKind = /exceeded \d+ms/.test(errorMessage(err))? "handler_timeout": "handler_error";@@ -810,13 +779,13 @@ export class TrustedExtensionRunner {const api: Record<string, unknown> = {on: (event: string, handler: Handler) => {if (typeof handler !== "function") return;- if (- !NOT_EMITTED_EVENTS.has(event) &&- !(TRUSTED_EXTENSION_EVENTS as readonly string[]).includes(event)- ) {+ if (!isKnownExtensionEvent(event)) {this.report(extension.spec.id, "unsupported_api", `unknown event "${event}"`, `on:${event}`);return;}+ if (TRUSTED_EXTENSION_EVENT_CAPABILITIES[event] === "deferred") {+ this.report(extension.spec.id, "unsupported_api", `event "${event}" is not emitted by Desktop`, `on:${event}`);+ }const list = extension.handlers.get(event) ?? [];list.push(handler);extension.handlers.set(event, list);diff --git a/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts b/packages/agent-runtime/src/extensions/runtime-lifecycle.test.tsnew file mode 100644index 000000000..f840b6333--- /dev/null+++ b/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts@@ -0,0 +1,97 @@+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.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 --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 31decad4f..0a59693d1 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -7596,6 +7596,10 @@ Delegation rules:}}await this.extensionBeforeAgentStart(modelInput);+ if (this.runCancelled || this.disposed) {+ this.keepPreflightUserMessage(incomingUserMessage);+ throw turnAbortedError("Turn aborted during extension hooks");+ }if (typeof modelInput === "string") {await this.agent.prompt(modelInput);} else {@@ -7633,7 +7637,6 @@ Delegation rules:return { turnId: this.turnId };}- /** `before_agent_start` hook: extensions may replace the system prompt for this turn. */private async extensionBeforeAgentStart(input: string | RuntimePrompt): Promise<void> {const runner = this.extensionRunner;if (!runner) return;@@ -7642,7 +7645,8 @@ Delegation rules:// Handlers edit the headers object in place, as they do in the pi CLI.const headers: Record<string, string> = { ...(this.provider.headers ?? {}) };await runner.emit("before_provider_headers", { type: "before_provider_headers", headers });- this.extensionProviderHeaders = headers;+ if (this.runCancelled || this.disposed) return;+ this.extensionProviderHeaders = { ...headers };}if (!runner.hasHandlers("before_agent_start")) return;const base = this.composeSystemPrompt();@@ -7788,6 +7792,7 @@ Delegation rules:this.acceptingSteering = false;this.gracefulStopRequested = false;this.runCancelled = true;+ this.extensionRunner?.cancelPending();this.resolvePendingAskTools();this.abortRunningDelegations();this.turnSubagentUsage = undefined;@@ -7825,9 +7830,10 @@ Delegation rules:}async dispose(): Promise<void> {+ if (this.disposed) return;const runner = this.extensionRunner;this.extensionRunner = undefined;- if (runner) await runner.dispose().catch(() => undefined);+ const closingExtensions = runner?.dispose();this.streamSink.dispose();this.disposed = true;this.acceptingSteering = false;@@ -7851,5 +7857,6 @@ Delegation rules:this.cleanupActiveToolProgress();if (this.compactionInProgress) this.compactionAborted = true;this.compactionAbort?.abort();+ await closingExtensions;}}