: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): keep task prompts recoverable when setup is interrupted (#90578)
Adam Leith03e96b46b558
diff --git a/products/desktop/packages/core/src/tasks/pendingPrompts.test.ts b/products/desktop/packages/core/src/tasks/pendingPrompts.test.tsindex 28d54e214733..d2b3a40ae44b 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,+ pendingPromptToContent,} from "./pendingPrompts";describe("pending prompts", () => {@@ -33,3 +34,23 @@ describe("pending prompts", () => {expect(buildPendingPromptKey(uuid, timestamp, entropy)).toBe(expected);});});++describe("pendingPromptToContent", () => {+ it("restores file chips from serialized content so attachments survive recovery", () => {+ const content = pendingPromptToContent({+ contentXml: 'fix <file path="src/a.ts" />',+ promptText: "fix @a.ts",+ });+ expect(content.segments).toContainEqual({+ type: "chip",+ chip: { type: "file", id: "src/a.ts", label: "src/a.ts" },+ });+ });++ it("falls back to plain text for records saved before content was captured", () => {+ const content = pendingPromptToContent({ promptText: "just text" });+ expect(content).toEqual({+ segments: [{ type: "text", text: "just text" }],+ });+ });+});diff --git a/products/desktop/packages/core/src/tasks/pendingPrompts.ts b/products/desktop/packages/core/src/tasks/pendingPrompts.tsindex 97a90c8324ec..513fa406d070 100644--- a/products/desktop/packages/core/src/tasks/pendingPrompts.ts+++ b/products/desktop/packages/core/src/tasks/pendingPrompts.ts@@ -1,5 +1,34 @@+import {+ type EditorContent,+ textToContent,+ xmlToContent,+} from "@posthog/core/message-editor/content";+export 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. */+ contentXml?: string;+ /** Plain-text fallback for records written before contentXml existed. */+ promptText: string;+}++/**+ * Reconstruct the editor content to drop back into the composer on recovery.+ * Prefers the serialized content so file chips and attachments survive; falls+ * back to plain text for records written before contentXml was captured.+ */+export function pendingPromptToContent(+ record: RecoverablePromptContent,+): EditorContent {+ const xml = record.contentXml?.trim();+ return xml ? xmlToContent(xml) : textToContent(record.promptText);+}+export interface TimestampedPendingPrompt {createdAt: number;}diff --git a/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.test.tsxindex c938df7cb433..95a2b8c98b26 100644--- a/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.test.tsx@@ -126,6 +126,7 @@ vi.mock("@tanstack/react-router", () => ({}),}));+import { useTaskInputPrefillStore } from "@posthog/ui/features/task-detail/stores/taskInputPrefillStore";import { SpaceNewTask } from "./SpaceNewTask";function renderNewTask() {@@ -143,6 +144,7 @@ describe("SpaceNewTask context panel", () => {useContextLayerFlag.mockReturnValue(false);useChannelWikiContext.mockReturnValue(NO_WIKI_PAGE);taskInputProps.mockReset();+ useTaskInputPrefillStore.setState({ prefill: {} });});it("blocks submission while the enabled wiki page is unresolved", () => {@@ -216,6 +218,41 @@ describe("SpaceNewTask context panel", () => {);});+ // Recovery routes an interrupted prompt through this composer under the+ // channels layout. It must forward the full content (chips + attachments) and+ // the record key, or the prompt lands in an empty composer and the durable+ // record is never cleared.+ it("forwards a recovered prompt's content and record key into the composer", () => {+ useFolderInstructions.mockReturnValue({ data: undefined });+ const initialContent = {+ segments: [+ { type: "text" as const, text: "restore me" },+ {+ type: "chip" as const,+ chip: { type: "file" as const, id: "src/app.ts", label: "app.ts" },+ },+ ],+ attachments: [{ id: "att-1", label: "diagram.png" }],+ };+ useTaskInputPrefillStore.setState({+ prefill: {+ initialContent,+ recoveredFromKey: "pending-key",+ requestId: "req-1",+ },+ });++ renderNewTask();++ expect(taskInputProps).toHaveBeenLastCalledWith(+ expect.objectContaining({+ initialContent,+ recoveredFromKey: "pending-key",+ initialPromptKey: "req-1",+ }),+ );+ });+it("passes the space's repository defaults so cloud tasks can span repos", () => {useFolderInstructions.mockReturnValue({ data: undefined });renderNewTask();diff --git a/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.tsx b/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.tsxindex c12fade02228..a2c2428ff545 100644--- a/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/SpaceNewTask.tsx@@ -157,7 +157,12 @@ export function SpaceNewTask({ channelId }: { channelId: string }) {channelRepositories={channel?.repositories}channelGithubIntegration={channel?.github_integration}// So a prompt handed to openTaskInput survives routing into a channel.+ // initialContent + recoveredFromKey carry a recovered prompt's chips+ // and attachments, and let the composer clear the durable record once+ // applied — same as the unscoped NewTaskScreen.initialPrompt={view.initialPrompt}+ initialContent={view.initialContent}+ recoveredFromKey={view.recoveredFromKey}initialPromptKey={view.taskInputRequestId}initialCloudRepository={view.initialCloudRepository}initialModel={view.initialModel}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.tsxnew file mode 100644index 000000000000..0a4793ecd34c--- /dev/null+++ b/products/desktop/packages/ui/src/features/task-detail/components/InterruptedPromptView.tsx@@ -0,0 +1,82 @@+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/NewTaskScreen.tsx b/products/desktop/packages/ui/src/features/task-detail/components/NewTaskScreen.tsxindex 8956f07ce14c..2ccdb60221c1 100644--- a/products/desktop/packages/ui/src/features/task-detail/components/NewTaskScreen.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/components/NewTaskScreen.tsx@@ -23,6 +23,8 @@ export function NewTaskScreen() {key={sessionId}sessionId={sessionId}initialPrompt={view.initialPrompt}+ initialContent={view.initialContent}+ recoveredFromKey={view.recoveredFromKey}initialPromptKey={view.taskInputRequestId}initialCloudRepository={view.initialCloudRepository}initialModel={view.initialModel}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 632fa1be1096..afd610006455 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@@ -1,4 +1,4 @@-import { openTaskInput } from "@posthog/ui/router/useOpenTask";+import { recoverPendingPrompt } from "@posthog/ui/features/task-detail/pendingPromptActions";import { logger } from "@posthog/ui/shell/logger";import { pendingTaskPromptStoreApi } from "@posthog/ui/shell/pendingTaskPromptStore";import { useEffect } from "react";@@ -29,6 +29,8 @@ async function recoverNewestPendingPrompt(): Promise<void> {log.info("Recovering an unsent prompt whose task never finished creating", {remaining: orphans.length - 1,});- pendingTaskPromptStoreApi.clear(newest.key);- openTaskInput({ initialPrompt: newest.prompt.promptText });+ // Restore the full content into the composer before clearing the record, so a+ // crash mid-recovery can't lose the prompt. Older orphans stay put and surface+ // on later launches.+ recoverPendingPrompt(newest.key);}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 0cf96a446d90..a9ac6acd1818 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@@ -52,6 +52,7 @@ import { useConnectivity } from "../../../hooks/useConnectivity";import { DotPatternBackground } from "../../../primitives/DotPatternBackground";import { toast } from "../../../primitives/toast";import { useActiveRepoStore } from "../../../shell/activeRepoStore";+import { pendingTaskPromptStoreApi } from "../../../shell/pendingTaskPromptStore";import { FOCUSABLE_SELECTOR } from "../../../utils/overlay";import { useAuthStateValue } from "../../auth/store";import { AutoresearchComposerControls } from "../../autoresearch/AutoresearchComposerControls";@@ -128,6 +129,10 @@ interface TaskInputProps {onTaskCreated?: (task: Task) => void;onTaskCreatedEffect?: (task: Task) => void;initialPrompt?: string;+ /** Full editor content to prefill (chips + attachments), preferred over initialPrompt. */+ initialContent?: EditorContent;+ /** Pending-prompt record to clear once this prefill is applied (interrupted-prompt recovery). */+ recoveredFromKey?: string;initialPromptKey?: string;initialCloudRepository?: string;initialModel?: string;@@ -196,6 +201,8 @@ export function TaskInput({onTaskCreated,onTaskCreatedEffect,initialPrompt,+ initialContent,+ recoveredFromKey,initialPromptKey,initialCloudRepository,initialModel,@@ -363,19 +370,37 @@ export function TaskInput({// Applying a prefilled prompt replaces whatever the composer had, so it must// happen exactly once per request — not again on every remount, which would- // clobber a draft the user typed in between.+ // clobber a draft the user typed in between. initialContent wins over+ // initialPrompt so a recovered prompt keeps its chips and attachments.const lastAppliedPromptKeyRef = useRef<string | null>(null);useEffect(() => {- if (!initialPrompt || !prefillRequestKey) return;+ if (!prefillRequestKey) return;+ if (!initialContent && !initialPrompt) return;if (lastAppliedPromptKeyRef.current === prefillRequestKey) return;lastAppliedPromptKeyRef.current = prefillRequestKey;- useDraftStore.getState().actions.setPendingContent(sessionId, {- segments: [{ type: "text", text: initialPrompt }],- });+ useDraftStore.getState().actions.setPendingContent(+ sessionId,+ initialContent ?? {+ segments: [{ type: "text", text: initialPrompt ?? "" }],+ },+ );+ // Clear the recovered prompt's durable record only now that its content is+ // in the composer, so an interrupted-then-recovered prompt is never lost to+ // a crash before this point.+ if (recoveredFromKey) {+ pendingTaskPromptStoreApi.clear(recoveredFromKey);+ }if (initialPromptKey) {useTaskInputPrefillStore.getState().consumePrompt(initialPromptKey);}- }, [initialPrompt, initialPromptKey, prefillRequestKey, sessionId]);+ }, [+ initialContent,+ initialPrompt,+ initialPromptKey,+ prefillRequestKey,+ recoveredFromKey,+ sessionId,+ ]);useEffect(() => {reportInputHadContentRef.current = false;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.tsxnew file mode 100644index 000000000000..3cc32ee0eb9c--- /dev/null+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskPendingView.test.tsx@@ -0,0 +1,59 @@+import { Theme } from "@radix-ui/themes";+import { 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();+ });+});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.tsxindex 70aa02e57d97..5a7ea58ae03f 100644--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskPendingView.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskPendingView.tsx@@ -1,7 +1,28 @@+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 { usePendingTaskPrompt } from "../../../shell/pendingTaskPromptStore";+import { useCallback } from "react";+import {+ usePendingTaskPrompt,+ usePendingTaskPromptStore,+} from "../../../shell/pendingTaskPromptStore";import { PendingChatView } from "../../sessions/components/PendingChatView";+import { InterruptedPromptView } from "./InterruptedPromptView";interface TaskPendingViewProps {pendingTaskKey: string;@@ -9,6 +30,17 @@ interface TaskPendingViewProps {export function TaskPendingView({ pendingTaskKey }: TaskPendingViewProps) {const pending = usePendingTaskPrompt(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 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@@ -22,10 +54,48 @@ export function TaskPendingView({ pendingTaskKey }: TaskPendingViewProps) {}}className="relative h-full w-full bg-background">- <PendingChatView- promptText={pending?.promptText ?? ""}- attachments={pending?.attachments}- />+ {pending?.interruptReason ? (+ <InterruptedPromptView+ promptText={pending.promptText}+ attachments={pending.attachments}+ reason={pending.interruptReason}+ onRecover={handleRecover}+ onDiscard={handleDiscard}+ />+ ) : pending ? (+ <PendingChatView+ promptText={pending.promptText}+ attachments={pending.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.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.tsindex d4af940f1458..e3d401bfdc18 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,3 +1,4 @@+import { getIsOnline } from "@posthog/core/connectivity/connectivityStore";import { partitionLocalMcpServersForRun } from "@posthog/core/local-mcp/localMcpImport";import {getErrorTitle,@@ -67,7 +68,6 @@ import { useTourStore } from "../../tour/tourStore";import { createFirstTaskTour } from "../../tour/tours/createFirstTaskTour";import { useExistingWorktreeConfirmStore } from "../stores/existingWorktreeConfirmStore";import { useRemoteBranchConfirmStore } from "../stores/remoteBranchConfirmStore";-import { restoreTaskInputTab } from "../taskInputTab";const log = logger.scope("task-creation");@@ -361,6 +361,12 @@ export function useTaskCreation({id: a.id,label: a.label,})),+ // The serialized content restores file chips and attachments on+ // recovery, so an interrupted prompt comes back whole, not as bare+ // text.+ contentXml: serializedContent,+ // 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.@@ -571,11 +577,32 @@ export function useTaskCreation({});}if (pendingTaskKey) {- pendingTaskPromptStoreApi.clear(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) {- pendingTaskPromptStoreApi.clear(createdTaskId);+ navigateBrowserTab(+ originTabId,+ {+ href: `/tasks/pending/${interruptedKey}`,+ title: "New task",+ },+ () => navigateToTaskPending(interruptedKey),+ );}- restoreTaskInputTab(originTabId, channelContextId ?? channelId);}}return result.success;@@ -586,11 +613,24 @@ export function useTaskCreation({toastError("Failed to create task", error);log.error("Unexpected error during task creation", { error });if (pendingTaskKey) {- pendingTaskPromptStoreApi.clear(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) {- pendingTaskPromptStoreApi.clear(createdTaskId);+ navigateBrowserTab(+ originTabId,+ { href: `/tasks/pending/${interruptedKey}`, title: "New task" },+ () => navigateToTaskPending(interruptedKey),+ );}- restoreTaskInputTab(originTabId, channelContextId ?? channelId);}return false;}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.tsnew file mode 100644index 000000000000..5d63a1a6fd98--- /dev/null+++ b/products/desktop/packages/ui/src/features/task-detail/pendingPromptActions.test.ts@@ -0,0 +1,59 @@+import { useTaskInputPrefillStore } from "@posthog/ui/features/task-detail/stores/taskInputPrefillStore";+import {+ pendingTaskPromptStoreApi,+ usePendingTaskPromptStore,+} from "@posthog/ui/shell/pendingTaskPromptStore";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import {+ discardPendingPrompt,+ recoverPendingPrompt,+} from "./pendingPromptActions";++function reset(): void {+ usePendingTaskPromptStore.setState({ byKey: {}, _hasHydrated: true });+ useTaskInputPrefillStore.setState({ prefill: {} });+}++describe("pendingPromptActions", () => {+ beforeEach(reset);+ 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" />',+ });++ const recovered = recoverPendingPrompt("k1");++ expect(recovered).toBe(true);+ const { prefill } = useTaskInputPrefillStore.getState();+ // The file chip is preserved, so recovery restores attachments, not just text.+ expect(prefill.initialContent?.segments).toContainEqual({+ type: "chip",+ chip: { type: "file", id: "src/a.ts", label: "src/a.ts" },+ });+ // The composer is told which record to clear once it applies the content.+ expect(prefill.recoveredFromKey).toBe("k1");+ // The durable record survives until then, so a crash before the composer+ // mounts leaves the prompt recoverable on the next launch.+ expect(pendingTaskPromptStoreApi.get("k1")).toBeDefined();+ });++ it("recovers nothing and stages nothing when the record is already gone", () => {+ expect(recoverPendingPrompt("missing")).toBe(false);+ expect(+ useTaskInputPrefillStore.getState().prefill.initialContent,+ ).toBeUndefined();+ });++ it("discards the prompt and opens an empty composer", () => {+ pendingTaskPromptStoreApi.set("k1", { promptText: "x", attachments: [] });+ discardPendingPrompt("k1");+ expect(pendingTaskPromptStoreApi.get("k1")).toBeUndefined();+ expect(+ useTaskInputPrefillStore.getState().prefill.initialContent,+ ).toBeUndefined();+ });+});diff --git a/products/desktop/packages/ui/src/features/task-detail/pendingPromptActions.ts b/products/desktop/packages/ui/src/features/task-detail/pendingPromptActions.tsnew file mode 100644index 000000000000..1fd51e5744f0--- /dev/null+++ b/products/desktop/packages/ui/src/features/task-detail/pendingPromptActions.ts@@ -0,0 +1,31 @@+import { pendingPromptToContent } from "@posthog/core/tasks/pendingPrompts";+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.+ * Returns false when the record is already gone (nothing to recover).+ */+export function recoverPendingPrompt(key: string): boolean {+ const record = pendingTaskPromptStoreApi.get(key);+ if (!record) return false;+ openTaskInput({+ 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 }),+ });+ return true;+}++/** Discard an interrupted prompt and open a fresh, empty new-task composer. */+export function discardPendingPrompt(key: string): void {+ pendingTaskPromptStoreApi.clear(key);+ openTaskInput();+}diff --git a/products/desktop/packages/ui/src/features/task-detail/stores/taskInputPrefillStore.ts b/products/desktop/packages/ui/src/features/task-detail/stores/taskInputPrefillStore.tsindex 63db50a3daff..4ca6e831a78e 100644--- a/products/desktop/packages/ui/src/features/task-detail/stores/taskInputPrefillStore.ts+++ b/products/desktop/packages/ui/src/features/task-detail/stores/taskInputPrefillStore.ts@@ -1,3 +1,4 @@+import type { EditorContent } from "@posthog/core/message-editor/content";import { create } from "zustand";export interface TaskInputReportAssociation {@@ -11,6 +12,18 @@ export interface TaskInputPrefill {/** `owner/repo` of the picked sidebar group, for groups with no folder. */folderRepository?: string;initialPrompt?: string;+ /**+ * Full editor content to restore, including file chips and attachments.+ * Preferred over initialPrompt when set (e.g. recovering an interrupted+ * prompt); initialPrompt stays for plain-text callers.+ */+ initialContent?: EditorContent;+ /**+ * Pending-prompt record key this prefill was recovered from. The composer+ * clears that record once it applies the content, so the durable record+ * outlives the transient prefill until the prompt is safely in the composer.+ */+ recoveredFromKey?: string;initialCloudRepository?: string;initialModel?: string;initialMode?: string;@@ -53,6 +66,8 @@ export const useTaskInputPrefillStore = create<PrefillStoreState>((set) => ({prefill: {...s.prefill,initialPrompt: undefined,+ initialContent: undefined,+ recoveredFromKey: undefined,requestId: undefined,},}diff --git a/products/desktop/packages/ui/src/features/task-detail/taskInputTab.test.ts b/products/desktop/packages/ui/src/features/task-detail/taskInputTab.test.tsdeleted file mode 100644index ce640f5efd02..000000000000--- a/products/desktop/packages/ui/src/features/task-detail/taskInputTab.test.ts+++ /dev/null@@ -1,51 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- navigateBrowserTab: vi.fn(),- openTaskInput: vi.fn(),-}));--vi.mock("@posthog/ui/features/browser-tabs/imperativeTabNavigation", () => ({- navigateBrowserTab: mocks.navigateBrowserTab,-}));-vi.mock("@posthog/ui/router/useOpenTask", () => ({- openTaskInput: mocks.openTaskInput,-}));--import { restoreTaskInputTab } from "./taskInputTab";--describe("restoreTaskInputTab", () => {- beforeEach(() => vi.clearAllMocks());-- it("restores a failed space task to its original space", () => {- restoreTaskInputTab("tab-1", "space-1");-- expect(mocks.navigateBrowserTab).toHaveBeenCalledWith(- "tab-1",- {- href: "/spaces/space-1/new",- title: "New task",- channelId: "space-1",- },- expect.any(Function),- );-- const navigateActiveTab = mocks.navigateBrowserTab.mock.calls[0]?.[2];- navigateActiveTab();- expect(mocks.openTaskInput).toHaveBeenCalledWith({ channelId: "space-1" });- });-- it("restores an unscoped task to the Code composer", () => {- restoreTaskInputTab("tab-1");-- const [, destination, navigateActiveTab] =- mocks.navigateBrowserTab.mock.calls[0];- expect(destination).toEqual({- href: "/new",- title: "New task",- channelId: undefined,- });- navigateActiveTab();- expect(mocks.openTaskInput).toHaveBeenCalledWith({ unscoped: true });- });-});diff --git a/products/desktop/packages/ui/src/features/task-detail/taskInputTab.ts b/products/desktop/packages/ui/src/features/task-detail/taskInputTab.tsdeleted file mode 100644index bcae5ca798a3..000000000000--- a/products/desktop/packages/ui/src/features/task-detail/taskInputTab.ts+++ /dev/null@@ -1,17 +0,0 @@-import { navigateBrowserTab } from "@posthog/ui/features/browser-tabs/imperativeTabNavigation";-import { openTaskInput } from "@posthog/ui/router/useOpenTask";--export function restoreTaskInputTab(- tabId: string | null,- spaceId?: string,-): void {- navigateBrowserTab(- tabId,- {- href: spaceId ? `/spaces/${spaceId}/new` : "/new",- title: "New task",- channelId: spaceId,- },- () => openTaskInput(spaceId ? { channelId: spaceId } : { unscoped: true }),- );-}diff --git a/products/desktop/packages/ui/src/router/useAppView.ts b/products/desktop/packages/ui/src/router/useAppView.tsindex 5403dca2cc85..350a01fce6f5 100644--- a/products/desktop/packages/ui/src/router/useAppView.ts+++ b/products/desktop/packages/ui/src/router/useAppView.ts@@ -1,3 +1,4 @@+import type { EditorContent } from "@posthog/core/message-editor/content";import {type TaskInputReportAssociation,useTaskInputPrefillStore,@@ -31,6 +32,8 @@ export interface AppView {pendingTaskKey?: string;taskInputRequestId?: string;initialPrompt?: string;+ initialContent?: EditorContent;+ recoveredFromKey?: string;initialCloudRepository?: string;initialModel?: string;initialMode?: string;@@ -150,6 +153,8 @@ export function useAppView(): AppView {folderId: prefill.folderId,folderRepository: prefill.folderRepository,initialPrompt: prefill.initialPrompt,+ initialContent: prefill.initialContent,+ recoveredFromKey: prefill.recoveredFromKey,initialCloudRepository: prefill.initialCloudRepository,initialModel: prefill.initialModel,initialMode: prefill.initialMode,diff --git a/products/desktop/packages/ui/src/router/useOpenTask.ts b/products/desktop/packages/ui/src/router/useOpenTask.tsindex c84f03f15e79..a4f362700849 100644--- a/products/desktop/packages/ui/src/router/useOpenTask.ts+++ b/products/desktop/packages/ui/src/router/useOpenTask.ts@@ -1,3 +1,4 @@+import type { EditorContent } from "@posthog/core/message-editor/content";import { resolveService, resolveServiceOptional } from "@posthog/di/container";import { ANALYTICS_EVENTS } from "@posthog/shared";import type { Task } from "@posthog/shared/domain-types";@@ -96,6 +97,14 @@ export interface TaskInputNavigationOptions {*/folderRepository?: string;initialPrompt?: string;+ /**+ * Full editor content to restore (chips + attachments), preferred over+ * initialPrompt. Used when recovering an interrupted prompt so nothing but+ * the plain text is lost.+ */+ initialContent?: EditorContent;+ /** Pending-prompt record key being recovered; the composer clears it once applied. */+ recoveredFromKey?: string;initialCloudRepository?: string;initialModel?: string;initialMode?: string;@@ -134,6 +143,8 @@ export function openTaskInput(!!options.folderId ||!!options.folderRepository ||!!options.initialPrompt ||+ !!options.initialContent ||+ !!options.recoveredFromKey ||!!options.initialCloudRepository ||!!options.initialModel ||!!options.initialMode ||@@ -144,6 +155,8 @@ export function openTaskInput(folderId: options.folderId,folderRepository: options.folderRepository,initialPrompt: options.initialPrompt,+ initialContent: options.initialContent,+ recoveredFromKey: options.recoveredFromKey,initialCloudRepository: options.initialCloudRepository,initialModel: options.initialModel,initialMode: options.initialMode,diff --git a/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.test.ts b/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.test.tsindex e9f6c1c126ee..10cd8a4873f2 100644--- a/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.test.ts+++ b/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.test.ts@@ -49,6 +49,19 @@ 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", () => {pendingTaskPromptStoreApi.set("old", {promptText: "old",diff --git a/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.ts b/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.tsindex cd227ef24aa0..2f40c6067249 100644--- a/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.ts+++ b/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.ts@@ -1,3 +1,4 @@+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";@@ -6,10 +7,30 @@ import { persist } from "zustand/middleware";export interface PendingTaskPrompt {promptText: string;attachments: UserMessageAttachment[];+ /**+ * Serialized editor content (chips + attachments) so recovery restores the+ * full prompt, not just its plain text. Absent on records written before this+ * 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;createdAt: number;}-export type PendingTaskPromptInput = Omit<PendingTaskPrompt, "createdAt">;+export type PendingTaskPromptInput = Omit<+ PendingTaskPrompt,+ "createdAt" | "interruptReason"+>;interface PendingTaskPromptStore {byKey: Record<string, PendingTaskPrompt>;@@ -18,6 +39,7 @@ interface PendingTaskPromptStore {set: (key: string, prompt: PendingTaskPromptInput) => void;get: (key: string) => PendingTaskPrompt | undefined;move: (fromKey: string, toKey: string) => void;+ markInterrupted: (key: string, reason: PendingPromptInterruptReason) => void;clear: (key: string) => void;}@@ -48,6 +70,19 @@ export const usePendingTaskPromptStore = create<PendingTaskPromptStore>()(return { byKey: { ...rest, [toKey]: entry } };});},+ markInterrupted: (key, reason) =>+ set((state) => {+ const entry = state.byKey[key];+ if (!entry) {+ return state;+ }+ return {+ byKey: {+ ...state.byKey,+ [key]: { ...entry, interruptReason: reason },+ },+ };+ }),clear: (key) =>set((state) => {if (!(key in state.byKey)) {@@ -83,6 +118,8 @@ export const pendingTaskPromptStoreApi = {get: (key: string) => usePendingTaskPromptStore.getState().get(key),move: (fromKey: string, toKey: string) =>usePendingTaskPromptStore.getState().move(fromKey, toKey),+ markInterrupted: (key: string, reason: PendingPromptInterruptReason) =>+ usePendingTaskPromptStore.getState().markInterrupted(key, reason),clear: (key: string) => usePendingTaskPromptStore.getState().clear(key),getAllNewestFirst: (): RecoverablePendingPrompt[] =>listPendingPromptsNewestFirst(usePendingTaskPromptStore.getState().byKey),