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): recover from missing plan workspace
zszz3ac63d0fad1db
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 7ede74646..60639f7fb 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -657,6 +657,15 @@ no editing, delegation, fake user message or transcript deletion occurs.Other deferred/plugin tools keep their existing visibility rules. See[the declaration/permission decision](../../adr/plan-tool-declarations-and-execution-denials.md).+Plan/Goal entry remains available without a project workspace. A submission+requires a persisted session workspace for its approval artifact.+`PLAN_WORKSPACE_REQUIRED` from submission is a recoverable tool error: it+explains how to bind a workspace and directs the agent to present the proposal+in chat without retrying until a workspace is bound. It does not terminate the+model loop, create an approval, or authorize execution. Successful submission+still terminates for approval; other submission failures retain their existing+termination behavior.+Approval has only `approve` and `reject`. Approval commits `mode = agent`, theexplicit permission mode, an execution ID, and `execution_state = queued` onthe same `plan_approvals` row in one host transaction. Thediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 18869dc83..94c37e076 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -6731,6 +6731,22 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.- **Status**: Automated (passed 2026-08-04): `test:e2e:plan` plus host-corepermission/policy and agent-runtime tool-composition tests+#### E2E-PLAN-WORKSPACE: Missing workspace does not strand a contract turn++- **Preconditions**: Isolated host, active global workspace, temporary session+ without a persisted project workspace; repeat for Plan and Goal.+- **Steps**: Enter the contract from Agent mode and submit. In the runtime,+ submit from a workspace-less contract session, receive the tool error, deliver+ a final explanation, and repeat on+ the user's next "continue" turn. Use a bound project as the success control.+- **Expected**: Entry succeeds and leaves the session in planning state.+ Submission fails with `PLAN_WORKSPACE_REQUIRED` without an approval or+ artifact. The runtime returns a non-terminating error with workspace binding+ guidance and permits a final assistant response. No execution is authorized.+ Bound-project submission still produces a pending immutable checkpoint.+- **Status**: Automated by `scripts/e2e-plan.mjs` and the runtime Plan transition+ tests with a scripted provider boundary.+#### E2E-106: SubmitPlan rejects into editable planning and resubmits a new artifact- **Preconditions**: A project-bound session is idle in Plan with a provider;diff --git a/packages/agent-runtime/src/plan-workspace-error.ts b/packages/agent-runtime/src/plan-workspace-error.tsnew file mode 100644index 000000000..9f022239b--- /dev/null+++ b/packages/agent-runtime/src/plan-workspace-error.ts@@ -0,0 +1,24 @@+/** Missing workspace is recoverable without approving or executing a contract. */+export function planWorkspaceRequiredResult(error: unknown) {+ if (+ typeof error !== "object" ||+ error === null ||+ !("data" in error) ||+ typeof error.data !== "object" ||+ error.data === null ||+ !("errorCode" in error.data) ||+ error.data.errorCode !== "PLAN_WORKSPACE_REQUIRED"+ )+ return undefined;++ return {+ content: [+ {+ type: "text" as const,+ text: "A project workspace is required for Plan/Goal approval. Bind this session to a project workspace before retrying. Explain the limitation and present the proposal in chat for now; do not retry submission until a workspace is bound. No approval was created and execution is not authorized.",+ },+ ],+ details: { errorCode: "PLAN_WORKSPACE_REQUIRED" },+ isError: true,+ };+}diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex b26e27786..2f4dc3fe8 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -2424,6 +2424,132 @@ describe("DesktopAgentRuntime tool schema completeness (#864)", () => {});describe("DesktopAgentRuntime plan transitions", () => {+ it.each(["plan", "goal"] as const)(+ "continues the %s user turn after a missing-workspace submission",+ async (kind) => {+ const host = {+ call: vi.fn(async (method: string) => {+ if (method === "plans.submit") {+ throw Object.assign(new Error("PLAN_WORKSPACE_REQUIRED"), {+ data: { errorCode: "PLAN_WORKSPACE_REQUIRED" },+ });+ }+ return undefined;+ }),+ };+ const runtime = createRuntime({ host, mode: kind });+ const requests: AgentMessage[][] = [];+ const internals = runtime as unknown as {+ agent: Agent;+ models: {+ streamSimple: (+ model: unknown,+ context: { messages: AgentMessage[] },+ ) => ReturnType<typeof createAssistantMessageEventStream>;+ };+ };+ internals.models = {+ streamSimple: (_model, context) => {+ requests.push([...context.messages]);+ const submit = requests.length % 2 === 1;+ const message = assistantMessage({+ content: submit+ ? [+ {+ type: "toolCall",+ id: `submit-${requests.length}`,+ name: kind === "plan" ? "SubmitPlan" : "SubmitGoal",+ arguments: {+ title: "Proposal",+ markdown: "# Proposal",+ question: "Proceed?",+ },+ },+ ]+ : [+ {+ type: "text",+ text: "Bind a project workspace before submitting. Here is the proposal.",+ },+ ],+ stopReason: submit ? "toolUse" : "stop",+ }) as unknown as AssistantMessage;+ const stream = createAssistantMessageEventStream();+ queueMicrotask(() => {+ stream.push({ type: "start", partial: message });+ stream.push({+ type: "done",+ reason: submit ? "toolUse" : "stop",+ message,+ });+ stream.end(message);+ });+ return stream;+ },+ };+ try {+ await runtime.prompt(+ "Propose the work before changing anything.",+ "user-1",+ "turn-1",+ );+ expect(requests).toHaveLength(2);+ const result = requests[1].find(+ (message) => message.role === "toolResult",+ );+ expect(result).toMatchObject({ isError: true, toolCallId: "submit-1" });+ expect(JSON.stringify(result)).toContain(+ "Bind this session to a project workspace",+ );+ expect(internals.agent.state.messages.at(-1)).toMatchObject({+ role: "assistant",+ content: [+ {+ type: "text",+ text: expect.stringContaining("Here is the proposal"),+ },+ ],+ });+ expect(runtime.getStatus().planningState).toBe("planning");+ await runtime.prompt("Continue.", "user-2", "turn-2");+ expect(requests).toHaveLength(4);+ expect(internals.agent.state.messages.at(-1)).toMatchObject({+ role: "assistant",+ });+ } finally {+ await runtime.dispose();+ }+ },+ );++ it.each(["PLAN_ARTIFACT_WRITE_FAILED", "PLAN_SESSION_NOT_FOUND"])(+ "still terminates submission for %s",+ async (errorCode) => {+ const host = { call: vi.fn().mockRejectedValue({ data: { errorCode } }) };+ const runtime = createRuntime({ host, mode: "plan", turnId: "turn-1" });+ const { agent } = runtime as unknown as { agent: Agent };+ try {+ const tool = agent.state.tools.find(+ (entry) => entry.name === "SubmitPlan",+ );+ if (!tool) throw new Error("Missing submit tool");+ const result = await tool.execute("submit", {+ title: "Plan",+ markdown: "# Plan",+ question: "Proceed?",+ });+ expect(result).toMatchObject({+ isError: true,+ terminate: true,+ details: { errorCode },+ });+ expect(runtime.getStatus().planningState).toBe("planning");+ } finally {+ await runtime.dispose();+ }+ },+ );+it("guards transition batches and terminates after durable plan submission", async () => {const host = { call: vi.fn() };const runtime = createRuntime({ host, turnId: "turn-1" });diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 0c6140702..51745e99a 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -1,3 +1,4 @@+import { planWorkspaceRequiredResult } from "./plan-workspace-error.js";import { accountModelStream } from "./request-usage.js";import { modeToolDenial, retainModeToolDeclaration, withModeExecutionGuard } from "./mode-tool-access.js";import { restoreHostedSearchReplay } from "./hosted-search-replay.js";@@ -5398,6 +5399,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when thequestion,});} catch (error) {+ const recovery = planWorkspaceRequiredResult(error);+ if (recovery) return recovery;const errorCode =(error as { data?: { errorCode?: string } })?.data?.errorCode ??"PLAN_SUBMIT_FAILED";diff --git a/scripts/e2e-plan.mjs b/scripts/e2e-plan.mjsindex ff9b538f7..7cfc8ce57 100644--- a/scripts/e2e-plan.mjs+++ b/scripts/e2e-plan.mjs@@ -194,6 +194,28 @@ function bashParams(sessionId, toolCallId, shell, command, extra = {}) {};}+async function scenarioWorkspaceRequired(binary, tempRoot) {+ return withScenario("E2E-PLAN-WORKSPACE", async (ctx) => {+ for (const kind of ["plan", "goal"]) {+ const session = await createSession(ctx.host, undefined, "Temporary contract", "agent");+ const turnId = await beginTurn(ctx.host, session.id);+ const entered = await ctx.host.call("plans.enter", {+ sessionId: session.id, turnId, toolCallId: "enter", kind,+ });+ assert(entered.state === "planning", "temporary session cannot enter planning");+ await expectRpcError(() => ctx.host.call("plans.submit", {+ sessionId: session.id, turnId, toolCallId: "submit", kind,+ title: "Proposal", markdown: "# Proposal", question: "Proceed?",+ }), ["PLAN_WORKSPACE_REQUIRED"]);+ const pending = await ctx.host.call("plans.pending", { sessionId: session.id });+ assert(pending.state === "planning", "failed submission changed planning state");+ assert(pending.plans.length === 0, "failed submission created an approval");+ await endTurn(ctx.host, turnId);+ }+ return "Plan/Goal allow planning without a workspace but reject approval submission";+ }, binary, tempRoot);+}+async function scenario105(binary, tempRoot) {return withScenario("E2E-105", async (ctx) => {await writeFile(join(ctx.workspace, "readme.txt"), "Plan workspace read fixture\n", "utf8");@@ -973,6 +995,7 @@ async function main() {const tempRoot = await mkdtemp(join(tmpdir(), "pi-desktop-plan-e2e-"));try {+ await runScenario("E2E-PLAN-WORKSPACE", () => scenarioWorkspaceRequired(binary, tempRoot));await runScenario("E2E-105", () => scenario105(binary, tempRoot));await runScenario("E2E-106", () => scenario106(binary, tempRoot));await runScenario("E2E-PLAN-005", () => scenarioPlanSafePlugin(binary, tempRoot));