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(desktop): fold plans from permission requests into the transcript tool call (#86176)

Thomas Obermüllerda35956c48ae
diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts
index 3261a4a16c3b..2e728e01d5cb 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts
@@ -1198,3 +1198,143 @@ function findProgressGroups(items: ConversationItem[]): ProgressGroupUpdate[] {
}
return groups;
}
+
+describe("plan recovered from a permission request", () => {
+ // A sandbox agent that recovers the plan from a plan file sends the
+ // ExitPlanMode tool_call plan-less; the plan travels only inside the
+ // permission request, which persists in the run log.
+ const PLAN = "# Dummy plan\n\n1. Open `dummy.ts`.\n2. Add a log line.";
+
+ const exitPlanModeMsg = (
+ ts: number,
+ rawInput: Record<string, unknown> = {},
+ ): AcpMessage => ({
+ type: "acp_message",
+ ts,
+ message: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ update: {
+ sessionUpdate: "tool_call",
+ toolCallId: "toolu_plan",
+ title: "Ready to code?",
+ kind: "switch_mode",
+ status: "pending",
+ rawInput,
+ content: [],
+ _meta: { claudeCode: { toolName: "ExitPlanMode" } },
+ },
+ },
+ },
+ });
+
+ const permissionRequestMsg = (ts: number, plan: string): AcpMessage => ({
+ type: "acp_message",
+ ts,
+ message: {
+ jsonrpc: "2.0",
+ method: "_posthog/permission_request",
+ params: {
+ requestId: "req-plan",
+ toolCallId: "toolu_plan",
+ options: [
+ { optionId: "default", name: "Yes, continue", kind: "allow_once" },
+ ],
+ toolCall: {
+ toolCallId: "toolu_plan",
+ kind: "switch_mode",
+ title: "Ready to code?",
+ content: [{ type: "content", content: { type: "text", text: plan } }],
+ rawInput: {
+ plan,
+ planFilePath: "/root/.claude/plans/plan.md",
+ toolName: "ExitPlanMode",
+ },
+ },
+ },
+ },
+ });
+
+ const resolvingUpdateMsg = (ts: number): AcpMessage => ({
+ type: "acp_message",
+ ts,
+ message: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ update: {
+ sessionUpdate: "tool_call_update",
+ toolCallId: "toolu_plan",
+ rawInput: {},
+ status: "completed",
+ },
+ },
+ },
+ });
+
+ function planToolCallOf(items: ConversationItem[]) {
+ const item = items.find(
+ (i) =>
+ i.type === "session_update" && i.update.sessionUpdate === "tool_call",
+ );
+ return (item?.type === "session_update" ? item.update : undefined) as
+ | { rawInput?: { plan?: string }; status?: string }
+ | undefined;
+ }
+
+ it("folds the plan from a logged permission_request into the plan-less tool call", () => {
+ const { items } = buildConversationItems(
+ [
+ userPromptMsg(1, 1, "plan something"),
+ exitPlanModeMsg(2),
+ permissionRequestMsg(3, PLAN),
+ ],
+ true,
+ );
+
+ expect(planToolCallOf(items)?.rawInput?.plan).toBe(PLAN);
+ });
+
+ it("keeps the recovered plan across the resolving plan-less tool_call_update", () => {
+ const { items } = buildConversationItems(
+ [
+ userPromptMsg(1, 1, "plan something"),
+ exitPlanModeMsg(2),
+ permissionRequestMsg(3, PLAN),
+ resolvingUpdateMsg(4),
+ ],
+ true,
+ );
+
+ const toolCall = planToolCallOf(items);
+ expect(toolCall?.status).toBe("completed");
+ expect(toolCall?.rawInput?.plan).toBe(PLAN);
+ });
+
+ it("applies a plan whose permission frame arrives before the tool_call", () => {
+ const { items } = buildConversationItems(
+ [
+ userPromptMsg(1, 1, "plan something"),
+ permissionRequestMsg(2, PLAN),
+ exitPlanModeMsg(3),
+ ],
+ true,
+ );
+
+ expect(planToolCallOf(items)?.rawInput?.plan).toBe(PLAN);
+ });
+
+ it("never overrides an inline plan", () => {
+ const { items } = buildConversationItems(
+ [
+ userPromptMsg(1, 1, "plan something"),
+ exitPlanModeMsg(2, { plan: "inline plan" }),
+ permissionRequestMsg(3, PLAN),
+ ],
+ true,
+ );
+
+ expect(planToolCallOf(items)?.rawInput?.plan).toBe("inline plan");
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
index 678dfff780e0..fa7195031258 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
@@ -157,6 +157,12 @@ export interface ItemBuilder {
/** Runs that emitted `_posthog/run_started`; until then the setup card's
* "agent" step stays in_progress rather than completing at HTTP-boot time. */
runStartedRunIds: Set<string>;
+ /** Plans recovered from `_posthog/permission_request` frames, keyed by
+ * toolCallId. A sandbox agent that read the plan from a plan file sends the
+ * ExitPlanMode tool_call plan-less — the plan travels only inside the
+ * permission request — and the resolving tool_call_update replays the raw
+ * plan-less input, so the plan is re-applied after every merge. */
+ recoveredPlans: Map<string, string>;
}
export function createItemBuilder(): ItemBuilder {
@@ -174,6 +180,7 @@ export function createItemBuilder(): ItemBuilder {
lastActivityAt: null,
isBackgroundTurnActive: false,
runStartedRunIds: new Set(),
+ recoveredPlans: new Map(),
};
}
@@ -187,6 +194,36 @@ function noteActivity(b: ItemBuilder, ts: number) {
const TERMINAL_TOOL_STATUSES = new Set(["completed", "failed", "cancelled"]);
+/** The plan markdown carried by an ExitPlanMode-shaped input, or undefined. */
+function recoveredPlanOf(rawInput: unknown): string | undefined {
+ const plan = (rawInput as { plan?: unknown } | null | undefined)?.plan;
+ return typeof plan === "string" && plan.trim() ? plan : undefined;
+}
+
+function toolCallCarriesPlan(toolCall: ToolCall): boolean {
+ if (recoveredPlanOf(toolCall.rawInput)) return true;
+ return (toolCall.content ?? []).some((item) => {
+ const record = item as {
+ content?: { type?: string; text?: string };
+ } | null;
+ return record?.content?.type === "text" && !!record.content.text?.trim();
+ });
+}
+
+/** Fold a recovered plan into `toolCallId`'s call unless it already carries
+ * one (an inline plan always wins). Mutates the registered ToolCall, so an
+ * already-pushed item reflects it. */
+function applyRecoveredPlan(b: ItemBuilder, toolCallId: string): void {
+ const plan = b.recoveredPlans.get(toolCallId);
+ if (!plan) return;
+ const toolCall = b.currentTurn?.toolCalls.get(toolCallId);
+ if (!toolCall || toolCallCarriesPlan(toolCall)) return;
+ toolCall.rawInput = {
+ ...(toolCall.rawInput as Record<string, unknown> | null | undefined),
+ plan,
+ };
+}
+
function isTerminalToolStatus(status: string | null | undefined): boolean {
return status != null && TERMINAL_TOOL_STATUSES.has(status);
}
@@ -692,6 +729,27 @@ function handleNotification(
// products are surfaced as a persistent, de-duplicated bar above the composer
// (see accumulateSessionResources / SessionResourcesBar).
+ if (isNotification(msg.method, POSTHOG_NOTIFICATIONS.PERMISSION_REQUEST)) {
+ // Permission frames persist in the run log, so recovering the plan here
+ // also covers reloads and historical replays — unlike the pending
+ // permission in the session store, which is dropped once answered.
+ const toolCall = (
+ msg.params as
+ | { toolCall?: { toolCallId?: unknown; rawInput?: unknown } }
+ | undefined
+ )?.toolCall;
+ const plan = recoveredPlanOf(toolCall?.rawInput);
+ if (
+ typeof toolCall?.toolCallId === "string" &&
+ toolCall.toolCallId &&
+ plan
+ ) {
+ b.recoveredPlans.set(toolCall.toolCallId, plan);
+ applyRecoveredPlan(b, toolCall.toolCallId);
+ }
+ return;
+ }
+
if (
isNotification(msg.method, POSTHOG_NOTIFICATIONS.BACKGROUND_TURN_STARTED)
) {
@@ -1150,6 +1208,7 @@ function processSessionUpdate(
pushItem(b, toolCall, ts);
}
}
+ applyRecoveredPlan(b, update.toolCallId);
break;
}
@@ -1164,6 +1223,7 @@ function processSessionUpdate(
if (!wasTerminal && isTerminalToolStatus(existing.status)) {
b.completedToolCallCount++;
}
+ applyRecoveredPlan(b, update.toolCallId);
}
break;
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
index 12c879066f59..57cfb0a1d7d6 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
@@ -95,6 +95,7 @@ import { GitActionMessage } from "@posthog/ui/features/sessions/components/GitAc
import { GitActionResult } from "@posthog/ui/features/sessions/components/GitActionResult";
import { isUserInitiatedConversationItem } from "@posthog/ui/features/sessions/components/isUserInitiatedConversationItem";
import { mergeConversationItems } from "@posthog/ui/features/sessions/components/mergeConversationItems";
+import { isPlanItem } from "@posthog/ui/features/sessions/components/new-thread/buildThreadGroups";
import { extractCanvasInstructions } from "@posthog/ui/features/sessions/components/session-update/canvasInstructions";
import { extractChannelContext } from "@posthog/ui/features/sessions/components/session-update/channelContext";
import { extractCustomInstructions } from "@posthog/ui/features/sessions/components/session-update/customInstructions";
@@ -245,7 +246,7 @@ function stableRunItems(run: SessionUpdateItem[]): SessionUpdateItem[] {
return run;
}
-function groupToolRuns(items: ConversationItem[]): ThreadItem[] {
+export function groupToolRuns(items: ConversationItem[]): ThreadItem[] {
const out: ThreadItem[] = [];
// The buffer holds the active run in order: tools, the thoughts between them, and any invisible
// items interleaved with either.
@@ -269,6 +270,14 @@ function groupToolRuns(items: ConversationItem[]): ThreadItem[] {
for (const item of items) {
if (isToolCallItem(item)) {
+ // A plan presented for approval renders as the full PlanApprovalView
+ // card — folded into a "N tool calls" chip, the plan the user is being
+ // asked to approve is invisible. Same exemption as buildThreadGroups.
+ if (isPlanItem(item)) {
+ flush();
+ out.push(item);
+ continue;
+ }
buffer.push(item);
toolCount++;
} else if (isInvisibleItem(item) || isThoughtItem(item)) {
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts
new file mode 100644
index 000000000000..342682dbc215
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts
@@ -0,0 +1,79 @@
+import type { ConversationItem } from "@posthog/ui/features/sessions/components/buildConversationItems";
+import { describe, expect, it } from "vitest";
+import { groupToolRuns } from "./ChatThread";
+
+type SessionUpdateItem = Extract<ConversationItem, { type: "session_update" }>;
+
+function toolItem(
+ id: string,
+ update: Record<string, unknown> = {},
+): SessionUpdateItem {
+ return {
+ type: "session_update",
+ id,
+ update: {
+ sessionUpdate: "tool_call",
+ toolCallId: id,
+ title: id,
+ kind: "execute",
+ status: "completed",
+ ...update,
+ },
+ turnContext: {
+ toolCalls: new Map(),
+ childItems: new Map(),
+ turnCancelled: false,
+ turnComplete: true,
+ },
+ } as SessionUpdateItem;
+}
+
+const planItem = (id: string, update: Record<string, unknown> = {}) =>
+ toolItem(id, { kind: "switch_mode", title: "Ready to code?", ...update });
+
+describe("groupToolRuns", () => {
+ it("collapses a plain run of tools into one chip", () => {
+ const out = groupToolRuns([toolItem("t1"), toolItem("t2")]);
+ expect(out.map((r) => r.type)).toEqual(["tool_group"]);
+ });
+
+ it("keeps a plan approval out of the chip so the plan card renders", () => {
+ // The reproducing shape: the agent edits the plan file, then calls
+ // ExitPlanMode — grouped, the plan the user must approve is invisible.
+ const out = groupToolRuns([toolItem("edit"), planItem("plan")]);
+ expect(out.map((r) => r.type)).toEqual([
+ "session_update",
+ "session_update",
+ ]);
+ expect(out[1]).toMatchObject({ id: "plan" });
+ });
+
+ it("breaks a longer run around the plan", () => {
+ const out = groupToolRuns([
+ toolItem("t1"),
+ toolItem("t2"),
+ planItem("plan"),
+ toolItem("t3"),
+ ]);
+ expect(out.map((r) => r.type)).toEqual([
+ "tool_group",
+ "session_update",
+ "session_update",
+ ]);
+ expect(out[1]).toMatchObject({ id: "plan" });
+ });
+
+ it("exempts a plan identified only by its agent tool name", () => {
+ const out = groupToolRuns([
+ toolItem("edit"),
+ planItem("plan", {
+ kind: "other",
+ _meta: { claudeCode: { toolName: "ExitPlanMode" } },
+ }),
+ ]);
+ expect(out.map((r) => r.type)).toEqual([
+ "session_update",
+ "session_update",
+ ]);
+ });
+});
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.ts
index 2b5fc9215907..cf3e3a540f05 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
@@ -101,7 +101,7 @@ function isDirectMessageItem(item: ConversationItem): boolean {
* A plan presented for approval (the ExitPlanMode / switch_mode tool call,
* rendered by PlanApprovalView). Keep it visible so the user can read it.
*/
-function isPlanItem(item: ConversationItem): boolean {
+export function isPlanItem(item: ConversationItem): boolean {
return (
item.type === "session_update" &&
item.update.sessionUpdate === "tool_call" &&
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/PlanApprovalView.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/PlanApprovalView.test.tsx
index 3bd1add8e865..c54f5ad85369 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/PlanApprovalView.test.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/PlanApprovalView.test.tsx
@@ -148,4 +148,32 @@ describe("PlanApprovalView", () => {
screen.queryByRole("button", { name: /show plan/i }),
).not.toBeInTheDocument();
});
+
+ it("prefers rawInput.plan over denial text in content once resolved", async () => {
+ const user = userEvent.setup();
+ // A denial's tool_call_update replaces `content` with the refusal message;
+ // the plan survives only on rawInput.
+ renderView({
+ toolCall: makeToolCall({
+ status: "failed",
+ rawInput: { plan: PLAN_MARKER },
+ content: [
+ {
+ type: "content",
+ content: {
+ type: "text",
+ text: "User rejected the plan with feedback: stopping.",
+ },
+ },
+ ],
+ }),
+ });
+
+ await user.click(screen.getByRole("button", { name: /show plan/i }));
+
+ expect(screen.getByText(PLAN_MARKER)).toBeInTheDocument();
+ expect(
+ screen.queryByText(/user rejected the plan/i),
+ ).not.toBeInTheDocument();
+ });
});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/PlanApprovalView.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/PlanApprovalView.tsx
index bf609d89d27a..e3566a8c4501 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/PlanApprovalView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/PlanApprovalView.tsx
@@ -33,10 +33,17 @@ export function PlanApprovalView({
| undefined;
const isHistoricalPlan = rawInput?.historical === true;
- const planText = useMemo(
- () => extractPlanText({ rawInput, content }),
- [content, rawInput],
- );
+ const planText = useMemo(() => {
+ // Once resolved, the update stream may have replaced `content` with the
+ // outcome message (a denial's refusal text) — the typed rawInput.plan is
+ // then the only faithful copy, so it wins. While streaming, content stays
+ // authoritative over a possibly partial rawInput snapshot.
+ const resolved = isHistoricalPlan || isComplete || isFailed || wasCancelled;
+ return resolved
+ ? (extractPlanText({ rawInput, content: [] }) ??
+ extractPlanText({ rawInput, content }))
+ : extractPlanText({ rawInput, content });
+ }, [content, rawInput, isHistoricalPlan, isComplete, isFailed, wasCancelled]);
const wasNotApproved = isFailed || wasCancelled;
const showResult = isHistoricalPlan || isComplete || wasNotApproved;