Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
ToolCallContent,
} from "@agentclientprotocol/sdk";
import type {
PermissionMode,
PermissionRuleValue,
PermissionUpdate,
} from "@anthropic-ai/claude-agent-sdk";
Expand Down Expand Up @@ -39,6 +40,7 @@ import type { Session } from "../types";
import {
buildExitPlanModePermissionOptions,
buildPermissionOptions,
CLEAR_AND_CONTINUE_OPTION_ID,
} from "./permission-options";

const SPEAK_TOOL_ID = qualifiedLocalToolName(SPEAK_TOOL_NAME);
Expand Down Expand Up @@ -284,32 +286,72 @@ async function requestPlanApproval(
});
}

const PLAN_APPROVAL_MODE_OPTION_IDS = [
"auto",
"default",
"acceptEdits",
"bypassPermissions",
] as const satisfies readonly PermissionMode[];

function isPlanApprovalMode(value: string): value is PermissionMode {
return (PLAN_APPROVAL_MODE_OPTION_IDS as readonly string[]).includes(value);
}

function resolvePlanApprovalMode(
optionId: string,
response: RequestPermissionResponse,
previousMode?: string,
): PermissionMode | null {
if (isPlanApprovalMode(optionId)) {
return optionId;
}

// Opt-in clear-and-continue: honor the ModeSelector choice when present,
// otherwise fall back to the mode the session was in before plan mode.
if (optionId === CLEAR_AND_CONTINUE_OPTION_ID) {
const answers = response._meta?.answers as
| Record<string, string>
| undefined;
const fromAnswers = answers?.executionMode;
if (typeof fromAnswers === "string" && isPlanApprovalMode(fromAnswers)) {
return fromAnswers;
}
if (previousMode && isPlanApprovalMode(previousMode)) {
return previousMode;
}
return "default";
}

return null;
}

