: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(code): show a recovered plan in the thread, not just the prompt (#80963)
Dylan Martinee0228b0e71d
diff --git a/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.test.ts b/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.test.tsindex 595fa7e11fc6..ca528ecc1688 100644--- a/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.test.ts+++ b/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.test.ts@@ -505,3 +505,39 @@ describe("handleSystemMessage model_refusal_fallback", () => {},);});++describe("tool_use blocks for an already-emitted tool call", () => {+ function toolUseMessage(name: string, input: Record<string, unknown>) {+ return assistantMessage("msg_1", [+ { type: "tool_use", id: "toolu_1", name, input },+ ]);+ }++ it("keeps the permission handler's resolved plan on an ExitPlanMode call", async () => {+ const { context, updates } = createHandlerContext();+ context.emittedToolCalls = new Set(["toolu_1"]);++ await handleUserAssistantMessage(+ toolUseMessage("ExitPlanMode", {}),+ context,+ );++ expect(+ updates.filter((u) => u.update.sessionUpdate === "tool_call_update"),+ ).toEqual([]);+ });++ it("still updates other tools from the streamed input", async () => {+ const { context, updates } = createHandlerContext();+ context.emittedToolCalls = new Set(["toolu_1"]);++ await handleUserAssistantMessage(+ toolUseMessage("Read", { file_path: "/test/a.ts" }),+ context,+ );++ expect(+ updates.filter((u) => u.update.sessionUpdate === "tool_call_update"),+ ).toHaveLength(1);+ });+});diff --git a/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.ts b/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.tsindex 83e998563503..f5ab450245a1 100644--- a/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.ts+++ b/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.ts@@ -273,6 +273,10 @@ function handleToolUseChunk(}if (alreadyEmitted) {+ // Replaying the raw input would overwrite the plan resolved by the permission handler.+ if (chunk.name === "ExitPlanMode") {+ return null;+ }return {_meta: meta,toolCallId: chunk.id,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.tsindex 6bea7c248bcd..ee5564f7682e 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@@ -520,3 +520,67 @@ describe("AskUserQuestion cancelled outcomes", () => {await expect(canUseTool(context)).rejects.toThrow("Tool use aborted");});});++describe("ExitPlanMode plan resolution", () => {+ const PLAN =+ "# Add the CTA\n\nPut a signup button in the hero and point it at /signup.";++ function createPlanContext(emittedToolCalls: Set<string>) {+ return createContext("ExitPlanMode", {+ toolInput: {},+ emittedToolCalls,+ session: {+ permissionMode: "plan",+ lastPlanContent: PLAN,+ notificationHistory: [],+ },+ applySessionMode: vi.fn().mockResolvedValue(undefined),+ client: {+ sessionUpdate: vi.fn().mockResolvedValue(undefined),+ requestPermission: vi.fn().mockResolvedValue({+ outcome: { outcome: "selected", optionId: "default" },+ }),+ },+ });+ }++ function planUpdates(context: Parameters<typeof canUseTool>[0]) {+ return (context.client.sessionUpdate as ReturnType<typeof vi.fn>).mock.calls+ .map(([notification]) => notification.update)+ .filter(+ (update: { rawInput?: { plan?: unknown } }) =>+ update.rawInput?.plan === PLAN,+ );+ }++ it("emits the tool call with a plan recovered from the plan file", async () => {+ const context = createPlanContext(new Set());++ await canUseTool(context);++ expect(planUpdates(context)).toEqual([+ expect.objectContaining({+ sessionUpdate: "tool_call",+ kind: "switch_mode",+ }),+ ]);+ });++ it("backfills the recovered plan onto an already-emitted tool call", async () => {+ const context = createPlanContext(new Set(["test-tool-use-id"]));++ await canUseTool(context);++ expect(planUpdates(context)).toEqual([+ expect.objectContaining({+ sessionUpdate: "tool_call_update",+ toolCallId: "test-tool-use-id",+ content: expect.arrayContaining([+ expect.objectContaining({+ content: expect.objectContaining({ text: PLAN }),+ }),+ ]),+ }),+ ]);+ });+});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.tsindex 928074dd039c..c6aad314abbb 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@@ -2,6 +2,7 @@ import type {AgentSideConnection,RequestPermissionRequest,RequestPermissionResponse,+ ToolCallContent,} from "@agentclientprotocol/sdk";import type {PermissionRuleValue,@@ -231,6 +232,29 @@ async function validatePlanContent(return { valid: true };}+async function publishResolvedPlan(+ context: ToolHandlerContext,+ updatedInput: Record<string, unknown>,+ toolInfo: { content?: ToolCallContent[] },+): Promise<void> {+ if (+ updatedInput === context.toolInput ||+ !context.emittedToolCalls?.has(context.toolUseID)+ ) {+ return;+ }++ await context.client.sessionUpdate({+ sessionId: context.sessionId,+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: context.toolUseID,+ rawInput: updatedInput,+ content: toolInfo.content,+ },+ });+}+async function requestPlanApproval(context: ToolHandlerContext,updatedInput: Record<string, unknown>,@@ -242,7 +266,11 @@ async function requestPlanApproval(input: updatedInput,});- return await requestPermissionFromClient(context, {+ await publishResolvedPlan(context, updatedInput, toolInfo);++ const resolvedPlanContext = { ...context, toolInput: updatedInput };++ return await requestPermissionFromClient(resolvedPlanContext, {options: buildExitPlanModePermissionOptions(session.modeBeforePlan),sessionId,toolCall: {diff --git a/products/desktop/packages/ui/src/features/sessions/components/new-thread/buildThreadGroups.test.ts b/products/desktop/packages/ui/src/features/sessions/components/new-thread/buildThreadGroups.test.tsindex 50a9affd5d2e..d542bd7ad6b9 100644--- a/products/desktop/packages/ui/src/features/sessions/components/new-thread/buildThreadGroups.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/new-thread/buildThreadGroups.test.ts@@ -96,3 +96,35 @@ describe("buildThreadGroups MCP detection", () => {expect(row.summary.doneLabel).toBe("1 subagent, 2 tool calls");});});++describe("buildThreadGroups plan detection", () => {+ // The plan tool call is emitted from the model's raw input, and its plan text+ // and switch_mode kind are backfilled by the permission handler. Grouping by+ // kind alone folds an ExitPlanMode call into the collapsed tool group before+ // its kind resolves — burying the plan the user is meant to read. Matching by+ // tool name keeps it as its own row regardless of when the kind arrives.+ it.each([+ ["switch_mode kind", { kind: "switch_mode" }, undefined],+ [+ "ExitPlanMode name, kind not yet resolved",+ { kind: "other" },+ { claudeCode: { toolName: "ExitPlanMode" } },+ ],+ ])(+ "keeps a plan tool call (%s) as its own row, not folded into a group",+ (_label, overrides, meta) => {+ const write = toolCallItem(+ "write",+ { claudeCode: { toolName: "Write" } },+ { kind: "edit" },+ );+ const plan = toolCallItem("plan", meta, overrides);++ expect(isGroupableItem(plan)).toBe(false);++ const grouping = buildThreadGroups([write, plan], {});+ expect(grouping.rows.map((r) => r.kind)).toEqual(["tool_group", "item"]);+ expect(grouping.idToRowIndex.get("plan")).toBe(1);+ },+ );+});diff --git a/products/desktop/packages/ui/src/features/sessions/components/new-thread/buildThreadGroups.ts b/products/desktop/packages/ui/src/features/sessions/components/new-thread/buildThreadGroups.tsindex 1ab8dbb544d5..6b750577fb9b 100644--- a/products/desktop/packages/ui/src/features/sessions/components/new-thread/buildThreadGroups.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/new-thread/buildThreadGroups.ts@@ -11,6 +11,7 @@ import {MCP_ICON,SUBAGENT_ICON,} from "@posthog/ui/features/sessions/components/new-thread/conversationThreadConfig";+import { isPlanApprovalTool } from "@posthog/ui/features/sessions/components/session-update/collaborationTools";export interface GroupIconEntry {Icon: Icon;@@ -96,13 +97,14 @@ function isDirectMessageItem(item: ConversationItem): boolean {/*** A plan presented for approval (the ExitPlanMode / switch_mode tool call,- * rendered by PlanApprovalView). Never folded — a plan is meant to be read.+ * rendered by PlanApprovalView). Keep it visible so the user can read it.*/function isPlanItem(item: ConversationItem): boolean {return (item.type === "session_update" &&item.update.sessionUpdate === "tool_call" &&- item.update.kind === "switch_mode"+ (item.update.kind === "switch_mode" ||+ isPlanApprovalTool(readAgentToolName(item.update._meta))));}diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallBlock.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallBlock.tsxindex a602acf31bb9..56a4463b3749 100644--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallBlock.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/ToolCallBlock.tsx@@ -16,7 +16,7 @@ import type { ToolCall } from "@posthog/ui/features/sessions/types";import { Box } from "@radix-ui/themes";import type { ConversationItem, TurnContext } from "../buildConversationItems";import { useChatThreadChrome } from "../chat-thread/chatThreadChrome";-import { isSubagentSpawnTool } from "./collaborationTools";+import { isPlanApprovalTool, isSubagentSpawnTool } from "./collaborationTools";import {MCP_TOOL_BLOCK_COMPONENT,type McpToolBlockComponent,@@ -79,6 +79,14 @@ export function ToolCallBlock({);}+ if (isPlanApprovalTool(toolName)) {+ return (+ <Box>+ <PlanApprovalView {...props} />+ </Box>+ );+ }+const content = (() => {switch (toolCall.kind) {case "switch_mode":diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/collaborationTools.ts b/products/desktop/packages/ui/src/features/sessions/components/session-update/collaborationTools.tsindex d482aeaa0fc7..897003beee15 100644--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/collaborationTools.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/collaborationTools.ts@@ -7,3 +7,9 @@ export const SUBAGENT_SPAWN_TOOL_NAMES = new Set<string>([export function isSubagentSpawnTool(toolName: string | undefined): boolean {return SUBAGENT_SPAWN_TOOL_NAMES.has(toolName ?? "");}++export const PLAN_APPROVAL_TOOL_NAMES = new Set<string>(["ExitPlanMode"]);++export function isPlanApprovalTool(toolName: string | undefined): boolean {+ return PLAN_APPROVAL_TOOL_NAMES.has(toolName ?? "");+}