Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(code): make plan mode show, keep, and reload its plan (#83903)

Dylan Martin564a9957a6db
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/PlanApprovalCard.test.tsx b/products/desktop/apps/mobile/src/features/tasks/components/PlanApprovalCard.test.tsx
index f22275268d42..28bb5cb8046f 100644
--- a/products/desktop/apps/mobile/src/features/tasks/components/PlanApprovalCard.test.tsx
+++ b/products/desktop/apps/mobile/src/features/tasks/components/PlanApprovalCard.test.tsx
@@ -2,6 +2,7 @@ import { createElement } from "react";
import { TextInput } from "react-native";
import { act, create } from "react-test-renderer";
import { describe, expect, it, vi } from "vitest";
+import type { ToolStatus } from "@/features/chat";
import { PlanApprovalCard } from "./PlanApprovalCard";
vi.mock("phosphor-react-native", () => ({
@@ -47,7 +48,7 @@ function findPressableWithText(
describe("PlanApprovalCard", () => {
it("renders the plan with the markdown renderer", () => {
const plan = "# Plan\n\n1. Inspect renderer\n2. Fix markdown output";
- let renderer: ReturnType<typeof create> | null = null;
+ let renderer!: ReturnType<typeof create>;
act(() => {
renderer = create(
@@ -76,16 +77,104 @@ describe("PlanApprovalCard", () => {
);
});
- if (!renderer) {
- throw new Error("Renderer not created");
- }
+ expect(
+ renderer.root.find((node) => node.props.content === plan).props.content,
+ ).toBe(plan);
+ });
+
+ it("renders the plan from the tool call when the permission is gone", () => {
+ const plan = "# Plan\n\n1. Inspect renderer\n2. Fix markdown output";
+ let renderer!: ReturnType<typeof create>;
+
+ act(() => {
+ renderer = create(
+ createElement(PlanApprovalCard, {
+ toolData: {
+ toolCallId: "tool-plan",
+ status: "completed",
+ args: { plan },
+ },
+ }),
+ );
+ });
- expect(renderer.root.findByType("MarkdownText").props.content).toBe(plan);
+ expect(
+ renderer.root.find((node) => node.props.content === plan).props.content,
+ ).toBe(plan);
+ });
+
+ it.each<[ToolStatus, string, string]>([
+ ["error", "Sent back with guidance", "Plan approved"],
+ ["completed", "Plan approved", "Sent back with guidance"],
+ ])(
+ "shows the outcome for a %s plan when the permission is gone",
+ (status, expectedLabel, unexpectedLabel) => {
+ const plan = "# Plan\n\n1. Inspect renderer";
+ let renderer!: ReturnType<typeof create>;
+
+ act(() => {
+ renderer = create(
+ createElement(PlanApprovalCard, {
+ toolData: {
+ toolCallId: "tool-plan",
+ status,
+ args: { plan },
+ },
+ }),
+ );
+ });
+
+ const hasLabel = (label: string) =>
+ renderer.root.findAll((node) => node.props.children === label).length >
+ 0;
+
+ expect(hasLabel(expectedLabel)).toBe(true);
+ expect(hasLabel(unexpectedLabel)).toBe(false);
+ },
+ );
+
+ it("shows a rejection when a live permission has no local response and errored", () => {
+ const plan = "# Plan\n\n1. Inspect renderer";
+ let renderer!: ReturnType<typeof create>;
+
+ act(() => {
+ renderer = create(
+ createElement(PlanApprovalCard, {
+ toolData: {
+ toolCallId: "tool-plan",
+ status: "error",
+ args: { plan },
+ },
+ permission: {
+ requestId: "request-plan",
+ toolCall: {
+ toolCallId: "tool-plan",
+ title: "Ready to code?",
+ kind: "switch_mode",
+ rawInput: { plan },
+ },
+ options: [
+ {
+ kind: "allow_once",
+ optionId: "default",
+ name: "Yes, and manually approve edits",
+ },
+ ],
+ },
+ }),
+ );
+ });
+
+ const hasLabel = (label: string) =>
+ renderer.root.findAll((node) => node.props.children === label).length > 0;
+
+ expect(hasLabel("Sent back with guidance")).toBe(true);
+ expect(hasLabel("Plan approved")).toBe(false);
});
it("sends the selected approval option immediately", () => {
const onSendPermissionResponse = vi.fn();
- let renderer: ReturnType<typeof create> | null = null;
+ let renderer!: ReturnType<typeof create>;
act(() => {
renderer = create(
@@ -114,10 +203,6 @@ describe("PlanApprovalCard", () => {
);
});
- if (!renderer) {
- throw new Error("Renderer not created");
- }
-
const approveButton = findPressableWithText(
renderer,
"Yes, and manually approve edits",
@@ -136,7 +221,7 @@ describe("PlanApprovalCard", () => {
it("collects feedback before sending the reject option", () => {
const onSendPermissionResponse = vi.fn();
- let renderer: ReturnType<typeof create> | null = null;
+ let renderer!: ReturnType<typeof create>;
act(() => {
renderer = create(
@@ -166,10 +251,6 @@ describe("PlanApprovalCard", () => {
);
});
- if (!renderer) {
- throw new Error("Renderer not created");
- }
-
const feedbackOption = findPressableWithText(
renderer,
"No, and tell the agent what to do differently",
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/PlanApprovalCard.tsx b/products/desktop/apps/mobile/src/features/tasks/components/PlanApprovalCard.tsx
index a03ff18bea1d..051c03daa4b5 100644
--- a/products/desktop/apps/mobile/src/features/tasks/components/PlanApprovalCard.tsx
+++ b/products/desktop/apps/mobile/src/features/tasks/components/PlanApprovalCard.tsx
@@ -18,6 +18,7 @@ import type { CloudPendingPermissionRequest } from "../types";
interface ToolData {
toolCallId: string;
status: ToolStatus;
+ args?: Record<string, unknown>;
}
interface PermissionResponseArgs {
@@ -46,10 +47,12 @@ export function PlanApprovalCard({
const [customInput, setCustomInput] = useState("");
const response = permission?.response;
- const planText = useMemo(
- () => (permission ? extractPlanText(permission.toolCall) : null),
- [permission],
- );
+ const planText = useMemo(() => {
+ if (permission) {
+ return extractPlanText(permission.toolCall);
+ }
+ return extractPlanText({ rawInput: toolData.args });
+ }, [permission, toolData.args]);
const selectedOption = useMemo(
() =>
permission?.options.find(
@@ -62,7 +65,7 @@ export function PlanApprovalCard({
toolData.status === "completed" ||
toolData.status === "error";
- if (!permission) {
+ if (!permission && !planText) {
return null;
}
@@ -93,7 +96,7 @@ export function PlanApprovalCard({
null;
const resolvedAsReject = selectedOption
? isPermissionRejection(selectedOption)
- : false;
+ : toolData.status === "error";
return (
<View className="mx-4 my-1 rounded-lg border border-accent-6 bg-gray-2">
@@ -119,7 +122,7 @@ export function PlanApprovalCard({
showsVerticalScrollIndicator={false}
>
<View className="px-3 py-3">
- <MarkdownText content={planText} />
+ <MarkdownText content={planText} disableRemoteImages />
</View>
</ScrollView>
</View>
@@ -154,7 +157,7 @@ export function PlanApprovalCard({
</View>
</View>
</View>
- ) : (
+ ) : permission ? (
<View className="px-3 pb-3">
{permission.options.map((option) => {
const meta = getPermissionOptionMeta(option);
@@ -227,7 +230,7 @@ export function PlanApprovalCard({
);
})}
</View>
- )}
+ ) : null}
</View>
);
}
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts
index 84361c7343d1..3c0415d74058 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts
@@ -687,14 +687,8 @@ describe("ClaudeAcpAgent /clear", () => {
});
it("resets pre-clear plan and notification state so it can't resurface after /clear", async () => {
- // ExitPlanMode falls back to lastPlanContent/fileContentCache/
- // notificationHistory when its tool input omits an explicit plan; left
- // untouched, a plan written before /clear (possibly carrying
- // repo-injected content) could resurface in the fresh session.
const { agent } = makeAgent();
const { session } = installFakeSession(agent, "s-plan");
- (session as unknown as { lastPlanContent?: string }).lastPlanContent =
- "stale pre-clear plan";
(session as unknown as { lastPlanFilePath?: string }).lastPlanFilePath =
"/tmp/repo/.claude/plans/old.md";
session.notificationHistory.push({ type: "assistant", text: "old" });
@@ -705,9 +699,6 @@ describe("ClaudeAcpAgent /clear", () => {
prompt: [{ type: "text", text: "/clear" }],
});
- expect(
- (session as unknown as { lastPlanContent?: string }).lastPlanContent,
- ).toBeUndefined();
expect(
(session as unknown as { lastPlanFilePath?: string }).lastPlanFilePath,
).toBeUndefined();
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.permission-mode.test.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.permission-mode.test.ts
index adfc6415f962..fbe4634e2caa 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.permission-mode.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.permission-mode.test.ts
@@ -84,6 +84,21 @@ function installFakeSession(
return query;
}
+function sessionOf(agent: Agent): { lastPlanFilePath?: string } {
+ return (agent as unknown as { session: { lastPlanFilePath?: string } })
+ .session;
+}
+
+async function enterPlanModeViaHook(agent: Agent): Promise<void> {
+ const onModeChange = (
+ agent as unknown as {
+ createOnModeChange: () => (mode: CodeExecutionMode) => Promise<void>;
+ }
+ ).createOnModeChange();
+
+ await onModeChange("plan");
+}
+
describe("ClaudeAcpAgent.setSessionMode — SDK permission-mode translation", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -148,4 +163,37 @@ describe("ClaudeAcpAgent.setSessionMode — SDK permission-mode translation", ()
expect(session.permissionMode).toBe("plan");
expect(session.modeBeforePlan).toBe("auto");
});
+
+ it.each<[string, (agent: Agent) => Promise<void>]>([
+ [
+ "setSessionMode",
+ async (agent) => {
+ await agent.setSessionMode({ sessionId: "s-mode", modeId: "plan" });
+ },
+ ],
+ ["the EnterPlanMode hook", enterPlanModeViaHook],
+ ])(
+ "clears the prior cycle's plan file when %s starts a new planning cycle",
+ async (_entryPoint, enterPlanMode) => {
+ const { agent } = makeAgent();
+ installFakeSession(agent, "s-mode", "auto");
+ sessionOf(agent).lastPlanFilePath = "/tmp/repo/.claude/plans/old-plan.md";
+
+ await enterPlanMode(agent);
+
+ expect(sessionOf(agent).lastPlanFilePath).toBeUndefined();
+ },
+ );
+
+ it("keeps the plan file when plan mode is re-entered mid-cycle", async () => {
+ const { agent } = makeAgent();
+ installFakeSession(agent, "s-mode", "plan");
+ sessionOf(agent).lastPlanFilePath = "/tmp/repo/.claude/plans/drafting.md";
+
+ await agent.setSessionMode({ sessionId: "s-mode", modeId: "plan" });
+
+ expect(sessionOf(agent).lastPlanFilePath).toBe(
+ "/tmp/repo/.claude/plans/drafting.md",
+ );
+ });
});
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
index 743a5ce84e98..9e988d977d05 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
@@ -1879,13 +1879,9 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
session.taskState.clear();
this.toolUseStreamCache.clear();
this.emittedToolCalls.clear();
- // Nothing from before the boundary should be able to reach the fresh
- // session: reset the plan/notification state ExitPlanMode falls back
- // to when its tool input omits an explicit plan, so a stale (possibly
- // repo-injected) pre-clear plan can't resurface after approval.
+ // Nothing from before the boundary should reach the fresh session.
session.notificationHistory.length = 0;
session.lastPlanFilePath = undefined;
- session.lastPlanContent = undefined;
this.fileContentCache = {};
// Only broadcast (and thus persist) the "/clear" prompt once the new
@@ -2256,6 +2252,10 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
);
if (modeId === "plan" && previousMode !== "plan") {
this.session.modeBeforePlan = previousMode;
+ // A new planning cycle must not resolve against the prior cycle's plan
+ // file. Left set, an ExitPlanMode before this cycle's first plan write
+ // reads the old file, which passes validation and gets approved.
+ this.session.lastPlanFilePath = undefined;
}
try {
await this.session.query.setPermissionMode(
@@ -2811,6 +2811,9 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
this.session.queryOptions.permissionMode = toSdkPermissionMode(newMode);
if (newMode === "plan" && previousMode !== "plan") {
this.session.modeBeforePlan = previousMode;
+ // Same reason as applySessionMode: a new cycle must not inherit the
+ // prior cycle's plan file.
+ this.session.lastPlanFilePath = undefined;
}
}
await this.updateConfigOption("mode", newMode);
diff --git a/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.test.ts b/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.test.ts
index 184180bad00c..f52079bb6d4b 100644
--- a/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.test.ts
@@ -1,4 +1,7 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import * as fs from "node:fs/promises";
+import * as os from "node:os";
+import * as path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
compilePostHogExecPermissionRegex,
DEFAULT_POSTHOG_EXEC_PERMISSION_REGEX_SOURCE,
@@ -563,41 +566,79 @@ describe("AskUserQuestion cancelled outcomes", () => {
describe("ExitPlanMode plan resolution", () => {
const PLAN =
"# Add the CTA\n\nPut a signup button in the hero and point it at /signup.";
+ const SKELETON = "# Add the CTA\n\nTODO: fill this in before asking to code.";
+
+ let configDir: string;
+ let planFilePath: string;
+ let previousConfigDir: string | undefined;
+
+ beforeEach(async () => {
+ previousConfigDir = process.env.CLAUDE_CONFIG_DIR;
+ configDir = await fs.mkdtemp(path.join(os.tmpdir(), "plan-mode-"));
+ process.env.CLAUDE_CONFIG_DIR = configDir;
+ const plansDir = path.join(configDir, "plans");
+ await fs.mkdir(plansDir, { recursive: true });
+ planFilePath = path.join(plansDir, "add-the-cta.md");
+ });
+
+ afterEach(async () => {
+ if (previousConfigDir === undefined) {
+ delete process.env.CLAUDE_CONFIG_DIR;
+ } else {
+ process.env.CLAUDE_CONFIG_DIR = previousConfigDir;
+ }
+ await fs.rm(configDir, { recursive: true, force: true });
+ });
- function createPlanContext(emittedToolCalls: Set<string>) {
+ function planSession(overrides: Record<string, unknown> = {}) {
+ return {
+ permissionMode: "plan",
+ settingsManager: { getRepoRoot: vi.fn().mockReturnValue("/repo") },
+ ...overrides,
+ };
+ }
+
+ function exitPlanModeContext(
+ emittedToolCalls: Set<string>,
+ session: Record<string, unknown>,
+ requestPermission = vi.fn().mockResolvedValue({
+ outcome: { outcome: "selected", optionId: "default" },
+ }),
+ ) {
return createContext("ExitPlanMode", {
toolInput: {},
emittedToolCalls,
- session: {
- permissionMode: "plan",
- lastPlanContent: PLAN,
- notificationHistory: [],
- },
+ session,
applySessionMode: vi.fn().mockResolvedValue(undefined),
client: {
sessionUpdate: vi.fn().mockResolvedValue(undefined),
- requestPermission: vi.fn().mockResolvedValue({
- outcome: { outcome: "selected", optionId: "default" },
- }),
+ requestPermission,
},
});
}
- function planUpdates(context: Parameters<typeof canUseTool>[0]) {
+ function planUpdates(
+ context: Parameters<typeof canUseTool>[0],
+ plan: string,
+ ) {
return (context.client.sessionUpdate as ReturnType<typeof vi.fn>).mock.calls
.map(([notification]) => notification.update)
.filter(
(update: { rawInput?: { plan?: unknown } }) =>
- update.rawInput?.plan === PLAN,
+ update.rawInput?.plan === plan,
);
}
- it("emits the tool call with a plan recovered from the plan file", async () => {
- const context = createPlanContext(new Set());
+ it("emits the tool call with the plan read from the plan file", async () => {
+ await fs.writeFile(planFilePath, PLAN);
+ const context = exitPlanModeContext(
+ new Set(),
+ planSession({ lastPlanFilePath: planFilePath }),
+ );
await canUseTool(context);
- expect(planUpdates(context)).toEqual([
+ expect(planUpdates(context, PLAN)).toEqual([
expect.objectContaining({
sessionUpdate: "tool_call",
kind: "switch_mode",
@@ -605,12 +646,16 @@ describe("ExitPlanMode plan resolution", () => {
]);
});
- it("backfills the recovered plan onto an already-emitted tool call", async () => {
- const context = createPlanContext(new Set(["test-tool-use-id"]));
+ it("backfills the plan onto an already-emitted tool call", async () => {
+ await fs.writeFile(planFilePath, PLAN);
+ const context = exitPlanModeContext(
+ new Set(["test-tool-use-id"]),
+ planSession({ lastPlanFilePath: planFilePath }),
+ );
await canUseTool(context);
- expect(planUpdates(context)).toEqual([
+ expect(planUpdates(context, PLAN)).toEqual([
expect.objectContaining({
sessionUpdate: "tool_call_update",
toolCallId: "test-tool-use-id",
@@ -622,4 +667,86 @@ describe("ExitPlanMode plan resolution", () => {
}),
]);
});
+
+ it("reviews the plan as last edited, not the draft first written", async () => {
+ const session = planSession();
+ await fs.writeFile(planFilePath, SKELETON);
+ await canUseTool(
+ createContext("Write", {
+ session,
+ toolInput: { file_path: planFilePath, content: SKELETON },
+ }),
+ );
+
+ await fs.writeFile(planFilePath, PLAN);
+ const context = exitPlanModeContext(new Set(["test-tool-use-id"]), session);
+
+ await canUseTool(context);
+
+ expect(planUpdates(context, PLAN)).toHaveLength(1);
+ expect(planUpdates(context, SKELETON)).toEqual([]);
+ });
+
+ it.each(["auto", "acceptEdits", "default"])(
+ "surfaces the plan when the session mode is %s while the CLI is planning",
+ async (permissionMode) => {
+ const session = planSession({ permissionMode });
+ await fs.writeFile(planFilePath, PLAN);
+ await canUseTool(
+ createContext("Write", {
+ session,
+ toolInput: { file_path: planFilePath, content: PLAN },
+ }),
+ );
+
+ const context = exitPlanModeContext(
+ new Set(["test-tool-use-id"]),
+ session,
+ );
+ await canUseTool(context);
+
+ expect(planUpdates(context, PLAN)).toHaveLength(1);
+ },
+ );
+
+ it("requests approval again when the plan changes during review", async () => {
+ const edited =
+ "# Add the CTA\n\nPut it in the nav instead, and add a test.";
+ await fs.writeFile(planFilePath, PLAN);
+ let requestCount = 0;
+ const requestPermission = vi.fn().mockImplementation(async () => {
+ requestCount += 1;
+ if (requestCount === 1) {
+ await fs.writeFile(planFilePath, edited);
+ }
+ return { outcome: { outcome: "selected", optionId: "default" } };
+ });
+ const context = exitPlanModeContext(
+ new Set(["test-tool-use-id"]),
+ planSession({ lastPlanFilePath: planFilePath }),
+ requestPermission,
+ );
+
+ const result = await canUseTool(context);
+
+ expect(requestPermission).toHaveBeenCalledTimes(2);
+ expect(requestPermission.mock.calls[1]?.[0].toolCall.rawInput.plan).toBe(
+ edited,
+ );
+ expect(result.behavior).toBe("allow");
+ if (result.behavior === "allow") {
+ expect(result.updatedInput.plan).toBe(edited);
+ }
+ });
+
+ it("denies without a plan file rather than approving an empty plan", async () => {
+ const context = exitPlanModeContext(new Set(), planSession());
+
+ const result = await canUseTool(context);
+
+ expect(result.behavior).toBe("deny");
+ if (result.behavior === "deny") {
+ expect(result.interrupt).toBe(false);
+ }
+ });
});
diff --git a/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.ts b/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.ts
index c6aad314abbb..80caa469cd96 100644
--- a/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/permissions/permission-handlers.ts
@@ -24,9 +24,10 @@ import {
} from "../mcp/tool-metadata";
import {
getClaudePlansDir,
- getLatestAssistantText,
isClaudePlanFilePath,
isPlanReady,
+ isSubagentPlanFilePath,
+ readPlanFile,
} from "../plan/utils";
import {
type AskUserQuestionInput,
@@ -172,32 +173,27 @@ async function buildDenialResult(
return { behavior: "deny", message, interrupt: !feedback };
}
-function getPlanFromFile(
- session: Session,
- fileContentCache: { [key: string]: string },
-): string | undefined {
- return (
- session.lastPlanContent ||
- (session.lastPlanFilePath
- ? fileContentCache[session.lastPlanFilePath]
- : undefined)
- );
+function extractPlanText(input: Record<string, unknown>): string | undefined {
+ const plan = (input as { plan?: unknown })?.plan;
+ return typeof plan === "string" ? plan : undefined;
}
-function ensurePlanInInput(
- toolInput: Record<string, unknown>,
- fallbackPlan: string | undefined,
-): Record<string, unknown> {
- const hasPlan = typeof (toolInput as { plan?: unknown })?.plan === "string";
- if (hasPlan || !fallbackPlan) {
+async function resolvePlanInput(
+ context: ToolHandlerContext,
+): Promise<Record<string, unknown>> {
+ const { session, toolInput } = context;
+ const planFilePath = session.lastPlanFilePath;
+ const planFromFile = planFilePath ? await readPlanFile(planFilePath) : null;
+ const plan = planFromFile ?? extractPlanText(toolInput);
+
+ if (!plan) {
return toolInput;
}
- return { ...toolInput, plan: fallbackPlan };
-}
+ if (!planFilePath) {
+ return { ...toolInput, plan };
+ }
-function extractPlanText(input: Record<string, unknown>): string | undefined {
- const plan = (input as { plan?: unknown })?.plan;
- return typeof plan === "string" ? plan : undefined;
+ return { ...toolInput, plan, planFilePath };
}
async function createPlanValidationError(
@@ -212,8 +208,11 @@ async function validatePlanContent(
planText: string | undefined,
context: ToolHandlerContext,
): Promise<{ valid: true } | { valid: false; error: ToolPermissionResult }> {
+ const planFile = context.session.lastPlanFilePath;
+
if (!planText) {
- const message = `Plan not ready. Provide the full markdown plan in ExitPlanMode or write it to ${getClaudePlansDir()} before requesting approval.`;
+ const target = planFile ?? `a file in ${getClaudePlansDir()}`;
+ const message = `No plan to review. Write your plan to ${target}, then call ExitPlanMode again.`;
return {
valid: false,
error: await createPlanValidationError(message, context),
@@ -221,8 +220,8 @@ async function validatePlanContent(
}
if (!isPlanReady(planText)) {
- const message =
- "Plan not ready. Provide the full markdown plan in ExitPlanMode before requesting approval.";
+ const target = planFile ?? "your plan file";
+ const message = `The plan in ${target} is too thin to review. It needs a markdown heading and enough detail to act on. Expand it, then call ExitPlanMode again.`;
return {
valid: false,
error: await createPlanValidationError(message, context),
@@ -232,6 +231,22 @@ async function validatePlanContent(
return { valid: true };
}
+async function publishPlanUpdate(
+ context: ToolHandlerContext,
+ input: Record<string, unknown>,
+ toolInfo: { content?: ToolCallContent[] },
+): Promise<void> {
+ await context.client.sessionUpdate({
+ sessionId: context.sessionId,
+ update: {
+ sessionUpdate: "tool_call_update",
+ toolCallId: context.toolUseID,
+ rawInput: input,
+ content: toolInfo.content,
+ },
+ });
+}
+
async function publishResolvedPlan(
context: ToolHandlerContext,
updatedInput: Record<string, unknown>,
@@ -244,15 +259,7 @@ async function publishResolvedPlan(
return;
}
- await context.client.sessionUpdate({
- sessionId: context.sessionId,
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: context.toolUseID,
- rawInput: updatedInput,
- content: toolInfo.content,
- },
- });
+ await publishPlanUpdate(context, updatedInput, toolInfo);
}
async function requestPlanApproval(
@@ -340,24 +347,41 @@ async function handleEnterPlanModeTool(
async function handleExitPlanModeTool(
context: ToolHandlerContext,
): Promise<ToolPermissionResult> {
- const { session, toolInput, fileContentCache } = context;
+ let updatedInput = await resolvePlanInput(context);
+
+ while (true) {
+ const validationResult = await validatePlanContent(
+ extractPlanText(updatedInput),
+ context,
+ );
+ if (!validationResult.valid) {
+ return validationResult.error;
+ }
- const planFromFile = getPlanFromFile(session, fileContentCache);
- const latestText = getLatestAssistantText(session.notificationHistory);
- const fallbackPlan = planFromFile || (latestText ?? undefined);
- const updatedInput = ensurePlanInInput(toolInput, fallbackPlan);
- const planText = extractPlanText(updatedInput);
+ const response = await requestPlanApproval(context, updatedInput);
+ if (context.signal?.aborted || response.outcome?.outcome === "cancelled") {
+ throw new Error("Tool use aborted");
+ }
- const validationResult = await validatePlanContent(planText, context);
- if (!validationResult.valid) {
- return validationResult.error;
- }
+ if (
+ response.outcome?.outcome === "selected" &&
+ (response.outcome.optionId === "auto" ||
+ response.outcome.optionId === "default" ||
+ response.outcome.optionId === "acceptEdits" ||
+ response.outcome.optionId === "bypassPermissions")
+ ) {
+ const latestInput = await resolvePlanInput({
+ ...context,
+ toolInput: updatedInput,
+ });
+ if (extractPlanText(latestInput) !== extractPlanText(updatedInput)) {
+ updatedInput = latestInput;
+ continue;
+ }
+ }
- const response = await requestPlanApproval(context, updatedInput);
- if (context.signal?.aborted || response.outcome?.outcome === "cancelled") {
- throw new Error("Tool use aborted");
+ return await applyPlanApproval(response, context, updatedInput);
}
- return await applyPlanApproval(response, context, updatedInput);
}
function buildQuestionOptions(question: QuestionItem) {
@@ -677,6 +701,24 @@ async function handlePostHogExecApprovalFlow(
return buildDenialResult(context, response);
}
+function recordPlanFile(context: ToolHandlerContext): void {
+ const { session, toolName, toolInput } = context;
+
+ if (!WRITE_TOOLS.has(toolName)) {
+ return;
+ }
+
+ const filePath = (toolInput as { file_path?: string })?.file_path;
+ if (!filePath || !isClaudePlanFilePath(filePath)) {
+ return;
+ }
+ if (isSubagentPlanFilePath(filePath)) {
+ return;
+ }
+
+ session.lastPlanFilePath = filePath;
+}
+
function handlePlanFileException(
context: ToolHandlerContext,
): ToolPermissionResult | null {
@@ -686,17 +728,10 @@ function handlePlanFileException(
return null;
}
- const filePath = (toolInput as { file_path?: string })?.file_path;
- if (!isClaudePlanFilePath(filePath)) {
+ if (!isClaudePlanFilePath((toolInput as { file_path?: string })?.file_path)) {
return null;
}
- session.lastPlanFilePath = filePath;
- const content = (toolInput as { content?: string })?.content;
- if (typeof content === "string") {
- session.lastPlanContent = content;
- }
-
return {
behavior: "allow",
updatedInput: toolInput as Record<string, unknown>,
@@ -764,6 +799,8 @@ export async function canUseTool(
): Promise<ToolPermissionResult> {
const { toolName, toolInput, session, allowedDomains } = context;
+ recordPlanFile(context);
+
// Enforce domain allowlist for web tools
if (allowedDomains && allowedDomains.length > 0) {
if (toolName === "WebFetch" || toolName === "WebSearch") {
diff --git a/products/desktop/packages/agent/src/adapters/claude/plan/utils.test.ts b/products/desktop/packages/agent/src/adapters/claude/plan/utils.test.ts
new file mode 100644
index 000000000000..370d5cdb2695
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/claude/plan/utils.test.ts
@@ -0,0 +1,22 @@
+import * as path from "node:path";
+import type { ExitPlanModeInput } from "@anthropic-ai/claude-agent-sdk/sdk-tools.js";
+import { describe, expect, it } from "vitest";
+import { isSubagentPlanFilePath } from "./utils";
+
+type Assert<T extends true> = T;
+type _NoPlanOnExitPlanModeInput = Assert<
+ ExitPlanModeInput extends { plan: string } ? false : true
+>;
+
+describe("isSubagentPlanFilePath", () => {
+ it.each([
+ ["calm-roaming-inlet-agent-ae27af0da6318b9d6.md", true],
+ ["calm-roaming-inlet.md", false],
+ ["rename-the-agent-decade.md", false],
+ ["agent-notes.md", false],
+ ])("treats %s as a subagent plan: %s", (basename, expected) => {
+ expect(
+ isSubagentPlanFilePath(path.join("/home/u/.claude/plans", basename)),
+ ).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/agent/src/adapters/claude/plan/utils.ts b/products/desktop/packages/agent/src/adapters/claude/plan/utils.ts
index bb32f7c80c5f..c9677a28f6ad 100644
--- a/products/desktop/packages/agent/src/adapters/claude/plan/utils.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/plan/utils.ts
@@ -1,6 +1,6 @@
+import * as fs from "node:fs/promises";
import * as os from "node:os";
import * as path from "node:path";
-import type { SessionNotification } from "@agentclientprotocol/sdk";
function getClaudeConfigDir(): string {
return process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
@@ -17,6 +17,10 @@ export function isClaudePlanFilePath(filePath: string | undefined): boolean {
return resolved === plansDir || resolved.startsWith(plansDir + path.sep);
}
+export function isSubagentPlanFilePath(filePath: string): boolean {
+ return /-agent-[0-9a-f]{8,}\.md$/i.test(path.basename(filePath));
+}
+
export function isPlanReady(plan: string | undefined): boolean {
if (!plan) return false;
const trimmed = plan.trim();
@@ -24,33 +28,14 @@ export function isPlanReady(plan: string | undefined): boolean {
return /(^|\n)#{1,6}\s+\S/.test(trimmed);
}
-export function getLatestAssistantText(
- notifications: SessionNotification[],
-): string | null {
- const chunks: string[] = [];
- let started = false;
-
- for (let i = notifications.length - 1; i >= 0; i -= 1) {
- const update = notifications[i]?.update;
- if (!update) continue;
-
- if (update.sessionUpdate === "agent_message_chunk") {
- started = true;
- const content = update.content as {
- type?: string;
- text?: string;
- } | null;
- if (content?.type === "text" && content.text) {
- chunks.push(content.text);
- }
- continue;
- }
-
- if (started) {
- break;
+export async function readPlanFile(filePath: string): Promise<string | null> {
+ try {
+ const content = await fs.readFile(filePath, "utf8");
+ if (!content.trim()) {
+ return null;
}
+ return content;
+ } catch {
+ return null;
}
-
- if (chunks.length === 0) return null;
- return chunks.reverse().join("");
}
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.test.ts b/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.test.ts
index ff92a4b6730f..fb3749e74159 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.test.ts
@@ -524,6 +524,32 @@ describe("conversationTurnsToJsonlEntries", () => {
expect(parsed.slug).toBeDefined();
});
+ it("derives a stable slug from the session id across rehydrations", () => {
+ const turns = [
+ {
+ role: "user" as const,
+ content: [{ type: "text" as const, text: "hello" }],
+ },
+ ];
+ const slugOf = (lines: string[]) =>
+ parseConversationEntries(lines).find((e: { slug?: string }) => e.slug)
+ ?.slug;
+
+ const slugFor = (sessionId: string) =>
+ slugOf(conversationTurnsToJsonlEntries(turns, { ...config, sessionId }));
+
+ const first = slugOf(conversationTurnsToJsonlEntries(turns, config));
+
+ expect(first).toBeDefined();
+ expect(slugOf(conversationTurnsToJsonlEntries(turns, config))).toBe(first);
+ expect(slugFor("sess-2")).not.toBe(first);
+
+ const sameMillisecondA = "01a011f5-c8f3-73d9-a32e-ff7eee2a8793";
+ const sameMillisecondB = "01a011f5-c8f3-7b41-9c05-1122334455aa";
+
+ expect(slugFor(sameMillisecondA)).not.toBe(slugFor(sameMillisecondB));
+ });
+
it("chains parentUuid across conversation entries", () => {
const lines = conversationTurnsToJsonlEntries(
[
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.ts b/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.ts
index a9fb6f0268f9..0f1c620b2384 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.ts
@@ -1,4 +1,4 @@
-import { randomUUID } from "node:crypto";
+import { createHash, randomUUID } from "node:crypto";
import * as fs from "node:fs/promises";
import * as os from "node:os";
import * as path from "node:path";
@@ -367,64 +367,10 @@ function generateMessageId(): string {
return id;
}
-const ADJECTIVES = [
- "bright",
- "calm",
- "daring",
- "eager",
- "fair",
- "gentle",
- "happy",
- "keen",
- "lively",
- "merry",
- "noble",
- "polite",
- "quick",
- "sharp",
- "warm",
- "witty",
-];
-const VERBS = [
- "blazing",
- "crafting",
- "dashing",
- "flowing",
- "gliding",
- "humming",
- "jumping",
- "linking",
- "melting",
- "nesting",
- "pacing",
- "roaming",
- "sailing",
- "turning",
- "waving",
- "zoning",
-];
-const NOUNS = [
- "aurora",
- "breeze",
- "cedar",
- "delta",
- "ember",
- "frost",
- "grove",
- "haven",
- "inlet",
- "jewel",
- "knoll",
- "lotus",
- "maple",
- "nexus",
- "oasis",
- "prism",
-];
-
-function generateSlug(): string {
- const pick = (arr: string[]) => arr[Math.floor(Math.random() * arr.length)];
- return `${pick(ADJECTIVES)}-${pick(VERBS)}-${pick(NOUNS)}`;
+function sessionSlug(sessionId: string): string {
+ const digest = createHash("sha256").update(sessionId).digest("hex");
+
+ return `session-${digest.slice(0, 12)}`;
}
export function conversationTurnsToJsonlEntries(
@@ -436,7 +382,7 @@ export function conversationTurnsToJsonlEntries(
const model = config.model ?? DEFAULT_GATEWAY_MODEL;
const version = config.version ?? "2.1.63";
const gitBranch = config.gitBranch ?? "";
- const slug = config.slug ?? generateSlug();
+ const slug = config.slug ?? sessionSlug(config.sessionId);
const permissionMode = config.permissionMode ?? "default";
const baseTime = Date.now() - turns.length * 3000;
let turnIndex = 0;
diff --git a/products/desktop/packages/agent/src/adapters/claude/types.ts b/products/desktop/packages/agent/src/adapters/claude/types.ts
index 7053955835bf..55fe57b55bdc 100644
--- a/products/desktop/packages/agent/src/adapters/claude/types.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/types.ts
@@ -92,7 +92,6 @@ export type Session = BaseSession & {
cwd: string;
taskRunId?: string;
lastPlanFilePath?: string;
- lastPlanContent?: string;
effort?: EffortLevel;
/** User intent; retained while a non-fast model hides the "fast" option. */
fastModeEnabled: boolean;
diff --git a/products/desktop/scripts/mobile-type-baseline.json b/products/desktop/scripts/mobile-type-baseline.json
index d98222dc6cc2..aeccbdf3fb77 100644
--- a/products/desktop/scripts/mobile-type-baseline.json
+++ b/products/desktop/scripts/mobile-type-baseline.json
@@ -42,9 +42,6 @@
"src/features/navigation/components/NavDrawer.tsx": {
"TS2551 Property 'absoluteFillObject' does not exist on type 'typeof StyleSheet'. Did you mean 'absoluteFill'?": 2
},
- "src/features/tasks/components/PlanApprovalCard.test.tsx": {
- "TS2339 Property 'root' does not exist on type 'never'.": 2
- },
"src/features/tasks/components/PlanApprovalCard.tsx": {
"TS2345 Argument of type 'CloudPermissionOption' is not assignable to parameter of type 'PermissionOption'.": 3
},