async function applyPlanApproval(
response: RequestPermissionResponse,
context: ToolHandlerContext,
updatedInput: Record<string, unknown>,
): Promise<ToolPermissionResult> {
if (
response.outcome?.outcome === "selected" &&
(response.outcome.optionId === "auto" ||
response.outcome.optionId === "default" ||
response.outcome.optionId === "acceptEdits" ||
response.outcome.optionId === "bypassPermissions")
) {
await context.applySessionMode(response.outcome.optionId);
await context.updateConfigOption("mode", response.outcome.optionId);
if (response.outcome?.outcome === "selected") {
const mode = resolvePlanApprovalMode(
response.outcome.optionId,
response,
context.session.modeBeforePlan,
);
if (mode) {
await context.applySessionMode(mode);
await context.updateConfigOption("mode", mode);

return {
behavior: "allow",
updatedInput,
updatedPermissions: context.suggestions ?? [
{
type: "setMode",
mode: response.outcome.optionId,
destination: "localSettings",
},
],
};
return {
behavior: "allow",
updatedInput,
updatedPermissions: context.suggestions ?? [
{
type: "setMode",
mode,
destination: "localSettings",
},
],
};
}
}

const customInput = (response._meta as Record<string, unknown> | undefined)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,20 @@ describe("buildExitPlanModePermissionOptions", () => {
expect(options[options.length - 1].optionId).toBe("reject_with_feedback");
});

it("includes an opt-in clear-and-continue option before reject", () => {
const options = buildExitPlanModePermissionOptions();
const clearIndex = options.findIndex(
(opt) => opt.optionId === "clearAndContinue",
);
expect(clearIndex).toBeGreaterThanOrEqual(0);
expect(options[clearIndex]).toMatchObject({
optionId: "clearAndContinue",
kind: "allow_once",
name: "Yes, clear history and continue from plan",
});
expect(options[clearIndex + 1]?.optionId).toBe("reject_with_feedback");
});

it.each([
{
previousMode: "default",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ const CONTINUE_LABELS: Record<string, string> = {
bypassPermissions: "Yes, continue bypassing all permissions",
};

/** Opt-in plan approval: clear planning context, then continue from the plan. */
export const CLEAR_AND_CONTINUE_OPTION_ID = "clearAndContinue";

export function buildExitPlanModePermissionOptions(
previousMode?: string,
): PermissionOption[] {
Expand Down Expand Up @@ -151,6 +154,16 @@ export function buildExitPlanModePermissionOptions(
}
}

options.push({
kind: "allow_once",
name: "Yes, clear history and continue from plan",
optionId: CLEAR_AND_CONTINUE_OPTION_ID,
_meta: {
description:
"Discard planning conversation tokens and start implementation with a fresh context seeded by this plan",
},
});

options.push({
kind: "reject_once",
name: "No, and tell the agent what to do differently",
Expand Down
111 changes: 111 additions & 0 deletions products/desktop/packages/core/src/sessions/planContinuation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import type { PermissionRequest } from "@posthog/shared";
import { describe, expect, it } from "vitest";
import {
buildApprovedPlanContinuationPrompt,
CLEAR_AND_CONTINUE_OPTION_ID,
extractPlanMarkdownFromPermission,
isClearAndContinueOption,
isPlanApprovalAcceptOption,
isPlanApprovalPermission,
resolveClearAndContinueExecutionMode,
shouldContinueFromApprovedPlan,
toApprovedExecutionMode,
} from "./planContinuation";

function makePermission(
overrides: Partial<PermissionRequest> & {
toolCall?: PermissionRequest["toolCall"];
} = {},
): PermissionRequest {
return {
taskRunId: "run-1",
receivedAt: 0,
options: [],
...overrides,
} as PermissionRequest;
}

describe("planContinuation", () => {
it("detects plan approval permissions", () => {
expect(
isPlanApprovalPermission(
makePermission({ toolCall: { kind: "switch_mode" } as never }),
),
).toBe(true);
expect(
isPlanApprovalPermission(
makePermission({ toolCall: { kind: "execute" } as never }),
),
).toBe(false);
});

it("recognizes approve option ids", () => {
expect(isPlanApprovalAcceptOption("auto")).toBe(true);
expect(isPlanApprovalAcceptOption("reject_with_feedback")).toBe(false);
expect(isClearAndContinueOption(CLEAR_AND_CONTINUE_OPTION_ID)).toBe(true);
expect(isClearAndContinueOption("auto")).toBe(false);
});

it("only continues for the explicit clear-and-continue option", () => {
const permission = makePermission({
toolCall: { kind: "switch_mode" } as never,
});
expect(shouldContinueFromApprovedPlan(permission, "auto")).toBe(false);
expect(
shouldContinueFromApprovedPlan(permission, CLEAR_AND_CONTINUE_OPTION_ID),
).toBe(true);
expect(
shouldContinueFromApprovedPlan(permission, "reject_with_feedback"),
).toBe(false);
});

it("extracts trimmed plan markdown from rawInput", () => {
const permission = makePermission({
toolCall: {
kind: "switch_mode",
rawInput: { plan: " ## Steps\n- one " },
} as never,
});
expect(extractPlanMarkdownFromPermission(permission)).toBe(
"## Steps\n- one",
);
expect(
extractPlanMarkdownFromPermission(
makePermission({ toolCall: { kind: "switch_mode" } as never }),
),
).toBeNull();
// A non-string plan must not reach the continuation prompt.
expect(
extractPlanMarkdownFromPermission(
makePermission({
toolCall: { kind: "switch_mode", rawInput: { plan: 42 } } as never,
}),
),
).toBeNull();
});

it("maps approve option to execution mode", () => {
expect(toApprovedExecutionMode("auto")).toBe("auto");
expect(toApprovedExecutionMode("acceptEdits")).toBe("acceptEdits");
});

it("resolves clear-and-continue execution mode from answers", () => {
expect(
resolveClearAndContinueExecutionMode({ executionMode: "acceptEdits" }),
).toBe("acceptEdits");
expect(resolveClearAndContinueExecutionMode({})).toBe("default");
expect(resolveClearAndContinueExecutionMode()).toBe("default");
});

it("builds a continuation prompt that embeds the plan", () => {
const blocks = buildApprovedPlanContinuationPrompt("## Fix\n- patch auth");
expect(blocks).toHaveLength(1);
expect(blocks[0]?.type).toBe("text");
const textBlock = blocks[0];
if (textBlock?.type !== "text") {
throw new Error("expected text block");
}
expect(textBlock.text).toContain("## Fix\n- patch auth");
expect(textBlock.text).toContain("execute this plan directly");
});
});
101 changes: 101 additions & 0 deletions products/desktop/packages/core/src/sessions/planContinuation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import type { ContentBlock } from "@agentclientprotocol/sdk";
import type { ExecutionMode, PermissionRequest } from "@posthog/shared";
import { z } from "zod";

/** Option ids offered when approving ExitPlanMode (see buildExitPlanModePermissionOptions). */
export const PLAN_APPROVAL_ACCEPT_OPTION_IDS = [
"auto",
"default",
"acceptEdits",
"bypassPermissions",
] as const;

export type PlanApprovalAcceptOptionId =
(typeof PLAN_APPROVAL_ACCEPT_OPTION_IDS)[number];

/**
* Opt-in plan-approval option: clear planning context, then continue from the
* approved plan. Kept in sync with `CLEAR_AND_CONTINUE_OPTION_ID` in the Claude
* permission-options module (agent cannot import core).
*/
export const CLEAR_AND_CONTINUE_OPTION_ID = "clearAndContinue";

/** Answers key used by the plan UI to carry the ModeSelector choice. */
export const CLEAR_AND_CONTINUE_EXECUTION_MODE_KEY = "executionMode";

/**
* The adapter intercepts this before the SDK conversion and swaps in a fresh
* SDK session, so it is how core asks for a clear.
*/
export const CLEAR_CONVERSATION_COMMAND = "/clear";

export function isPlanApprovalPermission(
permission: PermissionRequest,
): boolean {
return permission.toolCall?.kind === "switch_mode";
}

export function isPlanApprovalAcceptOption(
optionId: string,
): optionId is PlanApprovalAcceptOptionId {
return (PLAN_APPROVAL_ACCEPT_OPTION_IDS as readonly string[]).includes(
optionId,
);
}

export function isClearAndContinueOption(optionId: string): boolean {
return optionId === CLEAR_AND_CONTINUE_OPTION_ID;
}

/**
* Only the explicit "clear history and continue from plan" option triggers a
* fresh implementation session — normal approve keeps the planning context.
*/
export function shouldContinueFromApprovedPlan(
permission: PermissionRequest,
optionId: string,
): boolean {
return (
isPlanApprovalPermission(permission) && isClearAndContinueOption(optionId)
);
}

/** ExitPlanMode carries the approved plan as markdown on its tool input. */
const planToolInputSchema = z.object({ plan: z.string() });

export function extractPlanMarkdownFromPermission(
permission: PermissionRequest,
): string | null {
const parsed = planToolInputSchema.safeParse(permission.toolCall?.rawInput);
if (!parsed.success) return null;
const trimmed = parsed.data.plan.trim();
return trimmed.length > 0 ? trimmed : null;
}

export function toApprovedExecutionMode(
optionId: PlanApprovalAcceptOptionId,
): ExecutionMode {
return optionId;
}

export function resolveClearAndContinueExecutionMode(
answers?: Record<string, string>,
): ExecutionMode {
const mode = answers?.[CLEAR_AND_CONTINUE_EXECUTION_MODE_KEY];
if (mode && isPlanApprovalAcceptOption(mode)) {
return toApprovedExecutionMode(mode);
}
return "default";
}

export function buildApprovedPlanContinuationPrompt(
planMarkdown: string,
): ContentBlock[] {
const text = [
"The user approved the implementation plan below. Planning is complete — execute this plan directly.",
"Do not re-enter plan mode unless the user asks for a significant change in direction.",
"",
planMarkdown,
].join("\n");
return [{ type: "text", text }];
}
Loading