Skip to content

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

fix(agent-runtime): run extensions in the session scratch when unbound

GalaxyXieyue9693c1399c0
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 76a5df735..f5f86dea7 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -9617,7 +9617,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| Post-baseline local automation | E2E-220 |
| Post-baseline local automation (MCP `pi_session_get` large compaction) | E2E-MCP-session-get-projects-large-compaction |
| 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-HOOKS-prompt-chain, 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) | E2E-DIALOG-long-text-boundaries, E2E-241, E2E-242, E2E-HOOKS-prompt-chain, E2E-HOOKS-cancel-and-dispose, E2E-TRUSTED-EXTENSION-custom-agent-stream-and-binding, E2E-243, E2E-TRUSTED-EXTENSION-temporary-session-cwd-is-scratch, 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 |
@@ -14691,6 +14691,22 @@ plugin-form fixtures in an isolated temporary directory at runtime.
- **Milestone**: Post-MVP (R7 v1)
- **Status**: Partially automated (`pnpm test:e2e:trusted-extensions`); global/composer command discovery, prompt broker round-trip, abort, session rename, exec, and Host-owned queue pass, while no-session and remote-control cases remain additional validation.
+#### E2E-TRUSTED-EXTENSION-temporary-session-cwd-is-scratch: Extensions in a temporary session work in its scratch
+
+- **Preconditions**: An enabled fixture extension registering command `where`
+ that reports `ctx.cwd`, `ctx.sessionManager.getCwd()`, and the working
+ directory of a child started with `pi.exec` without a `cwd` option.
+- **Steps**: 1) Start a temporary session (no project) and run `/where`
+ before any tool call. 2) Run `/where` in a project session.
+- **Expected**: In the temporary session all three values are the session's
+ `scratch/<sessionId>` directory, which exists and the child starts in; none
+ is the sidecar's process directory. In the project session all three are
+ the project root, and no scratch directory is created for the extension.
+- **Specs linked**: `07-plugins/16-trusted-extensions.md` §7; D114
+- **Acceptance**: A (app control), Quality
+- **Milestone**: Post-MVP (R7 v1)
+- **Status**: Unit-covered (`packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts`); Electron journey Documented
+
#### E2E-244: Unsupported APIs, load errors, and handler timeouts degrade to diagnostics
- **Preconditions**: Four enabled fixture extensions: one importing
diff --git a/docs/spec/07-plugins/16-trusted-extensions.md b/docs/spec/07-plugins/16-trusted-extensions.md
index 010776a56..1250af2c6 100644
--- a/docs/spec/07-plugins/16-trusted-extensions.md
+++ b/docs/spec/07-plugins/16-trusted-extensions.md
@@ -419,7 +419,10 @@ the UI broker's own prompt timeout does not extend that budget.
4. Every execution writes an audit line with extension id, tool name, and
duration. Parameters are not logged.
5. `exec` runs in the sidecar with the session's working directory and the
- session's proxy and environment settings.
+ session's proxy and environment settings. That directory, also `ctx.cwd`,
+ is the project root; a temporary session uses its own scratch directory
+ (D114), which the runtime creates before extensions load, never the
+ sidecar's process directory.
## 8. Commands
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.md
index f1348c06c..2f702374f 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
@@ -5677,7 +5677,7 @@ eleven-tool-round desktop paths are verified by
| 基线后本地自动化 | E2E-220 |
| 基线后本地自动化(MCP `pi_session_get` 超大 compaction) | E2E-MCP-session-get-projects-large-compaction |
| 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-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) | E2E-DIALOG-long-text-boundaries、E2E-241、E2E-242、E2E-HOOKS-cancel-and-dispose、E2E-243、E2E-TRUSTED-EXTENSION-temporary-session-cwd-is-scratch、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 |
@@ -7829,6 +7829,21 @@ runner 会在运行时的隔离临时目录中生成六个插件形态 fixture
- **里程碑**:MVP 后(R7 v1)
- **状态**:部分自动化(`pnpm test:e2e:trusted-extensions`);全局/Composer 命令发现、提示 broker 往返、中止、会话重命名、exec 和 Host 队列已覆盖;无会话与远程控制仍需额外验证
+#### E2E-TRUSTED-EXTENSION-temporary-session-cwd-is-scratch:临时会话里的扩展在本会话 scratch 中工作
+
+- **前置条件**:一个已启用的夹具扩展,注册命令 `where`,报告 `ctx.cwd`、
+ `ctx.sessionManager.getCwd()`,以及不带 `cwd` 选项用 `pi.exec` 启动的子进程的
+ 工作目录。
+- **步骤**:1)开一个临时会话(无项目),在任何工具调用之前运行 `/where`。
+ 2)在项目会话中运行 `/where`。
+- **预期**:临时会话中三个值都是该会话的 `scratch/<sessionId>` 目录,该目录存在且
+ 子进程在其中启动;没有一个是 sidecar 的进程目录。项目会话中三个值都是项目根,
+ 且不会为扩展创建 scratch 目录。
+- **链接规格**:`07-plugins/16-trusted-extensions.md` §7;D114
+- **验收**:A(应用控制)、质量
+- **里程碑**:MVP 后(R7 v1)
+- **状态**:单元测试覆盖(`packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts`);Electron 流程已记录
+
#### E2E-244:不支持的 API、加载错误与处理器超时降级为诊断
- **前置条件**:四个已启用的夹具扩展:一个在顶层导入 `@earendil-works/pi-tui` 并
diff --git a/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md b/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md
index be5dbff66..ec0cd5aad 100644
--- a/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md
+++ b/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md
@@ -244,7 +244,9 @@ UI broker 自身的提示超时不会延长该预算。
3. 执行在 sidecar 内按 `ExtensionAPI` 的 `execute` 签名进行。不弹出宿主权限提示;信任决定已
在启用时做出。`onUpdate` 流映射到工具执行更新事件。
4. 每次执行写一条审计记录,含扩展 id、工具名和耗时。不记录参数。
-5. `exec` 在 sidecar 内以会话工作目录、会话代理和环境设置运行。
+5. `exec` 在 sidecar 内以会话工作目录、会话代理和环境设置运行。该目录(也是
+ `ctx.cwd`)是项目根;临时会话使用它自己的 scratch 目录(D114),运行时在加载
+ 扩展前创建,不会退回 sidecar 的进程目录。
## 8. 命令
diff --git a/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts b/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts
index 1aa06fa22..ad7f0b079 100644
--- a/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts
+++ b/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts
@@ -1,5 +1,5 @@
import { createServer } from "node:http";
-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
@@ -15,6 +15,44 @@ function deferred<T>() {
return { promise, resolve };
}
+type CwdProbe = { cwd: string; getCwd: string; exec: string };
+
+/** A trusted extension whose `where` command reports every cwd it can see (#1459). */
+async function probeExtensionCwd(options: { projectPath?: string; scratchDir: string; root: string }) {
+ const key = `__piCwdProbe_${Math.random().toString(36).slice(2)}`;
+ const entry = join(options.root, "cwd-probe.ts");
+ writeFileSync(entry, `export default function (pi) {
+ pi.registerCommand("where", { handler: async (_args, ctx) => {
+ const run = await pi.exec(process.execPath, ["-e", "process.stdout.write(process.cwd())"]);
+ globalThis[${JSON.stringify(key)}] = { cwd: ctx.cwd, getCwd: ctx.sessionManager.getCwd(), exec: run.stdout };
+ } });
+ }`);
+ const runtime = new DesktopAgentRuntime({
+ host: { call: async () => ({}), onNotification: () => () => {} } as never,
+ sessionId: "cwd-probe",
+ ...(options.projectPath ? { projectPath: options.projectPath } : {}),
+ scratchDir: options.scratchDir,
+ 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 },
+ trustedExtensions: [{ id: entry, entry, label: "Cwd probe", root: options.root, source: "plugin" }],
+ onEvent: () => {},
+ });
+ try {
+ await runtime.loadTrustedExtensions();
+ expect(await runtime.runTrustedExtensionCommand("where", "")).toEqual({ handled: true });
+ return (globalThis as Record<string, unknown>)[key] as CwdProbe;
+ } finally {
+ await runtime.dispose();
+ delete (globalThis as Record<string, unknown>)[key];
+ }
+}
+
describe("Desktop extension lifecycle", () => {
it("loads trusted extensions once when the first calls race the lazy import", async () => {
const root = mkdtempSync(join(tmpdir(), "pi-hooks-load-race-"));
@@ -55,6 +93,35 @@ describe("Desktop extension lifecycle", () => {
}
});
+ it("gives extensions the session scratch as cwd in a temporary session (#1459)", async () => {
+ const root = mkdtempSync(join(tmpdir(), "pi-hooks-cwd-scratch-"));
+ // Scratch is created lazily (D114): it does not exist before the first use.
+ const scratchDir = join(root, "data", "scratch", "cwd-probe");
+ try {
+ const seen = await probeExtensionCwd({ scratchDir, root });
+ expect(existsSync(scratchDir)).toBe(true);
+ expect(seen.cwd).toBe(scratchDir);
+ expect(seen.getCwd).toBe(scratchDir);
+ expect(realpathSync(seen.exec)).toBe(realpathSync(scratchDir));
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it("keeps the project root as extension cwd in a project session", async () => {
+ const root = mkdtempSync(join(tmpdir(), "pi-hooks-cwd-project-"));
+ const scratchDir = join(root, "data", "scratch", "cwd-probe");
+ try {
+ const seen = await probeExtensionCwd({ projectPath: root, scratchDir, root });
+ expect(seen.cwd).toBe(root);
+ expect(seen.getCwd).toBe(root);
+ expect(realpathSync(seen.exec)).toBe(realpathSync(root));
+ expect(existsSync(scratchDir)).toBe(false);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
it("does not apply a session rename locally after its invocation is cancelled", async () => {
const rename = deferred<Record<string, never>>();
const runtime = new DesktopAgentRuntime({
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 4dff3fd77..0f0e5de36 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -18,6 +18,7 @@ import { createJevClassifierTool } from "./jev-classifier-tool.js";
import { scheduledToolParameters, scheduledToolDescriptions } from "./scheduled-tools.js";
import { withPiFileOpToolNames } from "./pi-file-ops.js";
import { randomUUID } from "node:crypto";
+import { mkdirSync } from "node:fs";
import {
settledDelegationMessage,
taskMessageSnapshot,
@@ -2728,11 +2729,28 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
getTrustedExtensionReports() {
return this.extensionRunner?.getLoadReports() ?? [];
}
+ /**
+ * The working directory extensions see: the project root, or the session
+ * scratch for a temporary session. Scratch is otherwise created lazily by the
+ * first host tool call (D114), so it is created here; a failure leaves the
+ * path in place, because loading extensions must not fail the session.
+ */
+ private extensionCwd(): string {
+ if (this.projectPath) return this.projectPath;
+ if (!this.scratchDir) return process.cwd();
+ try {
+ mkdirSync(this.scratchDir, { recursive: true });
+ } catch {
+ // pi.exec reports the missing directory itself.
+ }
+ return this.scratchDir;
+ }
+
private createExtensionBridge(): TrustedExtensionBridge {
const runtime = this;
return {
sessionId: this.sessionId,
- cwd: this.projectPath ?? process.cwd(),
+ cwd: this.extensionCwd(),
getModel: () => runtime.model,
setModel: (model, signal) => runtime.setExtensionModel(model, signal),
modelRegistry: runtime.extensionModelRegistry(),