: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(desktop): land new tasks directly on their chat (#94261)
Shy Alter2c585218d0ae
diff --git a/products/desktop/docs/ARCHITECTURE.md b/products/desktop/docs/ARCHITECTURE.mdindex f2d9f4b4ae4b..6681393b9696 100644--- a/products/desktop/docs/ARCHITECTURE.md+++ b/products/desktop/docs/ARCHITECTURE.md@@ -34,6 +34,24 @@ Two tRPC surfaces exist:- `@posthog/host-router`: Electron main process API for its renderer.- `@posthog/workspace-server`: privileged Node backend API consumed by `@posthog/workspace-client`.+## New task startup++Submitting a task keeps the composer busy until creation opens the task's chat.+The chat displays the submitted prompt with the current startup status until+initialization ends and the transcript or error state takes over. The waiting+message and composer use the same outer gutters and column width as the live chat.++New cloud runs seed the full user message before subscribing to setup progress.+The chat renders that message immediately, including its space context chip.+Reopened transcripts reconcile the plain initial prompt with its context-bearing+echo before rendering, so the same submission appears only once.++Cloud creation can succeed while the run is still queued. The pending prompt+remains available to the chat after that success; `SessionView` clears it when+initialization ends. Successful submissions are marked as submitted so startup+recovery does not reopen them as unsent drafts. Failed creation retains the prompt+for recovery into the originating composer.+## Dependency InjectionUse plain Inversify through `@posthog/di`.diff --git a/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.ts b/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.tsindex ed8400bc2dbf..41264cb6aeb7 100644--- a/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.ts+++ b/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.ts@@ -93,7 +93,7 @@ function snapshotUpdate(};}-function createHarness(isTaskAuthor = true) {+function createHarness(isTaskAuthor = true, initialPrompt?: string) {const sessions: Record<string, AgentSession> = {};const store = {getSessions: () => sessions,@@ -135,7 +135,19 @@ function createHarness(isTaskAuthor = true) {if (session) session.pendingPermissions = permissions;},clearTailOptimisticItems: vi.fn(),- appendOptimisticItem: vi.fn(),+ appendOptimisticItem: vi.fn(+ (+ taskRunId: string,+ item: Parameters<+ SessionServiceDeps["store"]["appendOptimisticItem"]+ >[1],+ ) => {+ sessions[taskRunId].optimisticItems.push({+ ...item,+ id: "optimistic-test",+ });+ },+ ),replaceOptimisticWithEvent: vi.fn(),clearMessageQueue: vi.fn(),};@@ -220,12 +232,14 @@ function createHarness(isTaskAuthor = true) {} as unknown as SessionServiceDeps;const service = new SessionService(deps);+ if (initialPrompt) service.rememberInitialCloudPrompt(TASK_ID, initialPrompt);service.watchCloudTask(TASK_ID, RUN_ID, "https://us.posthog.com", 1);if (!onUpdate) throw new Error("watchCloudTask did not subscribe");const session = sessions[RUN_ID];if (session) session.isTaskAuthor = isTaskAuthor;return {+ session,sendUpdate: (update: CloudTaskUpdatePayload) => onUpdate?.(update),notifyPromptComplete,notifyPermissionRequest,@@ -235,6 +249,43 @@ function createHarness(isTaskAuthor = true) {}describe("cloud task update notifications", () => {+ it.each([+ "Check the build",+ 'Check the build\n\n<channel_context channel="example">Project notes.</channel_context>',+ ])("seeds a new run's prompt before any setup logs arrive: %s", (prompt) => {+ const harness = createHarness(true, prompt);++ expect(harness.session.events).toEqual([]);+ expect(harness.session.optimisticItems).toEqual([+ expect.objectContaining({ content: prompt, pinToTop: true }),+ ]);+ harness.sendUpdate(+ logsUpdate(+ [+ {+ type: "notification",+ notification: {+ method: "_posthog/progress",+ params: {+ step: "sandbox",+ status: "running",+ label: "Setting up sandbox",+ },+ },+ },+ ],+ 1,+ ),+ );+ expect(harness.session.optimisticItems).toEqual([+ expect.objectContaining({ content: prompt, pinToTop: true }),+ ]);+ });++ it("does not seed a reopened run before its history is known", () => {+ expect(createHarness().session.optimisticItems).toEqual([]);+ });+it("does not notify a non-owner watching the task", () => {const harness = createHarness(false);diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.tsindex 5e0994e1e86e..702368e23591 100644--- a/products/desktop/packages/core/src/sessions/sessionService.ts+++ b/products/desktop/packages/core/src/sessions/sessionService.ts@@ -6652,10 +6652,21 @@ export class SessionService {existing?.taskRunId === taskRunId ? existing.adapter : persistedAdapter,);this.d.store.setSession(session);- // Optimistic seeding for the initial task description is deferred- // until `hydrateCloudTaskSessionFromLogs` confirms there's no prior- // conversation. Otherwise reopening a task with history would flash- // the description at top until hydration replaced it.+ // Creation supplies the exact prompt before setup logs can arrive.+ // Reopened tasks have no creation seed and must await transcript hydration.+ const initialPrompt = this.initialCloudOptimisticPrompt.get(taskId);+ if (+ initialPrompt &&+ !isTerminalStatus(runStatus) &&+ !runState?.resume_from_run_id+ ) {+ this.d.store.appendOptimisticItem(taskRunId, {+ type: "user_message",+ content: initialPrompt,+ timestamp: Date.now(),+ pinToTop: true,+ });+ }} else {// Ensure cloud flag and configOptions are set on existing sessionsconst updates: Partial<AgentSession> = {};diff --git a/products/desktop/packages/core/src/sessions/sessionViewState.test.ts b/products/desktop/packages/core/src/sessions/sessionViewState.test.tsindex c40b0d91d858..626679b47afe 100644--- a/products/desktop/packages/core/src/sessions/sessionViewState.test.ts+++ b/products/desktop/packages/core/src/sessions/sessionViewState.test.ts@@ -46,6 +46,24 @@ function makeSession(}describe("deriveSessionViewState", () => {+ it("opens the live cloud chat as soon as the initial prompt is seeded", () => {+ const session = makeSession("queued");+ session.optimisticItems = [+ {+ id: "initial-prompt",+ type: "user_message",+ content: "Check the build",+ timestamp: 1,+ pinToTop: true,+ },+ ];++ expect(+ deriveSessionViewState(session, makeTask("queued"), null, true)+ .isInitializing,+ ).toBe(false);+ });+it("uses a live cloud session when task run metadata is unavailable", () => {const task = makeTask("in_progress");task.latest_run = undefined;diff --git a/products/desktop/packages/core/src/sessions/sessionViewState.ts b/products/desktop/packages/core/src/sessions/sessionViewState.tsindex 6fcff5d11c87..b68a51122f46 100644--- a/products/desktop/packages/core/src/sessions/sessionViewState.ts+++ b/products/desktop/packages/core/src/sessions/sessionViewState.ts@@ -48,6 +48,9 @@ export function deriveSessionViewState(const isNewSessionWithInitialPrompt =!task.latest_run?.id && !!task.description;const isResumingExistingSession = !!task.latest_run?.id;+ const hasOptimisticPrompt = session?.optimisticItems.some(+ (item) => item.type === "user_message",+ );const isHydratingEmptyTranscript =effectiveIsCloud &&events.length === 0 &&@@ -55,7 +58,10 @@ export function deriveSessionViewState(const isInitializing = effectiveIsCloud? isHydratingEmptyTranscript ||(!hasError &&- (!session || (events.length === 0 && isCloudRunNotTerminal)))+ (!session ||+ (events.length === 0 &&+ !hasOptimisticPrompt &&+ isCloudRunNotTerminal))): !session ||(session.status === "connecting" && events.length === 0) ||(session.status === "connected" &&diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.tsindex 49b10f6c08c5..55c841800082 100644--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts@@ -45,7 +45,6 @@ interface WarmActivationPayload {pendingUserMessage?: string;pendingUserArtifactIds?: string[];suppressWarmReuse: boolean;- augmented: boolean;}// The local connect path appends channel CONTEXT.md to initialPrompt and gets@@ -57,7 +56,7 @@ interface WarmActivationPayload {function buildCloudFirstMessage(messageText: string | undefined,input: TaskCreationInput,-): { pendingUserMessage?: string; augmented: boolean } {+): string | undefined {const customInstructionsText = messageText? buildCustomInstructionsText(input.customInstructions): null;@@ -67,14 +66,11 @@ function buildCloudFirstMessage(input.channelContextId,input.channelContextPath,);- const pendingUserMessage =+ return ([messageText, customInstructionsText, channelContextText].filter((part): part is string => !!part)- .join("\n\n") || undefined;- return {- pendingUserMessage,- augmented: !!(customInstructionsText || channelContextText),- };+ .join("\n\n") || undefined+ );}export class TaskCreationSaga extends Saga<@@ -313,7 +309,7 @@ export class TaskCreationSaga extends Saga<// Warm-activated at create time: the backend already forwarded the first// message (with any uploaded artifacts) to the pre-warmed run.if (!taskId && warmPayload && task.latest_run) {- if (warmPayload.augmented && warmPayload.pendingUserMessage) {+ if (warmPayload.pendingUserMessage) {this.deps.sessionService.rememberInitialCloudPrompt(task.id,warmPayload.pendingUserMessage,@@ -407,15 +403,15 @@ export class TaskCreationSaga extends Saga<? warmPayload.transport: await buildTransport();- const { pendingUserMessage, augmented } = warmPayload- ? warmPayload+ const pendingUserMessage = warmPayload+ ? warmPayload.pendingUserMessage: buildCloudFirstMessage(transport?.messageText, input);// The sandbox echoes pendingUserMessage back once it boots; until then// the optimistic placeholder would show the bare task description with// no CONTEXT.md / personalization chip. Hand the augmented message to// the session service so it seeds the placeholder right away.- if (!isPiRuntime && augmented && pendingUserMessage) {+ if (!isPiRuntime && pendingUserMessage) {this.deps.sessionService.rememberInitialCloudPrompt(task.id,pendingUserMessage,@@ -765,7 +761,7 @@ export class TaskCreationSaga extends Saga<resolvedContent,input.filePaths,);- const { pendingUserMessage, augmented } = buildCloudFirstMessage(+ const pendingUserMessage = buildCloudFirstMessage(transport.messageText,input,);@@ -773,7 +769,6 @@ export class TaskCreationSaga extends Saga<transport,pendingUserMessage,suppressWarmReuse: false,- augmented,};const lease =diff --git a/products/desktop/packages/core/src/tasks/pendingPrompts.test.ts b/products/desktop/packages/core/src/tasks/pendingPrompts.test.tsindex d2b3a40ae44b..9d33c3a9f93c 100644--- a/products/desktop/packages/core/src/tasks/pendingPrompts.test.ts+++ b/products/desktop/packages/core/src/tasks/pendingPrompts.test.ts@@ -3,6 +3,7 @@ import {buildPendingPromptKey,capPendingPrompts,listPendingPromptsNewestFirst,+ pendingPromptRecordFromContent,pendingPromptToContent,} from "./pendingPrompts";@@ -54,3 +55,24 @@ describe("pendingPromptToContent", () => {});});});++describe("pendingPromptRecordFromContent", () => {+ it("captures plain text, serialized chips, and attachments from the typed content", () => {+ const record = pendingPromptRecordFromContent({+ segments: [+ { type: "text", text: "fix " },+ {+ type: "chip",+ chip: { type: "file", id: "src/a.ts", label: "src/a.ts" },+ },+ ],+ attachments: [{ id: "notes.txt", label: "notes.txt" }],+ });++ expect(record.promptText).toBe("fix @src/a.ts");+ expect(record.contentXml).toContain('<file path="src/a.ts" />');+ expect(record.attachments).toEqual([+ { id: "notes.txt", label: "notes.txt" },+ ]);+ });+});diff --git a/products/desktop/packages/core/src/tasks/pendingPrompts.ts b/products/desktop/packages/core/src/tasks/pendingPrompts.tsindex fc9c34a6350c..4c7e3a4f047f 100644--- a/products/desktop/packages/core/src/tasks/pendingPrompts.ts+++ b/products/desktop/packages/core/src/tasks/pendingPrompts.ts@@ -1,4 +1,6 @@import {+ contentToPlainText,+ contentToXml,type EditorContent,textToContent,xmlToContent,@@ -6,9 +8,6 @@ import {const MAX_RECOVERABLE_PROMPTS = 20;-/** Why a submitted prompt never reached a running task. */-export type PendingPromptInterruptReason = "offline" | "failed";-/** The fields a recovered prompt restores its composer content from. */export interface RecoverablePromptContent {/** Serialized editor content (chips + attachments), preferred on restore. */@@ -29,6 +28,29 @@ export function pendingPromptToContent(return xml ? xmlToContent(xml) : textToContent(record.promptText);}+/**+ * Capture the durable record fields for a submit, from the composer content+ * the person typed. Wrappers that transform the content for the task request+ * (the autoresearch kickoff prepends a protocol preamble) must derive the+ * record from the original content: recovery restores what the person typed,+ * and a preamble that survives into the composer gets prepended a second time+ * on resubmit.+ */+export function pendingPromptRecordFromContent(content: EditorContent): {+ promptText: string;+ contentXml: string;+ attachments: { id: string; label: string }[];+} {+ return {+ promptText: contentToPlainText(content).trim(),+ contentXml: contentToXml(content).trim(),+ attachments: (content.attachments ?? []).map((attachment) => ({+ id: attachment.id,+ label: attachment.label,+ })),+ };+}+export interface TimestampedPendingPrompt {createdAt: number;}diff --git a/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts b/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.tsindex 221116e22ae3..b56af693b54d 100644--- a/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts+++ b/products/desktop/packages/ui/src/features/browser-tabs/imperativeTabNavigation.ts@@ -17,6 +17,15 @@ export function getCurrentBrowserTabId(): string | null {return getRouterOrNull()?.history.location.state.tabId ?? null;}+/**+ * Whether the tab still exists in the mirror. A null tabId means tabs are off,+ * so there is one window whose composer cannot have been closed with the tab.+ */+export function isBrowserTabOpen(tabId: string | null): boolean {+ if (!tabId) return true;+ return readMirror().tabs.some((candidate) => candidate.id === tabId);+}+/*** Move one browser tab to a new route without stealing focus from another tab.* Active tabs use router history; background tabs update their durable targetdiff --git a/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.test.tsxnew file mode 100644index 000000000000..3c781b74af97--- /dev/null+++ b/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.test.tsx@@ -0,0 +1,126 @@+import { Theme } from "@radix-ui/themes";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { PendingChatView } from "./PendingChatView";++class ResizeObserverCapture {+ static instances: ResizeObserverCallback[] = [];++ constructor(callback: ResizeObserverCallback) {+ ResizeObserverCapture.instances.push(callback);+ }++ observe() {}+ unobserve() {}+ disconnect() {}+}++function measure(element: HTMLElement, overflow: boolean): void {+ Object.defineProperty(element, "scrollHeight", {+ configurable: true,+ value: overflow ? 500 : 100,+ });+ Object.defineProperty(element, "clientHeight", {+ configurable: true,+ value: 100,+ });+ for (const callback of ResizeObserverCapture.instances) {+ callback([], {} as ResizeObserver);+ }+}++function renderPending(+ props: {+ content?: string;+ attachments?: { id: string; label: string }[];+ statusText?: string;+ } = {},+) {+ render(+ <Theme>+ <PendingChatView+ content={props.content ?? "Ship the login fix"}+ attachments={props.attachments}+ statusText={props.statusText}+ />+ </Theme>,+ );+}++describe("PendingChatView", () => {+ beforeEach(() => {+ ResizeObserverCapture.instances = [];+ vi.stubGlobal("ResizeObserver", ResizeObserverCapture);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("renders the prompt as a chat message with the default status", () => {+ renderPending();+ expect(screen.getByText("Ship the login fix")).toBeInTheDocument();+ expect(screen.getByText("Starting task...")).toBeInTheDocument();+ });++ it("shows the live run status in place of the default line", () => {+ renderPending({ statusText: "Starting the sandbox…" });+ expect(screen.getByText("Starting the sandbox…")).toBeInTheDocument();+ expect(screen.queryByText("Starting task...")).not.toBeInTheDocument();+ });++ it("renders file mentions as chips so the bubble matches the live transcript", () => {+ renderPending({+ content: 'fix <file path="src/a.ts" />',+ });+ expect(screen.getByText("src/a.ts")).toBeInTheDocument();+ expect(screen.queryByText("fix @src/a.ts")).not.toBeInTheDocument();+ });++ it("hides attachment chips when the content already carries file mentions", () => {+ renderPending({+ content: 'run this <file path="src/a.ts" />',+ attachments: [{ id: "src/a.ts", label: "src/a.ts" }],+ });+ expect(screen.getByText("src/a.ts")).toBeInTheDocument();+ // The attachment would render the same label a second time.+ expect(screen.getAllByText("src/a.ts")).toHaveLength(1);+ });++ it("shows attachments for plain content without file mentions", () => {+ renderPending({+ content: "summarize this",+ attachments: [{ id: "notes.txt", label: "notes.txt" }],+ });+ expect(screen.getByText("notes.txt")).toBeInTheDocument();+ });++ it("clamps a long prompt to five lines and expands on Show more", async () => {+ renderPending({+ content: Array.from({ length: 20 }, (_, i) => `line ${i}`).join("\n\n"),+ });++ const clamped = document.querySelector(".max-h-\\[5lh\\]");+ expect(clamped).not.toBeNull();+ expect(screen.queryByText("Show more")).not.toBeInTheDocument();++ measure(clamped as HTMLElement, true);+ await waitFor(() =>+ expect(screen.getByText("Show more")).toBeInTheDocument(),+ );++ fireEvent.click(screen.getByText("Show more"));+ expect(screen.getByText("Show less")).toBeInTheDocument();+ expect(document.querySelector(".max-h-\\[5lh\\]")).toBeNull();+ });++ it("keeps a short prompt unclamped with no toggle", () => {+ renderPending({ content: "Ship the login fix" });++ const clamped = document.querySelector(".max-h-\\[5lh\\]");+ expect(clamped).not.toBeNull();+ measure(clamped as HTMLElement, false);+ expect(screen.queryByText("Show more")).not.toBeInTheDocument();+ });+});diff --git a/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.tsx b/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.tsxindex 01409dabe085..df3612c2674f 100644--- a/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.tsx@@ -1,43 +1,74 @@import { Brain } from "@phosphor-icons/react";+import {+ ChatBubble,+ ChatBubbleContent,+ ChatMessage,+ ChatMessageContent,+ ChatMessageFooter,+} from "@posthog/quill";+import { ComposerWidth } from "@posthog/ui/features/sessions/components/ComposerWidth";+import { UserMessageBody } from "@posthog/ui/features/sessions/components/chat-thread/UserMessageBody";import { PendingInputPlaceholder } from "@posthog/ui/features/sessions/components/PendingInputPlaceholder";-import { UserMessage } from "@posthog/ui/features/sessions/components/session-update/UserMessage";-import { CHAT_CONTENT_MAX_WIDTH } from "@posthog/ui/features/sessions/constants";+import {+ CHAT_CONTENT_MAX_WIDTH,+ CHAT_CONTENT_PADDING_INLINE,+} from "@posthog/ui/features/sessions/constants";import type { UserMessageAttachment } from "@posthog/ui/features/sessions/userMessageTypes";-import { Box, Flex, Text } from "@radix-ui/themes";interface PendingChatViewProps {- promptText: string;+ /**+ * The prompt as the live transcript will render it (serialized content with+ * chips), so the bubble looks the same when the transcript replaces it.+ */+ content: string;attachments?: UserMessageAttachment[];+ statusText?: string;}export function PendingChatView({- promptText,+ content,attachments,+ statusText,}: PendingChatViewProps) {return (- <Flex direction="column" className="absolute inset-0 bg-background">- <Box className="min-h-0 flex-1 overflow-y-auto">- <Box- className="mx-auto flex flex-col gap-3 px-2 py-1.5"- style={{ maxWidth: CHAT_CONTENT_MAX_WIDTH }}+ <div className="absolute inset-0 flex flex-col bg-background">+ <div className="min-h-0 flex-1 overflow-y-auto [scrollbar-gutter:stable]">+ <div+ className="flex w-full flex-col gap-4 py-4 pb-8"+ style={{ paddingInline: CHAT_CONTENT_PADDING_INLINE }}>- <UserMessage- content={promptText}- attachments={attachments}- animate={false}- />- <Flex align="center" gap="2" className="pl-3">+ <div+ className="mx-auto w-full py-1"+ style={{ maxWidth: CHAT_CONTENT_MAX_WIDTH }}+ >+ <ChatMessage align="end">+ <ChatMessageContent className="gap-1">+ <ChatBubble align="end" className="rounded-lg">+ <ChatBubbleContent>+ <UserMessageBody+ content={content}+ attachments={attachments}+ />+ </ChatBubbleContent>+ </ChatBubble>+ <ChatMessageFooter aria-hidden className="min-h-5" />+ </ChatMessageContent>+ </ChatMessage>+ </div>+ <div+ className="mx-auto flex w-full items-center gap-2 px-2.5"+ style={{ maxWidth: CHAT_CONTENT_MAX_WIDTH }}+ ><Brain size={12} className="ph-pulse text-accent-11" />- <Text className="text-[13px] text-accent-11">Starting task...</Text>- </Flex>- </Box>- </Box>- <Box- className="mx-auto w-full p-2"- style={{ maxWidth: CHAT_CONTENT_MAX_WIDTH }}- >+ <span className="text-[13px] text-accent-11">+ {statusText ?? "Starting task..."}+ </span>+ </div>+ </div>+ </div>+ <ComposerWidth compact={false}><PendingInputPlaceholder />- </Box>- </Flex>+ </ComposerWidth>+ </div>);}diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionInitializingView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionInitializingView.tsxindex 3e555a856598..e2323a886421 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SessionInitializingView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionInitializingView.tsx@@ -13,7 +13,7 @@ interface SessionInitializingViewProps {const REVEAL_DELAY_MS = 2000;-function copyFor(+export function sessionInitializingCopy(executionTarget: "cloud" | "local",cloudStatus: TaskRunStatus | null | undefined,): { heading: string; subtitle: string } {@@ -49,7 +49,7 @@ export function SessionInitializingView({heading,subtitle,}: SessionInitializingViewProps) {- const copy = copyFor(executionTarget, cloudStatus);+ const copy = sessionInitializingCopy(executionTarget, cloudStatus);const visibleHeading = heading ?? copy.heading;const visibleSubtitle = subtitle ?? copy.subtitle;diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsxindex a285ec24b30a..76f03f5645cb 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx@@ -53,7 +53,10 @@ import { PlanStatusBar } from "@posthog/ui/features/sessions/components/PlanStatimport { QueuedMessagesDock } from "@posthog/ui/features/sessions/components/QueuedMessagesDock";import { ReasoningLevelSelector } from "@posthog/ui/features/sessions/components/ReasoningLevelSelector";import { RawLogsView } from "@posthog/ui/features/sessions/components/raw-logs/RawLogsView";-import { SessionInitializingView } from "@posthog/ui/features/sessions/components/SessionInitializingView";+import {+ SessionInitializingView,+ sessionInitializingCopy,+} from "@posthog/ui/features/sessions/components/SessionInitializingView";import { SideQuestionCard } from "@posthog/ui/features/sessions/components/SideQuestionCard";import { SteerQueueToggle } from "@posthog/ui/features/sessions/components/SteerQueueToggle";import {@@ -742,16 +745,23 @@ export function SessionView({</Box></>) : isInitializing ? (- isCloud ? (+ pendingTaskPrompt?.promptText ? (+ <PendingChatView+ content={+ pendingTaskPrompt.contentXml ?? pendingTaskPrompt.promptText+ }+ attachments={pendingTaskPrompt.attachments}+ statusText={+ isCloud+ ? sessionInitializingCopy("cloud", cloudStatus).heading+ : undefined+ }+ />+ ) : isCloud ? (<SessionInitializingViewexecutionTarget="cloud"cloudStatus={cloudStatus}/>- ) : pendingTaskPrompt?.promptText ? (- <PendingChatView- promptText={pendingTaskPrompt.promptText}- attachments={pendingTaskPrompt.attachments}- />) : (<Flexalign="center"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.tsxindex 6166c300c198..c517478f4315 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@@ -1,5 +1,4 @@import {- CaretDown,Check,Copy,FileText,@@ -87,6 +86,7 @@ import {type TurnRow,} from "@posthog/ui/features/sessions/components/chat-thread/threadVirtualization";import { buildTurnCopyText } from "@posthog/ui/features/sessions/components/chat-thread/turnCopyText";+import { UserMessageBody } from "@posthog/ui/features/sessions/components/chat-thread/UserMessageBody";import { usePromptRecallSource } from "@posthog/ui/features/sessions/components/chat-thread/usePromptRecallSource";import { VirtualThreadScrollBody } from "@posthog/ui/features/sessions/components/chat-thread/VirtualThreadScrollBody";import {@@ -106,17 +106,12 @@ import {ONBOARDING_BRIEF_LABEL,ONBOARDING_BRIEF_TOOLTIP,} from "@posthog/ui/features/sessions/components/session-update/onboardingBrief";-import {- hasFileMentions,- MentionChip,- parseFileMentions,-} from "@posthog/ui/features/sessions/components/session-update/parseFileMentions";+import { MentionChip } from "@posthog/ui/features/sessions/components/session-update/parseFileMentions";import { extractPeerAgentMessage } from "@posthog/ui/features/sessions/components/session-update/peerAgentMessage";import { collapsePiSkillInvocation } from "@posthog/ui/features/sessions/components/session-update/piSkillInvocation";import { SessionUpdateView } from "@posthog/ui/features/sessions/components/session-update/SessionUpdateView";import { isShowActionsItem } from "@posthog/ui/features/sessions/components/session-update/showActionsItem";import { UserShellExecuteView } from "@posthog/ui/features/sessions/components/session-update/UserShellExecuteView";-import { UserMessageAttachments } from "@posthog/ui/features/sessions/components/UserMessageAttachments";import {CHAT_CONTENT_MAX_WIDTH,CHAT_CONTENT_PADDING_INLINE,@@ -595,29 +590,8 @@ function UserBubble({(s) => s.openCanvasInstructionsInSplit,);- const containsFileMentions = hasFileMentions(displayContent);-- const [isExpanded, setIsExpanded] = useState(false);- const [isOverflowing, setIsOverflowing] = useState(false);- const textRef = useRef<HTMLDivElement>(null);const footerRevealed = useContext(FooterRevealContext);- // Only meaningful while collapsed: expanding removes the clamp so scrollHeight === clientHeight.- // We keep the prior result when expanded so the "Show less" trigger stays put.- // biome-ignore lint/correctness/useExhaustiveDependencies: re-measure when the message text changes.- useEffect(() => {- if (isExpanded) return;- const el = textRef.current;- if (!el) return;- // The observer fires once on observe, after layout, so the first measure- // forces no layout inside the commit.- const observer = new ResizeObserver(() =>- setIsOverflowing(el.scrollHeight - el.clientHeight > 1),- );- observer.observe(el);- return () => observer.disconnect();- }, [displayContent, isExpanded]);-return (<MessageContextMenu value={displayContent}><ChatMessage align={peerAgentMessage ? "start" : "end"} className="group">@@ -683,42 +657,10 @@ function UserBubble({)}><ChatBubbleContent>- <div- ref={textRef}- className={cn(- "[&_p]:my-0",- !isExpanded && "max-h-[5lh] overflow-hidden",- // Fade the clamped text out at the bottom so it reads as "continues below". Only- // when actually overflowing — a short collapsed message shouldn't fade. The mask is- // paint-only, so it doesn't affect the overflow measurement above.- !isExpanded &&- isOverflowing &&- "[mask-image:linear-gradient(to_bottom,black_45%,transparent)]",- )}- >- {containsFileMentions ? (- parseFileMentions(displayContent)- ) : (- <ChatMarkdown content={displayContent} />- )}- </div>- {attachments.length > 0 && !containsFileMentions && (- <div className="mt-1.5">- <UserMessageAttachments attachments={attachments} />- </div>- )}- {isOverflowing && (- <button- type="button"- onClick={() => setIsExpanded((v) => !v)}- className="mt-1 flex items-center gap-0.5 text-muted-foreground text-sm hover:text-foreground"- >- Show {isExpanded ? "less" : "more"}- <CaretDown- className={cn("size-3", isExpanded && "rotate-180")}- />- </button>- )}+ <UserMessageBody+ content={displayContent}+ attachments={attachments}+ /></ChatBubbleContent></ChatBubble>)}diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/UserMessageBody.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/UserMessageBody.tsxnew file mode 100644index 000000000000..ba9e45942317--- /dev/null+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/UserMessageBody.tsx@@ -0,0 +1,91 @@+import { CaretDown } from "@phosphor-icons/react";+import { cn } from "@posthog/quill";+import { ChatMarkdown } from "@posthog/ui/features/sessions/components/chat-thread/ChatMarkdown";+import {+ hasFileMentions,+ parseFileMentions,+} from "@posthog/ui/features/sessions/components/session-update/parseFileMentions";+import { UserMessageAttachments } from "@posthog/ui/features/sessions/components/UserMessageAttachments";+import type { UserMessageAttachment } from "@posthog/ui/features/sessions/userMessageTypes";+import { useEffect, useRef, useState } from "react";++/**+ * The body of a user-authored chat bubble. Content carrying file, folder,+ * GitHub, or slash-command mentions renders as chips, so the same prompt draws+ * identically in the live transcript and in views that precede it. Plain+ * content renders as markdown.+ *+ * Attachments hide when the content carries file mentions: contentToXml folds+ * every attachment into a <file /> tag, so showing both would list it twice.+ *+ * Long content clamps to five lines with a Show more toggle, so a bubble in a+ * pre-transcript view never grows past what the live bubble would show.+ */+export function UserMessageBody({+ content,+ attachments = [],+}: {+ content: string;+ attachments?: UserMessageAttachment[];+}) {+ const containsFileMentions = hasFileMentions(content);++ const [isExpanded, setIsExpanded] = useState(false);+ const [isOverflowing, setIsOverflowing] = useState(false);+ const textRef = useRef<HTMLDivElement>(null);++ // Only meaningful while collapsed: expanding removes the clamp so scrollHeight === clientHeight.+ // We keep the prior result when expanded so the "Show less" trigger stays put.+ // biome-ignore lint/correctness/useExhaustiveDependencies: re-measure when the message text changes.+ useEffect(() => {+ if (isExpanded) return;+ const el = textRef.current;+ if (!el) return;+ // The observer fires once on observe, after layout, so the first measure+ // forces no layout inside the commit.+ const observer = new ResizeObserver(() =>+ setIsOverflowing(el.scrollHeight - el.clientHeight > 1),+ );+ observer.observe(el);+ return () => observer.disconnect();+ }, [content, isExpanded]);++ return (+ <>+ <div+ ref={textRef}+ className={cn(+ "[&_p]:my-0",+ !isExpanded && "max-h-[5lh] overflow-hidden",+ // Fade the clamped text out at the bottom so it reads as "continues below". Only+ // when actually overflowing — a short collapsed message shouldn't fade. The mask is+ // paint-only, so it doesn't affect the overflow measurement above.+ !isExpanded &&+ isOverflowing &&+ "[mask-image:linear-gradient(to_bottom,black_45%,transparent)]",+ )}+ >+ {containsFileMentions ? (+ parseFileMentions(content)+ ) : (+ <ChatMarkdown content={content} />+ )}+ </div>+ {attachments.length > 0 && !containsFileMentions && (+ <div className="mt-1.5">+ <UserMessageAttachments attachments={attachments} />+ </div>+ )}+ {isOverflowing && (+ <button+ type="button"+ onClick={() => setIsExpanded((v) => !v)}+ className="mt-1 flex items-center gap-0.5 text-muted-foreground text-sm hover:text-foreground"+ >+ Show {isExpanded ? "less" : "more"}+ <CaretDown className={cn("size-3", isExpanded && "rotate-180")} />+ </button>+ )}+ </>+ );+}diff --git a/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.test.ts b/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.test.tsindex fe98b2d706b3..c6a5c900dc69 100644--- a/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.test.ts@@ -96,28 +96,40 @@ describe("mergeConversationItems", () => {expect(pinned.content).toBe(echoedWithContext);});- it.each([- { name: "plain bare echo", bare: "hello" },- {- name: "bare echo carrying an attachment summary",- bare: "hello\n\nAttached files: clipboard.png",- },- ])(- "cloud: folds a raced $name and the shadow-context echo into the pinned message",- ({ bare }) => {+ it.each(+ [+ { name: "plain bare echo", bare: "hello" },+ {+ name: "bare echo carrying an attachment summary",+ bare: "hello\n\nAttached files: clipboard.png",+ },+ ].flatMap((entry) => [+ { ...entry, withOptimistic: true },+ { ...entry, withOptimistic: false },+ ]),+ )(+ "cloud: folds a raced $name and the shadow-context echo (optimistic: $withOptimistic)",+ ({ bare, withOptimistic }) => {const echoedWithContext ='hello\n\n<channel_context channel="bluebird">background</channel_context>';const result = mergeConversationItems({conversationItems: [userMessage("bare", bare),+ progressGroup("setup"),userMessage("shadow", echoedWithContext),userMessage("other", "different"),],- optimisticItems: [userMessage("opt", echoedWithContext)],+ optimisticItems: withOptimistic+ ? [userMessage("opt", echoedWithContext)]+ : [],isCloud: true,});- expect(result.map((item) => item.id)).toEqual(["opt", "other"]);+ expect(result.map((item) => item.id)).toEqual([+ withOptimistic ? "opt" : "bare",+ "setup",+ "other",+ ]);const pinned = result[0];if (pinned.type !== "user_message")throw new Error("expected user_message");@@ -125,6 +137,31 @@ describe("mergeConversationItems", () => {},);+ it("cloud: preserves a repeated prompt after the agent has replied", () => {+ const reply: ConversationItem = {+ ...progressGroup("reply"),+ update: {+ sessionUpdate: "agent_message_chunk",+ content: { type: "text", text: "Build checked." },+ },+ } as ConversationItem;+ const conversationItems = [+ userMessage("first", "Check the build"),+ reply,+ userMessage(+ "second",+ 'Check the build\n\n<channel_context channel="example">Project notes.</channel_context>',+ ),+ ];+ expect(+ mergeConversationItems({+ conversationItems,+ optimisticItems: [],+ isCloud: true,+ }),+ ).toEqual(conversationItems);+ });+it("cloud: dedupes the echo when the placeholder carries an 'Attached files:' summary the echo lacks", () => {const echoed = {...userMessage("echo", "hello\n\nDo this"),diff --git a/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.tsindex 820aa83e572d..a584f634a9ab 100644--- a/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/mergeConversationItems.ts@@ -37,6 +37,41 @@ function hasShadowContext(content: string): boolean {return hasChannelContext(content) || hasCustomInstructions(content);}+function reconcileInitialPromptEcho(+ items: ConversationItem[],+): ConversationItem[] {+ let initial: UserMessageItem | undefined;+ for (let index = 0; index < items.length; index++) {+ const item = items[index];+ if (+ item.type === "session_update" &&+ item.update.sessionUpdate === "progress_group"+ ) {+ continue;+ }+ if (item.type !== "user_message") return items;+ if (!initial) {+ if (hasShadowContext(item.content)) return items;+ initial = item;+ continue;+ }+ if (+ !hasShadowContext(item.content) ||+ strippedUserContent(initial.content) !== strippedUserContent(item.content)+ ) {+ return items;+ }+ // The stored startup transcript can contain both the bare request and its+ // context-bearing echo even after the in-memory optimistic row is gone.+ return items+ .filter((_, itemIndex) => itemIndex !== index)+ .map((entry) =>+ entry === initial ? { ...item, id: initial.id } : entry,+ );+ }+ return items;+}+// Cloud's initial optimistic is pinned to the top so the user's prompt stays// visible above setup progress. Follow-up optimistics render at the tail, but// before trailing progress cards, to match where the streamed `session/prompt`@@ -49,6 +84,9 @@ export function mergeConversationItems({optimisticItems,isCloud,}: MergeConversationItemsArgs): ConversationItem[] {+ if (isCloud) {+ conversationItems = reconcileInitialPromptEcho(conversationItems);+ }if (optimisticItems.length === 0) {return conversationItems;}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsxindex 6ce666a4391f..5b14443e98e6 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx@@ -85,8 +85,7 @@ export function SidebarNavSection({// Active flags are pure functions of the current view — mirror what// useSidebarData derives, without pulling in its task-loading.- const isHomeActive =- view.type === "task-input" || view.type === "task-pending";+ const isHomeActive = view.type === "task-input";const isActivityActive = view.type === "activity";const isInboxActive = view.type === "inbox";const isLoopsActive = view.type === "loops";diff --git a/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsx b/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsxindex e795ea01985d..c38b2e95119b 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsx@@ -114,8 +114,7 @@ export function TaskListView({(state) => state.showSidebarWorktrees,);const view = useAppView();- const isOnTaskInput =- view.type === "task-input" || view.type === "task-pending";+ const isOnTaskInput = view.type === "task-input";const prefersReducedMotion = useReducedMotion();// A drag that starts on a selected row carries the whole selection, so a pin// or an unpin applies to every row the user picked, not just the grabbed one.diff --git a/products/desktop/packages/ui/src/features/sidebar/useSidebarData.ts b/products/desktop/packages/ui/src/features/sidebar/useSidebarData.tsindex 5cdc362e8b14..32989c0d0347 100644--- a/products/desktop/packages/ui/src/features/sidebar/useSidebarData.ts+++ b/products/desktop/packages/ui/src/features/sidebar/useSidebarData.ts@@ -131,8 +131,7 @@ export function useSidebarData({],);- const isHomeActive =- activeView.type === "task-input" || activeView.type === "task-pending";+ const isHomeActive = activeView.type === "task-input";const isInboxActive = activeView.type === "inbox";const isAgentsActive = activeView.type === "agents";const isCommandCenterActive = activeView.type === "command-center";diff --git a/products/desktop/packages/ui/src/features/task-detail/components/InterruptedPromptView.tsx b/products/desktop/packages/ui/src/features/task-detail/components/InterruptedPromptView.tsxdeleted file mode 100644index 0a4793ecd34c..000000000000--- a/products/desktop/packages/ui/src/features/task-detail/components/InterruptedPromptView.tsx+++ /dev/null@@ -1,82 +0,0 @@-import type { PendingPromptInterruptReason } from "@posthog/core/tasks/pendingPrompts";-import { Button, Text } from "@posthog/quill";-import { UserMessage } from "@posthog/ui/features/sessions/components/session-update/UserMessage";-import { CHAT_CONTENT_MAX_WIDTH } from "@posthog/ui/features/sessions/constants";-import type { UserMessageAttachment } from "@posthog/ui/features/sessions/userMessageTypes";--interface InterruptedPromptViewProps {- promptText: string;- attachments?: UserMessageAttachment[];- reason: PendingPromptInterruptReason;- onRecover: () => void;- onDiscard: () => void;-}--const STATUS: Record<- PendingPromptInterruptReason,- { title: string; detail: string }-> = {- offline: {- title: "You're offline, so this task hasn't started",- detail:- "Your prompt is saved. Recover it to try again once you're back online.",- },- failed: {- title: "This task couldn't start",- detail: "Your prompt is saved. Recover it to edit and try again.",- },-};--/**- * Shown on the pending route when task setup failed and left the prompt unsent.- * Keeps the prompt on screen with actions to recover it into the composer or- * discard it, instead of dropping the user onto an empty screen.- */-export function InterruptedPromptView({- promptText,- attachments,- reason,- onRecover,- onDiscard,-}: InterruptedPromptViewProps) {- const status = STATUS[reason];- return (- <div className="absolute inset-0 flex flex-col bg-background">- <div className="min-h-0 flex-1 overflow-y-auto">- <div- className="mx-auto flex flex-col gap-3 px-2 py-1.5"- style={{ maxWidth: CHAT_CONTENT_MAX_WIDTH }}- >- <UserMessage- content={promptText}- attachments={attachments}- animate={false}- />- </div>- </div>- <div- className="mx-auto w-full p-2"- style={{ maxWidth: CHAT_CONTENT_MAX_WIDTH }}- >- <div className="flex flex-col gap-3 rounded-(--radius-3) border border-(--gray-5) bg-(--gray-2) p-4">- <div className="flex flex-col gap-1">- <Text weight="medium" className="text-(--gray-12)">- {status.title}- </Text>- <Text size="sm" className="text-(--gray-11)">- {status.detail}- </Text>- </div>- <div className="flex gap-2">- <Button variant="primary" size="default" onClick={onRecover}>- Recover prompt- </Button>- <Button variant="outline" size="default" onClick={onDiscard}>- Discard- </Button>- </div>- </div>- </div>- </div>- );-}diff --git a/products/desktop/packages/ui/src/features/task-detail/components/PendingPromptRecovery.tsx b/products/desktop/packages/ui/src/features/task-detail/components/PendingPromptRecovery.tsxindex afd610006455..7f0d6981f42d 100644--- a/products/desktop/packages/ui/src/features/task-detail/components/PendingPromptRecovery.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/components/PendingPromptRecovery.tsx@@ -20,7 +20,7 @@ export function PendingPromptRecovery(): null {async function recoverNewestPendingPrompt(): Promise<void> {await pendingTaskPromptStoreApi.whenHydrated();- const orphans = pendingTaskPromptStoreApi.getAllNewestFirst();+ const orphans = pendingTaskPromptStoreApi.getRecoverableNewestFirst();const [newest] = orphans;if (!newest) {return;diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsxindex 1625a29ed2f7..600d559e4692 100644--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx@@ -45,7 +45,6 @@ import {useAdapterSubscription,} from "@posthog/ui/features/settings/adapterSubscription";import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";-import { NEW_TASK_COMPOSER_FADE_MS } from "@posthog/ui/features/task-detail/newTaskComposerTransition";import type { TaskInputReportAssociation } from "@posthog/ui/features/task-detail/stores/taskInputPrefillStore";import { useTaskInputPrefillStore } from "@posthog/ui/features/task-detail/stores/taskInputPrefillStore";import { navigateToInbox } from "@posthog/ui/router/navigationBridge";@@ -1052,7 +1051,6 @@ export function TaskInput({const {isCreatingTask,- isExitingComposer,canSubmit,handleSubmit,additionalDirectories,@@ -1122,7 +1120,7 @@ export function TaskInput({...resolvedRun,instructions: contentToXml(content).trim(),});- const submitted = await handleSubmit(override);+ const submitted = await handleSubmit(override, content);if (submitted) {track(ANALYTICS_EVENTS.AUTORESEARCH_RUN_STARTED, {direction: resolvedRun.direction,@@ -1390,16 +1388,8 @@ export function TaskInput({// suggestions fade out (and back in when the prompt is cleared).top: suggestions && suggestions.length > 0 ? "38%" : "50%",transform: "translate(-50%, -50%)",- // Once the task is on its way, the whole composer fades out and- // the pending chat fades in over it.- opacity: isExitingComposer ? 0 : 1,- transitionProperty: "opacity",- transitionDuration: `${NEW_TASK_COMPOSER_FADE_MS}ms`,- transitionTimingFunction: "ease-out",}}- className={`absolute left-1/2 z-1 flex w-[calc(100%-2rem)] max-w-[600px] flex-col gap-2 ${- isExitingComposer ? "pointer-events-none" : ""- }`}+ className="absolute left-1/2 z-1 flex w-[calc(100%-2rem)] max-w-[600px] flex-col gap-2"><Flexgap="2"diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskPendingView.test.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskPendingView.test.tsxdeleted file mode 100644index 4ecbfa99b599..000000000000--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskPendingView.test.tsx+++ /dev/null@@ -1,87 +0,0 @@-import { Theme } from "@radix-ui/themes";-import { act, render, screen } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";--// The record-present branches render heavy session/composer trees this test-// never exercises (both cases below have no record), so stub them out.-vi.mock("../../sessions/components/PendingChatView", () => ({- PendingChatView: () => <div>pending-chat</div>,-}));-vi.mock("./InterruptedPromptView", () => ({- InterruptedPromptView: () => <div>interrupted</div>,-}));-vi.mock("@posthog/ui/router/useOpenTask", () => ({- openTaskInput: vi.fn(),-}));-vi.mock("@posthog/ui/features/task-detail/pendingPromptActions", () => ({- recoverPendingPrompt: vi.fn(),- discardPendingPrompt: vi.fn(),-}));--import { usePendingTaskPromptStore } from "../../../shell/pendingTaskPromptStore";-import { TaskPendingView } from "./TaskPendingView";--const UNAVAILABLE_TEXT = "This prompt is no longer available";--function renderPending() {- render(- <Theme>- <TaskPendingView pendingTaskKey="missing-key" />- </Theme>,- );-}--describe("TaskPendingView hydration gate", () => {- beforeEach(() => {- usePendingTaskPromptStore.setState({ byKey: {}, _hasHydrated: false });- });-- // The store hydrates from async host storage, so a lookup miss before- // hydration does not mean the record is gone. Showing the unavailable state- // then would strand a still-on-disk prompt behind a "Start a new task" button.- it("waits instead of claiming the prompt is gone before hydration", () => {- usePendingTaskPromptStore.setState({ _hasHydrated: false });- renderPending();- expect(screen.queryByText(UNAVAILABLE_TEXT)).not.toBeInTheDocument();- expect(- screen.queryByRole("button", { name: "Start a new task" }),- ).not.toBeInTheDocument();- });-- it("shows the unavailable state once a hydrated lookup finds no record", () => {- usePendingTaskPromptStore.setState({ _hasHydrated: true });- renderPending();- expect(screen.getByText(UNAVAILABLE_TEXT)).toBeInTheDocument();- expect(- screen.getByRole("button", { name: "Start a new task" }),- ).toBeInTheDocument();- });-- it("keeps the pending view while its prompt moves to the created task", () => {- usePendingTaskPromptStore.setState({ _hasHydrated: true });- usePendingTaskPromptStore.getState().set("pending-key", {- promptText: "Create a task",- attachments: [],- });- const { unmount } = render(- <Theme>- <TaskPendingView pendingTaskKey="pending-key" />- </Theme>,- );-- act(() => {- usePendingTaskPromptStore.getState().move("pending-key", "task-1");- });-- expect(screen.getByText("pending-chat")).toBeInTheDocument();- expect(screen.queryByText(UNAVAILABLE_TEXT)).not.toBeInTheDocument();-- unmount();- render(- <Theme>- <TaskPendingView pendingTaskKey="pending-key" />- </Theme>,- );- expect(screen.getByText(UNAVAILABLE_TEXT)).toBeInTheDocument();- });-});diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskPendingView.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskPendingView.tsxdeleted file mode 100644index 2fe0f8d6c99a..000000000000--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskPendingView.tsx+++ /dev/null@@ -1,110 +0,0 @@-import { ChatCircle } from "@phosphor-icons/react";-import {- Button,- Empty,- EmptyContent,- EmptyDescription,- EmptyHeader,- EmptyMedia,- EmptyTitle,- Spinner,-} from "@posthog/quill";-import { NEW_TASK_COMPOSER_FADE_MS } from "@posthog/ui/features/task-detail/newTaskComposerTransition";-import {- discardPendingPrompt,- recoverPendingPrompt,-} from "@posthog/ui/features/task-detail/pendingPromptActions";-import { openTaskInput } from "@posthog/ui/router/useOpenTask";-import { motion } from "framer-motion";-import { useCallback, useEffect } from "react";-import {- usePendingTaskPrompt,- usePendingTaskPromptStore,-} from "../../../shell/pendingTaskPromptStore";-import { PendingChatView } from "../../sessions/components/PendingChatView";-import { InterruptedPromptView } from "./InterruptedPromptView";--interface TaskPendingViewProps {- pendingTaskKey: string;-}--export function TaskPendingView({ pendingTaskKey }: TaskPendingViewProps) {- const pending = usePendingTaskPrompt(pendingTaskKey);- const pendingHandoff = usePendingTaskPromptStore(- (state) => state.handoffs[pendingTaskKey],- );- // The store persists through async host storage, so the first render always- // sees an empty map. Without gating on hydration a reload straight onto this- // route would flash "no longer available" over a record that is still on disk.- const hasHydrated = usePendingTaskPromptStore((state) => state._hasHydrated);- const clearHandoff = usePendingTaskPromptStore((state) => state.clearHandoff);- const displayedPending = pending ?? pendingHandoff;-- useEffect(() => {- return () => clearHandoff(pendingTaskKey);- }, [clearHandoff, pendingTaskKey]);-- const handleRecover = useCallback(() => {- recoverPendingPrompt(pendingTaskKey);- }, [pendingTaskKey]);- const handleDiscard = useCallback(() => {- discardPendingPrompt(pendingTaskKey);- }, [pendingTaskKey]);-- return (- // Picks up where the new-task composer's fade-out left off, so submitting- // reads as one phase handing over to the next.- <motion.div- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- transition={{- duration: NEW_TASK_COMPOSER_FADE_MS / 1000,- ease: "easeOut",- }}- className="relative h-full w-full bg-background"- >- {displayedPending?.interruptReason ? (- <InterruptedPromptView- promptText={displayedPending.promptText}- attachments={displayedPending.attachments}- reason={displayedPending.interruptReason}- onRecover={handleRecover}- onDiscard={handleDiscard}- />- ) : displayedPending ? (- <PendingChatView- promptText={displayedPending.promptText}- attachments={displayedPending.attachments}- />- ) : !hasHydrated ? (- <div className="absolute inset-0 flex items-center justify-center p-6">- <Spinner className="h-6 w-6" />- </div>- ) : (- <div className="absolute inset-0 flex items-center justify-center p-6">- <Empty>- <EmptyHeader>- <EmptyMedia variant="icon">- <ChatCircle />- </EmptyMedia>- <EmptyTitle>This prompt is no longer available</EmptyTitle>- <EmptyDescription>- It was already sent or discarded. Start a new task to keep- going.- </EmptyDescription>- </EmptyHeader>- <EmptyContent>- <Button- variant="primary"- size="default"- onClick={() => openTaskInput()}- >- Start a new task- </Button>- </EmptyContent>- </Empty>- </div>- )}- </motion.div>- );-}diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.test.tsx b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.test.tsxnew file mode 100644index 000000000000..dae66e3b2420--- /dev/null+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.test.tsx@@ -0,0 +1,242 @@+import type { EditorContent } from "@posthog/core/message-editor/content";+import {+ contentToPlainText,+ contentToXml,+ textToContent,+} from "@posthog/core/message-editor/content";+import type { Task } from "@posthog/shared/domain-types";+import { useTaskInputPrefillStore } from "@posthog/ui/features/task-detail/stores/taskInputPrefillStore";+import {+ pendingTaskPromptStoreApi,+ usePendingTaskPromptStore,+} from "@posthog/ui/shell/pendingTaskPromptStore";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, renderHook } from "@testing-library/react";+import type { ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const createTaskMock = vi.hoisted(() => vi.fn());+const invalidateTasksMock = vi.hoisted(() => vi.fn());+const openTaskMock = vi.hoisted(() => vi.fn());+const trackMock = vi.hoisted(() => vi.fn());++vi.mock("@posthog/di/react", () => ({+ useService: () => ({ createTask: createTaskMock }),+}));+vi.mock("@posthog/host-router/react", () => ({+ useHostTRPC: () => ({+ workspace: { getAll: { queryKey: () => ["workspaces"] } },+ additionalDirectories: {+ listDefaults: {+ queryOptions: () => ({+ queryKey: ["additional-directories"],+ queryFn: async () => [],+ }),+ },+ },+ }),+ useHostTRPCClient: () => ({+ workspace: { getWorktreeFileUsage: { query: vi.fn() } },+ }),+}));+vi.mock("@posthog/ui/features/canvas/hooks/useTaskChannels", () => ({+ useTaskChannels: () => ({ personalChannel: null }),+}));+vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({+ useFeatureFlag: () => false,+}));+vi.mock("@posthog/ui/features/settings/adapterSubscription", () => ({+ useAdapterSubscription: () => ({+ flagEnabled: false,+ loginState: "logged-out",+ subscriptionOn: false,+ }),+ subscriptionModelAccess: () => undefined,+}));+vi.mock("@posthog/ui/features/tasks/useTaskCrudMutations", () => ({+ useCreateTask: () => ({ invalidateTasks: invalidateTasksMock }),+}));+vi.mock("@posthog/ui/features/tasks/useTasks", () => ({+ useTasks: () => ({ data: [] }),+}));+vi.mock("@posthog/ui/features/local-mcp/useLocalMcpCloudServers", () => ({+ useLocalMcpCloudServers: () => ({ servers: [], isLoading: false }),+}));+vi.mock("../../../hooks/useConnectivity", () => ({+ useConnectivity: () => ({ isOnline: true }),+}));+vi.mock("../../billing/preflightCloudUsage", () => ({+ assertCloudUsageAvailable: async () => true,+}));+vi.mock("../../../primitives/toast", () => ({+ toast: { error: vi.fn() },+}));+vi.mock("../../../shell/analytics", () => ({ track: trackMock }));+vi.mock("../../../shell/logger", () => ({+ logger: {+ scope: () => ({ warn: vi.fn(), error: vi.fn(), info: vi.fn() }),+ },+}));+vi.mock("@posthog/ui/features/notifications/errorDetails", () => ({+ toastError: vi.fn(),+}));+vi.mock("@posthog/ui/features/auth/store", () => ({+ useAuthStateValue: () => true,+}));+vi.mock("@posthog/ui/router/useOpenTask", async (importOriginal) => {+ const actual =+ await importOriginal<typeof import("@posthog/ui/router/useOpenTask")>();+ return { ...actual, openTask: openTaskMock };+});++import type { EditorHandle } from "../../message-editor/types";+import { useTaskCreation } from "./useTaskCreation";++const KICKOFF_PREAMBLE =+ "AUTORESEARCH KICKOFF — protocol instructions generated for the run";++function fakeTask(): Task {+ return {+ id: "task-1",+ task_number: 1,+ slug: "task-1",+ title: "Optimize the login flow",+ description: "Optimize the login flow",+ created_at: "2026-06-15T00:00:00.000Z",+ updated_at: "2026-06-15T00:00:00.000Z",+ origin_product: "user_created",+ };+}++function editorHandle(content: EditorContent): { current: EditorHandle } {+ return {+ current: {+ focus: vi.fn(),+ blur: vi.fn(),+ clear: vi.fn(),+ isEmpty: () => false,+ getContent: () => content,+ getText: () => contentToPlainText(content),+ setContent: vi.fn(),+ insertEditorContent: vi.fn(),+ insertChip: vi.fn(),+ removeChipById: vi.fn(),+ replaceChipAttrs: vi.fn(),+ addAttachment: vi.fn(),+ removeAttachment: vi.fn(),+ },+ };+}++function wrapper({ children }: { children: ReactNode }) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+}++function renderTaskCreation(+ content: EditorContent,+ workspaceMode: "local" | "cloud" = "local",+) {+ return renderHook(+ () =>+ useTaskCreation({+ editorRef: editorHandle(content),+ sessionId: "session-1",+ selectedDirectory: "/repo",+ allowNoRepo: true,+ workspaceMode,+ editorIsEmpty: false,+ }),+ { wrapper },+ );+}++describe("useTaskCreation prompt records", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ createTaskMock.mockReset();+ usePendingTaskPromptStore.setState({ byKey: {}, _hasHydrated: true });+ useTaskInputPrefillStore.setState({ prefill: {} });+ });++ it.each(["local", "cloud"] as const)(+ "keeps the submitted prompt visible after successful %s creation until the chat takes over",+ async (workspaceMode) => {+ const brief = textToContent("Check the build");+ createTaskMock.mockImplementationOnce(async (_input, onTaskReady) => {+ const output = { task: fakeTask(), workspace: null };+ onTaskReady?.(output);+ return { success: true, data: output };+ });++ const { result } = renderTaskCreation(brief, workspaceMode);+ await act(async () => {+ expect(await result.current.handleSubmit()).toBe(true);+ });++ expect(pendingTaskPromptStoreApi.get("task-1")?.contentXml).toBe(+ contentToXml(brief).trim(),+ );+ expect(pendingTaskPromptStoreApi.getRecoverableNewestFirst()).toEqual([]);+ },+ );++ it("keeps the typed brief, not the kickoff preamble, in the recovery record after a late autoresearch failure", async () => {+ const brief = textToContent("Optimize the login flow");+ // Mirrors handleAutoresearchSubmit: the request content wraps the brief.+ const override: EditorContent = {+ segments: [+ { type: "text", text: `${KICKOFF_PREAMBLE}\n\n` },+ ...brief.segments,+ ],+ attachments: brief.attachments,+ };++ createTaskMock.mockImplementationOnce(async (_input, onTaskReady) => {+ // The late failure: onTaskReady already ran, so the record moved to the+ // task id and the origin tab sits on the rolled-back task.+ onTaskReady?.({ task: fakeTask(), workspace: null });+ return { success: false, error: "boom", failedStep: "create" };+ });++ const { result } = renderTaskCreation(brief);+ await act(async () => {+ await result.current.handleSubmit(override, brief);+ });++ const record = pendingTaskPromptStoreApi.get("task-1");+ expect(record?.promptText).toBe("Optimize the login flow");+ expect(record?.contentXml).toBe(contentToXml(brief).trim());+ expect(record?.contentXml).not.toContain("AUTORESEARCH");++ // Recovery stages the brief back into the composer, so a resubmit through+ // the still-armed autoresearch wrapper prepends the preamble only once.+ const { prefill } = useTaskInputPrefillStore.getState();+ expect(prefill.recoveredFromKey).toBe("task-1");+ expect(prefill.initialContent).toEqual(+ expect.objectContaining({ segments: brief.segments }),+ );+ });++ it("derives the record from the composer content on a plain submit", async () => {+ const brief = textToContent("Fix the flaky test");++ createTaskMock.mockImplementationOnce(async (_input, onTaskReady) => {+ onTaskReady?.({ task: fakeTask(), workspace: null });+ return { success: false, error: "boom", failedStep: "create" };+ });++ const { result } = renderTaskCreation(brief);+ await act(async () => {+ await result.current.handleSubmit();+ });++ expect(pendingTaskPromptStoreApi.get("task-1")?.contentXml).toBe(+ contentToXml(brief).trim(),+ );+ });+});diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.tsindex f5294bda867c..aec35d5e5b04 100644--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts@@ -1,4 +1,3 @@-import { getIsOnline } from "@posthog/core/connectivity/connectivityStore";import { partitionLocalMcpServersForRun } from "@posthog/core/local-mcp/localMcpImport";import {getErrorTitle,@@ -9,6 +8,7 @@ import {TASK_SERVICE,type TaskService,} from "@posthog/core/task-detail/taskService";+import { pendingPromptRecordFromContent } from "@posthog/core/tasks/pendingPrompts";import { useService } from "@posthog/di/react";import type { HostTrpcClient } from "@posthog/host-router/client";import { useHostTRPC, useHostTRPCClient } from "@posthog/host-router/react";@@ -22,10 +22,7 @@ import {type WorkspaceMode,} from "@posthog/shared";import type { ExecutionMode, Task } from "@posthog/shared/domain-types";-import {- getCurrentBrowserTabId,- navigateBrowserTab,-} from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";+import { getCurrentBrowserTabId } from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";import { useTaskChannels } from "@posthog/ui/features/canvas/hooks/useTaskChannels";import { useTaskRepositoryDraftStore } from "@posthog/ui/features/canvas/stores/taskRepositoryDraftStore";import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";@@ -33,9 +30,8 @@ import {subscriptionModelAccess,useAdapterSubscription,} from "@posthog/ui/features/settings/adapterSubscription";-import { waitForComposerExit } from "@posthog/ui/features/task-detail/newTaskComposerTransition";+import { settleFailedPromptRecord } from "@posthog/ui/features/task-detail/pendingPromptActions";import { useTaskInputPrefillStore } from "@posthog/ui/features/task-detail/stores/taskInputPrefillStore";-import { navigateToTaskPending } from "@posthog/ui/router/navigationBridge";import { openTask } from "@posthog/ui/router/useOpenTask";import { useQuery, useQueryClient } from "@tanstack/react-query";import { useCallback, useState } from "react";@@ -53,7 +49,6 @@ import { assertCloudUsageAvailable } from "../../billing/preflightCloudUsage";import { useUsageLimitStore } from "../../billing/usageLimitStore";import { useLocalMcpCloudServers } from "../../local-mcp/useLocalMcpCloudServers";import {- contentToPlainText,contentToXml,type EditorContent,extractFilePaths,@@ -128,10 +123,11 @@ interface UseTaskCreationOptions {interface UseTaskCreationReturn {isCreatingTask: boolean;- /** The task is on its way; the composer fades out before the chat replaces it. */- isExitingComposer: boolean;canSubmit: boolean;- handleSubmit: (contentOverride?: EditorContent) => Promise<boolean>;+ handleSubmit: (+ contentOverride?: EditorContent,+ promptContent?: EditorContent,+ ) => Promise<boolean>;additionalDirectories: string[];setAdditionalDirectories: (next: string[]) => void;}@@ -223,7 +219,6 @@ export function useTaskCreation({onTaskCreatedEffect,}: UseTaskCreationOptions): UseTaskCreationReturn {const [isCreatingTask, setIsCreatingTask] = useState(false);- const [isExitingComposer, setIsExitingComposer] = useState(false);const hostClient = useHostTRPCClient();const codexSubscription = useAdapterSubscription("codex");const claudeSubscription = useAdapterSubscription("claude");@@ -277,7 +272,15 @@ export function useTaskCreation({const canSubmit = !!editorRef.current && canSubmitBase && !editorIsEmpty;const handleSubmit = useCallback(- async (contentOverride?: EditorContent): Promise<boolean> => {+ async (+ contentOverride?: EditorContent,+ /**+ * The composer content the person typed, when a wrapper transformed it+ * for the task request. The prompt record and history restore this, so+ * generated request text never reaches the composer on recovery.+ */+ promptContent?: EditorContent,+ ): Promise<boolean> => {const editor = editorRef.current;if (!editor) return false;const allowSubmit = contentOverride ? canSubmitBase : canSubmit;@@ -288,7 +291,10 @@ export function useTaskCreation({// the exact prompt and tab that the user submitted.const originTabId = getCurrentBrowserTabId();const content = contentOverride ?? editor.getContent();- const plainPromptText = contentToPlainText(content).trim();+ const promptRecord = pendingPromptRecordFromContent(+ promptContent ?? content,+ );+ const plainPromptText = promptRecord.promptText;const serializedContent = contentToXml(content).trim();const filePaths = extractFilePaths(content);@@ -297,7 +303,6 @@ export function useTaskCreation({setIsCreatingTask(true);try {- // Block over-limit cloud creation before the pending view so it doesn't flash.if (workspaceMode === "cloud" && !(await assertCloudUsageAvailable())) {return false;}@@ -313,9 +318,8 @@ export function useTaskCreation({}// Confirm a couple of worktree branch situations before starting the- // task. Done before the pending view so a dialog (and a cancel) don't- // leave a half-started task on screen. Reusing an existing worktree takes- // priority over checking out a remote branch.+ // task. Reusing an existing worktree takes priority over checking out a+ // remote branch.let allowRemoteBranchCheckout = false;let reuseExistingWorktree = false;if (workspaceMode === "worktree" && branch && selectedDirectory) {@@ -360,41 +364,34 @@ export function useTaskCreation({}}- const shouldShowPendingView = !onTaskCreated && !!plainPromptText;- const pendingTaskKey = shouldShowPendingView+ const shouldPersistPromptRecord = !onTaskCreated && !!plainPromptText;+ const pendingTaskKey = shouldPersistPromptRecord? generatePendingTaskKey(): null;if (pendingTaskKey) {pendingTaskPromptStoreApi.set(pendingTaskKey, {- promptText: plainPromptText,- attachments: (content.attachments ?? []).map((a) => ({- id: a.id,- label: a.label,- })),+ promptText: promptRecord.promptText,+ attachments: promptRecord.attachments,// The serialized content restores file chips and attachments on// recovery, so an interrupted prompt comes back whole, not as bare// text.- contentXml: serializedContent,+ contentXml: promptRecord.contentXml,// Reopen recovery in the space the prompt was submitted in.channelId: channelId ?? undefined,});- // Fade the composer out before the chat fades in, so the phases- // hand over instead of cutting.- setIsExitingComposer(true);- await waitForComposerExit();- navigateBrowserTab(- originTabId,- {- href: `/tasks/pending/${pendingTaskKey}`,- title: "New task",- },- () => navigateToTaskPending(pendingTaskKey),- );}let createdTaskId: string | undefined;+ const settlePromptRecord = () => {+ settleFailedPromptRecord({+ recordKey: pendingTaskKey,+ createdTaskId,+ originTabId,+ });+ };+try {if (!contentOverride) {if (plainPromptText) {@@ -550,7 +547,9 @@ export function useTaskCreation({pendingTaskPromptStoreApi.clear(pendingTaskKey);}if (createdTaskId) {- pendingTaskPromptStoreApi.clear(createdTaskId);+ // Cloud creation succeeds before the transcript arrives.+ // SessionView clears the prompt when initialization ends.+ pendingTaskPromptStoreApi.markSubmitted(createdTaskId);}}setAdditionalDirectoriesOverride(null);@@ -603,34 +602,7 @@ export function useTaskCreation({error: result.error,});}- if (pendingTaskKey) {- // Never drop the prompt on failure. Keep the record and flag it- // interrupted so the pending view offers to recover or discard it,- // instead of navigating back to a composer that may not have it.- const interruptedKey = createdTaskId ?? pendingTaskKey;- // Read connectivity live, not the value captured at submit: the- // submit guard forced isOnline true then, so a connection dropped- // during setup only shows in the store now.- pendingTaskPromptStoreApi.markInterrupted(- interruptedKey,- getIsOnline() ? "failed" : "offline",- );- // If onTaskReady already navigated the origin tab to- // /tasks/$taskId (the worktree path notifies ready before later- // steps), a rolled-back task leaves it on a dead detail view.- // Return it to the pending route for the moved record so the- // Recover/Discard actions actually show.- if (createdTaskId) {- navigateBrowserTab(- originTabId,- {- href: `/tasks/pending/${interruptedKey}`,- title: "New task",- },- () => navigateToTaskPending(interruptedKey),- );- }- }+ settlePromptRecord();}return result.success;} catch (error) {@@ -639,31 +611,11 @@ export function useTaskCreation({});toastError("Failed to create task", error);log.error("Unexpected error during task creation", { error });- if (pendingTaskKey) {- // Keep the prompt recoverable from the pending view.- const interruptedKey = createdTaskId ?? pendingTaskKey;- // Live connectivity, not the submit-time value, so a drop during- // setup is classified as offline (see the failed-result branch).- pendingTaskPromptStoreApi.markInterrupted(- interruptedKey,- getIsOnline() ? "failed" : "offline",- );- // A throw after onTaskReady leaves the origin tab on the- // rolled-back task's detail view; return it to the pending route so- // recovery stays reachable.- if (createdTaskId) {- navigateBrowserTab(- originTabId,- { href: `/tasks/pending/${interruptedKey}`, title: "New task" },- () => navigateToTaskPending(interruptedKey),- );- }- }+ settlePromptRecord();return false;}} finally {setIsCreatingTask(false);- setIsExitingComposer(false);}},[@@ -722,7 +674,6 @@ export function useTaskCreation({return {isCreatingTask,- isExitingComposer,canSubmit,handleSubmit,additionalDirectories,diff --git a/products/desktop/packages/ui/src/features/task-detail/newTaskComposerTransition.ts b/products/desktop/packages/ui/src/features/task-detail/newTaskComposerTransition.tsdeleted file mode 100644index eb0952b3c15a..000000000000--- a/products/desktop/packages/ui/src/features/task-detail/newTaskComposerTransition.ts+++ /dev/null@@ -1,12 +0,0 @@-/**- * How long the new-task composer takes to fade out once its task has been- * submitted, and how long the pending chat takes to fade back in over it.- */-export const NEW_TASK_COMPOSER_FADE_MS = 160;--/** Resolves once the composer's fade-out has had its full window. */-export function waitForComposerExit(): Promise<void> {- return new Promise((resolve) =>- setTimeout(resolve, NEW_TASK_COMPOSER_FADE_MS),- );-}diff --git a/products/desktop/packages/ui/src/features/task-detail/pendingPromptActions.test.ts b/products/desktop/packages/ui/src/features/task-detail/pendingPromptActions.test.tsindex 5d63a1a6fd98..7a7485c60a83 100644--- a/products/desktop/packages/ui/src/features/task-detail/pendingPromptActions.test.ts+++ b/products/desktop/packages/ui/src/features/task-detail/pendingPromptActions.test.ts@@ -1,3 +1,5 @@+import { browserTabsStore } from "@posthog/core/browser-tabs/browserTabsStore";+import type { TabsSnapshot } from "@posthog/shared";import { useTaskInputPrefillStore } from "@posthog/ui/features/task-detail/stores/taskInputPrefillStore";import {pendingTaskPromptStoreApi,@@ -5,13 +7,43 @@ import {} from "@posthog/ui/shell/pendingTaskPromptStore";import { afterEach, beforeEach, describe, expect, it } from "vitest";import {- discardPendingPrompt,recoverPendingPrompt,+ settleFailedPromptRecord,} from "./pendingPromptActions";function reset(): void {usePendingTaskPromptStore.setState({ byKey: {}, _hasHydrated: true });useTaskInputPrefillStore.setState({ prefill: {} });+ browserTabsStore.getState().setSnapshot({ windows: [], tabs: [] });+}++function seedTabs(tabs: TabsSnapshot["tabs"]): void {+ browserTabsStore.getState().setSnapshot({ windows: [], tabs });+}++function backgroundTab(id: string): TabsSnapshot["tabs"][number] {+ return {+ id,+ windowId: "win-1",+ href: "/activity",+ viewState: null,+ dashboardId: null,+ taskId: null,+ channelId: null,+ channelSection: null,+ appView: null,+ position: 0,+ lastActiveAt: 0,+ createdAt: 0,+ };+}++function seedPrompt(key: string, promptText = "fix @a.ts"): void {+ pendingTaskPromptStoreApi.set(key, {+ promptText,+ attachments: [],+ contentXml: 'fix <file path="src/a.ts" />',+ });}describe("pendingPromptActions", () => {@@ -19,11 +51,7 @@ describe("pendingPromptActions", () => {afterEach(reset);it("stages the full prompt and keeps the record until the composer consumes it", () => {- pendingTaskPromptStoreApi.set("k1", {- promptText: "fix @a.ts",- attachments: [],- contentXml: 'fix <file path="src/a.ts" />',- });+ seedPrompt("k1");const recovered = recoverPendingPrompt("k1");@@ -48,12 +76,97 @@ describe("pendingPromptActions", () => {).toBeUndefined();});- it("discards the prompt and opens an empty composer", () => {- pendingTaskPromptStoreApi.set("k1", { promptText: "x", attachments: [] });- discardPendingPrompt("k1");+ it("recovers into the submitting tab instead of the active one", () => {+ seedTabs([backgroundTab("tab-bg")]);+ seedPrompt("k1");++ const recovered = recoverPendingPrompt("k1", "tab-bg");++ expect(recovered).toBe(true);+ // The background tab gets the composer as its durable target; the active+ // tab's composer is untouched, so no prefill is staged here.+ expect(+ useTaskInputPrefillStore.getState().prefill.initialContent,+ ).toBeUndefined();+ expect(browserTabsStore.getState().snapshot.tabs[0].href).toBe("/new");+ // The record survives until a composer applies it.+ expect(pendingTaskPromptStoreApi.get("k1")).toBeDefined();+ });++ it("leaves a closed submitting tab alone and keeps the record", () => {+ seedPrompt("k1");++ const recovered = recoverPendingPrompt("k1", "tab-gone");++ expect(recovered).toBe(true);+ expect(+ useTaskInputPrefillStore.getState().prefill.initialContent,+ ).toBeUndefined();+ // Next-launch recovery can still restore the prompt.+ expect(pendingTaskPromptStoreApi.get("k1")).toBeDefined();+ });++ it.each([+ { name: "open", tabs: [backgroundTab("tab-1")], recordSurvives: false },+ { name: "closed", tabs: [], recordSurvives: true },+ ])(+ "on an early failure it clears the record only while the origin tab keeps the draft ($name tab)",+ ({ tabs, recordSurvives }) => {+ seedTabs(tabs);+ seedPrompt("k1");++ settleFailedPromptRecord({+ recordKey: "k1",+ originTabId: "tab-1",+ });++ expect(pendingTaskPromptStoreApi.get("k1") !== undefined).toBe(+ recordSurvives,+ );+ },+ );++ it("on an early failure with tabs off it clears the record, because the composer still holds the draft", () => {+ seedPrompt("k1");++ settleFailedPromptRecord({ recordKey: "k1", originTabId: null });+expect(pendingTaskPromptStoreApi.get("k1")).toBeUndefined();+ });++ it("on a late failure it recovers the prompt into the submitting tab and keeps the record", () => {+ seedPrompt("task-123");++ settleFailedPromptRecord({+ recordKey: "k1",+ createdTaskId: "task-123",+ originTabId: null,+ });++ expect(pendingTaskPromptStoreApi.get("task-123")).toBeDefined();+ const { prefill } = useTaskInputPrefillStore.getState();+ expect(prefill.recoveredFromKey).toBe("task-123");+ });++ it("on a late failure with a closed submitting tab it keeps the record for next launch", () => {+ seedPrompt("task-123");++ settleFailedPromptRecord({+ recordKey: "k1",+ createdTaskId: "task-123",+ originTabId: "tab-gone",+ });++ expect(pendingTaskPromptStoreApi.get("task-123")).toBeDefined();expect(useTaskInputPrefillStore.getState().prefill.initialContent,).toBeUndefined();});++ it("settles nothing without a record key", () => {+ settleFailedPromptRecord({ recordKey: null, originTabId: null });+ expect(+ useTaskInputPrefillStore.getState().prefill.recoveredFromKey,+ ).toBeUndefined();+ });});diff --git a/products/desktop/packages/ui/src/features/task-detail/pendingPromptActions.ts b/products/desktop/packages/ui/src/features/task-detail/pendingPromptActions.tsindex 1fd51e5744f0..8f508de9104e 100644--- a/products/desktop/packages/ui/src/features/task-detail/pendingPromptActions.ts+++ b/products/desktop/packages/ui/src/features/task-detail/pendingPromptActions.ts@@ -1,31 +1,75 @@import { pendingPromptToContent } from "@posthog/core/tasks/pendingPrompts";+import {+ isBrowserTabOpen,+ navigateBrowserTab,+} from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";import { openTaskInput } from "@posthog/ui/router/useOpenTask";import { pendingTaskPromptStoreApi } from "@posthog/ui/shell/pendingTaskPromptStore";/**- * Drop an interrupted prompt back into the new-task composer. The durable- * record is kept and handed to the composer as `recoveredFromKey`; the composer- * clears it only once it has applied the content (see TaskInput). So a crash- * before the composer mounts leaves the record intact for the next launch to- * recover, never a cleared record whose content lived only in memory.+ * Drop a failed or interrupted prompt back into the new-task composer. The+ * durable record is kept and handed to the composer as `recoveredFromKey`; the+ * composer clears it only once it has applied the content (see TaskInput). So a+ * crash before the composer mounts leaves the record intact for the next launch+ * to recover, never a cleared record whose content lived only in memory.* Returns false when the record is already gone (nothing to recover).+ *+ * `originTabId` routes the recovery to the tab that submitted the prompt.+ * Without it the composer opens in whichever tab is currently active, which can+ * be a tab the submitter never looked at.*/-export function recoverPendingPrompt(key: string): boolean {+export function recoverPendingPrompt(+ key: string,+ originTabId?: string | null,+): boolean {const record = pendingTaskPromptStoreApi.get(key);if (!record) return false;- openTaskInput({+ const options = {initialContent: pendingPromptToContent(record),recoveredFromKey: key,// Reopen in the space the prompt was submitted in, not whatever is current....(record.channelId? { channelId: record.channelId }: { unscoped: true }),- });+ };+ // The active tab navigates now; a background tab stores the composer as its+ // durable target and picks up the prefill when the user returns to it; a+ // closed tab does nothing and the record stays for next-launch recovery.+ navigateBrowserTab(+ originTabId ?? null,+ {+ href: record.channelId ? `/spaces/${record.channelId}/new` : "/new",+ title: "New task",+ channelId: record.channelId ?? null,+ },+ () => openTaskInput(options),+ );return true;}-/** Discard an interrupted prompt and open a fresh, empty new-task composer. */-export function discardPendingPrompt(key: string): void {- pendingTaskPromptStoreApi.clear(key);- openTaskInput();+/**+ * Settle the pending-prompt record after a failed task creation.+ *+ * With a task id, onTaskReady already navigated the origin tab onto the+ * rolled-back task, so recovery sends that tab back to the composer with the+ * prompt. Without one the origin composer still holds the draft, so the record+ * would only duplicate it at the next launch and is cleared — unless the tab+ * is gone, because closing a tab clears its draft and the record is then the+ * only surviving copy. Kept records surface again through+ * PendingPromptRecovery on the next launch.+ */+export function settleFailedPromptRecord(args: {+ recordKey: string | null;+ createdTaskId?: string;+ originTabId: string | null;+}): void {+ const { recordKey, createdTaskId, originTabId } = args;+ if (!recordKey) return;+ if (createdTaskId) {+ recoverPendingPrompt(createdTaskId, originTabId);+ return;+ }+ if (isBrowserTabOpen(originTabId)) {+ pendingTaskPromptStoreApi.clear(recordKey);+ }}diff --git a/products/desktop/packages/ui/src/router/navigationBridge.ts b/products/desktop/packages/ui/src/router/navigationBridge.tsindex 4cebcbcd6fcd..f6dbe4e0e8af 100644--- a/products/desktop/packages/ui/src/router/navigationBridge.ts+++ b/products/desktop/packages/ui/src/router/navigationBridge.ts@@ -31,13 +31,6 @@ export function navigateToPullRequestView(prUrl: string): void {});}-export function navigateToTaskPending(key: string): void {- void getRouterOrNull()?.navigate({- to: "/tasks/pending/$key",- params: { key },- });-}-export function navigateToActivity(): void {void getRouterOrNull()?.navigate({ to: "/activity" });}diff --git a/products/desktop/packages/ui/src/router/routeTree.gen.ts b/products/desktop/packages/ui/src/router/routeTree.gen.tsindex 93fd4dd7a77a..330cf25cc80c 100644--- a/products/desktop/packages/ui/src/router/routeTree.gen.ts+++ b/products/desktop/packages/ui/src/router/routeTree.gen.ts@@ -49,7 +49,6 @@ import { Route as AgentsScoutsIndexRouteImport } from './routes/agents/scouts.inimport { Route as ShellSpacesIndexRouteImport } from './routes/_shell/spaces/index'import { Route as ShellSettingsIndexRouteImport } from './routes/_shell/settings/index'import { Route as ShellFeedsIndexRouteImport } from './routes/_shell/feeds/index'-import { Route as TasksPendingKeyRouteImport } from './routes/tasks/pending.$key'import { Route as LoopsLoopIdEditRouteImport } from './routes/loops/$loopId/edit'import { Route as InboxRunsReportIdRouteImport } from './routes/inbox/runs.$reportId'import { Route as InboxReportsReportIdRouteImport } from './routes/inbox/reports.$reportId'@@ -272,11 +271,6 @@ const ShellFeedsIndexRoute = ShellFeedsIndexRouteImport.update({path: '/feeds/',getParentRoute: () => ShellRoute,} as any)-const TasksPendingKeyRoute = TasksPendingKeyRouteImport.update({- id: '/tasks/pending/$key',- path: '/tasks/pending/$key',- getParentRoute: () => rootRouteImport,-} as any)const LoopsLoopIdEditRoute = LoopsLoopIdEditRouteImport.update({id: '/edit',path: '/edit',@@ -440,7 +434,6 @@ export interface FileRoutesByFullPath {'/inbox/reports/$reportId': typeof InboxReportsReportIdRoute'/inbox/runs/$reportId': typeof InboxRunsReportIdRoute'/loops/$loopId/edit': typeof LoopsLoopIdEditRoute- '/tasks/pending/$key': typeof TasksPendingKeyRoute'/feeds/': typeof ShellFeedsIndexRoute'/settings/': typeof ShellSettingsIndexRoute'/spaces/': typeof ShellSpacesIndexRoute@@ -495,7 +488,6 @@ export interface FileRoutesByTo {'/inbox/reports/$reportId': typeof InboxReportsReportIdRoute'/inbox/runs/$reportId': typeof InboxRunsReportIdRoute'/loops/$loopId/edit': typeof LoopsLoopIdEditRoute- '/tasks/pending/$key': typeof TasksPendingKeyRoute'/feeds': typeof ShellFeedsIndexRoute'/settings': typeof ShellSettingsIndexRoute'/spaces': typeof ShellSpacesIndexRoute@@ -561,7 +553,6 @@ export interface FileRoutesById {'/inbox/reports/$reportId': typeof InboxReportsReportIdRoute'/inbox/runs/$reportId': typeof InboxRunsReportIdRoute'/loops/$loopId/edit': typeof LoopsLoopIdEditRoute- '/tasks/pending/$key': typeof TasksPendingKeyRoute'/_shell/feeds/': typeof ShellFeedsIndexRoute'/_shell/settings/': typeof ShellSettingsIndexRoute'/_shell/spaces/': typeof ShellSpacesIndexRoute@@ -627,7 +618,6 @@ export interface FileRouteTypes {| '/inbox/reports/$reportId'| '/inbox/runs/$reportId'| '/loops/$loopId/edit'- | '/tasks/pending/$key'| '/feeds/'| '/settings/'| '/spaces/'@@ -682,7 +672,6 @@ export interface FileRouteTypes {| '/inbox/reports/$reportId'| '/inbox/runs/$reportId'| '/loops/$loopId/edit'- | '/tasks/pending/$key'| '/feeds'| '/settings'| '/spaces'@@ -747,7 +736,6 @@ export interface FileRouteTypes {| '/inbox/reports/$reportId'| '/inbox/runs/$reportId'| '/loops/$loopId/edit'- | '/tasks/pending/$key'| '/_shell/feeds/'| '/_shell/settings/'| '/_shell/spaces/'@@ -787,7 +775,6 @@ export interface RootRouteChildren {CodeIndexRoute: typeof CodeIndexRouteLoopsIndexRoute: typeof LoopsIndexRouteWebsiteIndexRoute: typeof WebsiteIndexRoute- TasksPendingKeyRoute: typeof TasksPendingKeyRoute}declare module '@tanstack/react-router' {@@ -1072,13 +1059,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ShellFeedsIndexRouteImportparentRoute: typeof ShellRoute}- '/tasks/pending/$key': {- id: '/tasks/pending/$key'- path: '/tasks/pending/$key'- fullPath: '/tasks/pending/$key'- preLoaderRoute: typeof TasksPendingKeyRouteImport- parentRoute: typeof rootRouteImport- }'/loops/$loopId/edit': {id: '/loops/$loopId/edit'path: '/edit'@@ -1443,7 +1423,6 @@ const rootRouteChildren: RootRouteChildren = {CodeIndexRoute: CodeIndexRoute,LoopsIndexRoute: LoopsIndexRoute,WebsiteIndexRoute: WebsiteIndexRoute,- TasksPendingKeyRoute: TasksPendingKeyRoute,}export const routeTree = rootRouteImport._addFileChildren(rootRouteChildren)diff --git a/products/desktop/packages/ui/src/router/routes/__root.tsx b/products/desktop/packages/ui/src/router/routes/__root.tsxindex 9027ea01a256..8b07802b9a7d 100644--- a/products/desktop/packages/ui/src/router/routes/__root.tsx+++ b/products/desktop/packages/ui/src/router/routes/__root.tsx@@ -486,9 +486,7 @@ function RootLayout() {tasks={visualTaskOrder}activeTaskId={activeTaskId}allTasks={tasks ?? []}- isOnNewTask={- view.type === "task-input" || view.type === "task-pending"- }+ isOnNewTask={view.type === "task-input"}onNavigateToTask={openTask}onNewTask={openTaskInput}/>diff --git a/products/desktop/packages/ui/src/router/routes/tasks/pending.$key.tsx b/products/desktop/packages/ui/src/router/routes/tasks/pending.$key.tsxdeleted file mode 100644index adcc240ba9da..000000000000--- a/products/desktop/packages/ui/src/router/routes/tasks/pending.$key.tsx+++ /dev/null@@ -1,11 +0,0 @@-import { TaskPendingView } from "@posthog/ui/features/task-detail/components/TaskPendingView";-import { createFileRoute } from "@tanstack/react-router";--export const Route = createFileRoute("/tasks/pending/$key")({- component: TaskPendingRoute,-});--function TaskPendingRoute() {- const { key } = Route.useParams();- return <TaskPendingView pendingTaskKey={key} />;-}diff --git a/products/desktop/packages/ui/src/router/useAppView.ts b/products/desktop/packages/ui/src/router/useAppView.tsindex a4ff2e3b3bd0..b30c2edebf51 100644--- a/products/desktop/packages/ui/src/router/useAppView.ts+++ b/products/desktop/packages/ui/src/router/useAppView.ts@@ -9,7 +9,6 @@ import { getCurrentMatches } from "./navigationBridge";export type AppViewType =| "task-detail"- | "task-pending"| "task-input"| "folder-settings"| "activity"@@ -29,7 +28,6 @@ export interface AppView {taskId?: string;folderId?: string;folderRepository?: string;- pendingTaskKey?: string;taskInputRequestId?: string;initialPrompt?: string;initialContent?: EditorContent;@@ -59,8 +57,6 @@ function deriveFromMatches(matches: Match[]): AppView {// their own query hooks (e.g. useTasks) keyed on `taskId`.return { type: "task-detail", taskId };}- case "/tasks/pending/$key":- return { type: "task-pending", pendingTaskKey: last.params.key };case "/new":return { type: "task-input" };case "/folders/$folderId":diff --git a/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.test.ts b/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.test.tsindex 10cd8a4873f2..5b3dac33f4aa 100644--- a/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.test.ts+++ b/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.test.ts@@ -49,20 +49,7 @@ describe("pendingTaskPromptStore", () => {expect(pendingTaskPromptStoreApi.get("k1")).toBeUndefined();});- it("flags an existing entry interrupted so the pending view can recover it", () => {- pendingTaskPromptStoreApi.set("k1", { promptText: "hi", attachments: [] });- pendingTaskPromptStoreApi.markInterrupted("k1", "offline");- expect(pendingTaskPromptStoreApi.get("k1")?.interruptReason).toBe(- "offline",- );- });-- it("never resurrects a discarded prompt when marking a missing key", () => {- pendingTaskPromptStoreApi.markInterrupted("gone", "failed");- expect(pendingTaskPromptStoreApi.get("gone")).toBeUndefined();- });-- it("returns every surviving entry newest-first for recovery", () => {+ it("recovers unsent prompts newest-first while keeping submitted prompts available for chat", () => {pendingTaskPromptStoreApi.set("old", {promptText: "old",attachments: [],@@ -75,10 +62,12 @@ describe("pendingTaskPromptStore", () => {promptText: "new",attachments: [],});+ pendingTaskPromptStoreApi.markSubmitted("mid");- const recovered = pendingTaskPromptStoreApi.getAllNewestFirst();+ const recovered = pendingTaskPromptStoreApi.getRecoverableNewestFirst();- expect(recovered.map((r) => r.key)).toEqual(["new", "mid", "old"]);+ expect(recovered.map((r) => r.key)).toEqual(["new", "old"]);+ expect(pendingTaskPromptStoreApi.get("mid")?.promptText).toBe("mid");});it("caps stored prompts to the newest, dropping the oldest", () => {@@ -89,7 +78,7 @@ describe("pendingTaskPromptStore", () => {});}- const recovered = pendingTaskPromptStoreApi.getAllNewestFirst();+ const recovered = pendingTaskPromptStoreApi.getRecoverableNewestFirst();expect(recovered).toHaveLength(20);expect(pendingTaskPromptStoreApi.get("k0")).toBeUndefined();diff --git a/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.ts b/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.tsindex 6579efd0cf4b..a5b080346f56 100644--- a/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.ts+++ b/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.ts@@ -1,4 +1,3 @@-import type { PendingPromptInterruptReason } from "@posthog/core/tasks/pendingPrompts";import type { UserMessageAttachment } from "@posthog/ui/features/sessions/userMessageTypes";import { electronStorage } from "@posthog/ui/shell/rendererStorage";import { create } from "zustand";@@ -13,35 +12,28 @@ export interface PendingTaskPrompt {* field existed; recovery falls back to promptText for those.*/contentXml?: string;- /**- * Set when task setup failed and left the prompt unsent. Presence flips the- * pending view from "starting" to the recoverable interrupted state. Cleared- * only by delivery (success) or the user discarding the prompt.- */- interruptReason?: PendingPromptInterruptReason;/*** Space the prompt was submitted in, so recovery reopens it there instead of* whatever space is current. Absent means it was submitted unscoped.*/channelId?: string;+ submitted?: boolean;createdAt: number;}type PendingTaskPromptInput = Omit<PendingTaskPrompt,- "createdAt" | "interruptReason"+ "createdAt" | "submitted">;interface PendingTaskPromptStore {byKey: Record<string, PendingTaskPrompt>;- handoffs: Record<string, PendingTaskPrompt>;_hasHydrated: boolean;setHasHydrated: (hydrated: boolean) => void;set: (key: string, prompt: PendingTaskPromptInput) => void;get: (key: string) => PendingTaskPrompt | undefined;move: (fromKey: string, toKey: string) => void;- clearHandoff: (key: string) => void;- markInterrupted: (key: string, reason: PendingPromptInterruptReason) => void;+ markSubmitted: (key: string) => void;clear: (key: string) => void;}@@ -49,7 +41,6 @@ export const usePendingTaskPromptStore = create<PendingTaskPromptStore>()(persist((set, get) => ({byKey: {},- handoffs: {},_hasHydrated: false,setHasHydrated: (hydrated) => set({ _hasHydrated: hydrated }),set: (key, prompt) =>@@ -70,31 +61,15 @@ export const usePendingTaskPromptStore = create<PendingTaskPromptStore>()(return state;}const { [fromKey]: _removed, ...rest } = state.byKey;- return {- byKey: { ...rest, [toKey]: entry },- handoffs: { ...state.handoffs, [fromKey]: entry },- };+ return { byKey: { ...rest, [toKey]: entry } };});},- clearHandoff: (key) =>- set((state) => {- if (!(key in state.handoffs)) {- return state;- }- const { [key]: _removed, ...rest } = state.handoffs;- return { handoffs: rest };- }),- markInterrupted: (key, reason) =>+ markSubmitted: (key) =>set((state) => {const entry = state.byKey[key];- if (!entry) {- return state;- }+ if (!entry || entry.submitted) return state;return {- byKey: {- ...state.byKey,- [key]: { ...entry, interruptReason: reason },- },+ byKey: { ...state.byKey, [key]: { ...entry, submitted: true } },};}),clear: (key) =>@@ -132,13 +107,13 @@ export const pendingTaskPromptStoreApi = {get: (key: string) => usePendingTaskPromptStore.getState().get(key),move: (fromKey: string, toKey: string) =>usePendingTaskPromptStore.getState().move(fromKey, toKey),- clearHandoff: (key: string) =>- usePendingTaskPromptStore.getState().clearHandoff(key),- markInterrupted: (key: string, reason: PendingPromptInterruptReason) =>- usePendingTaskPromptStore.getState().markInterrupted(key, reason),+ markSubmitted: (key: string) =>+ usePendingTaskPromptStore.getState().markSubmitted(key),clear: (key: string) => usePendingTaskPromptStore.getState().clear(key),- getAllNewestFirst: (): RecoverablePendingPrompt[] =>- listPendingPromptsNewestFirst(usePendingTaskPromptStore.getState().byKey),+ getRecoverableNewestFirst: (): RecoverablePendingPrompt[] =>+ listPendingPromptsNewestFirst(+ usePendingTaskPromptStore.getState().byKey,+ ).filter(({ prompt }) => !prompt.submitted),whenHydrated: (): Promise<void> => {if (usePendingTaskPromptStore.getState()._hasHydrated) {return Promise.resolve();