: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): save task prompt to history before preflight (#101402)
Charles Vienc788ad200bfc
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.tsxindex d3423a75f1ae..53ff7b08e87c 100644--- 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.tsx@@ -5,6 +5,7 @@ import {textToContent,} from "@posthog/core/message-editor/content";import type { Task } from "@posthog/shared/domain-types";+import { useTaskInputHistoryStore } from "@posthog/ui/features/message-editor/taskInputHistoryStore";import { useTaskInputPrefillStore } from "@posthog/ui/features/task-detail/stores/taskInputPrefillStore";import {pendingTaskPromptStoreApi,@@ -19,6 +20,9 @@ const createTaskMock = vi.hoisted(() => vi.fn());const invalidateTasksMock = vi.hoisted(() => vi.fn());const openTaskMock = vi.hoisted(() => vi.fn());const trackMock = vi.hoisted(() => vi.fn());+const assertCloudUsageAvailableMock = vi.hoisted(() =>+ vi.fn<() => Promise<boolean>>(async () => true),+);const cloudSubscription = vi.hoisted(() => ({cloudSubscriptionOn: false,cloudFlagEnabled: true,@@ -73,7 +77,7 @@ vi.mock("../../../hooks/useConnectivity", () => ({useConnectivity: () => ({ isOnline: true }),}));vi.mock("../../billing/preflightCloudUsage", () => ({- assertCloudUsageAvailable: async () => true,+ assertCloudUsageAvailable: assertCloudUsageAvailableMock,}));vi.mock("../../../primitives/toast", () => ({toast: { error: vi.fn() },@@ -99,9 +103,21 @@ vi.mock("@posthog/ui/router/useOpenTask", async (importOriginal) => {import type { EditorHandle } from "../../message-editor/types";import { useTaskCreation } from "./useTaskCreation";+type HandleSubmit = ReturnType<typeof useTaskCreation>["handleSubmit"];+const KICKOFF_PREAMBLE ="AUTORESEARCH KICKOFF — protocol instructions generated for the run";+function autoresearchOverride(brief: EditorContent): EditorContent {+ return {+ segments: [+ { type: "text", text: `${KICKOFF_PREAMBLE}\n\n` },+ ...brief.segments,+ ],+ attachments: brief.attachments,+ };+}+function fakeTask(): Task {return {id: "task-1",@@ -172,6 +188,87 @@ describe("useTaskCreation prompt records", () => {cloudSubscription.cloudSubscriptionOn = false;usePendingTaskPromptStore.setState({ byKey: {}, _hasHydrated: true });useTaskInputPrefillStore.setState({ prefill: {} });+ useTaskInputHistoryStore.setState({ entries: [] });+ });++ it.each<{+ name: string;+ workspaceMode: "local" | "cloud";+ preflight: () => void;+ submit: (+ handleSubmit: HandleSubmit,+ brief: EditorContent,+ ) => Promise<boolean>;+ createTaskCalls: number;+ }>([+ {+ name: "a plain submit blocked by the cloud usage preflight",+ workspaceMode: "cloud",+ preflight: () =>+ void assertCloudUsageAvailableMock.mockResolvedValueOnce(false),+ submit: (handleSubmit) => handleSubmit(),+ createTaskCalls: 0,+ },+ {+ name: "content handed over as an override",+ workspaceMode: "local",+ preflight: () => {},+ submit: (handleSubmit, brief) => handleSubmit(brief),+ createTaskCalls: 1,+ },+ {+ name: "an autoresearch override, keeping the brief and not the preamble",+ workspaceMode: "local",+ preflight: () => {},+ submit: (handleSubmit, brief) =>+ handleSubmit(autoresearchOverride(brief), brief),+ createTaskCalls: 1,+ },+ ])(+ "saves the typed prompt to history before creation can fail: $name",+ async ({ workspaceMode, preflight, submit, createTaskCalls }) => {+ const brief = textToContent("Check the build");+ preflight();+ createTaskMock.mockResolvedValueOnce({+ success: false,+ error: "boom",+ failedStep: "create",+ });++ const { result } = renderTaskCreation(brief, workspaceMode);+ await act(async () => {+ expect(await submit(result.current.handleSubmit, brief)).toBe(false);+ });++ expect(createTaskMock).toHaveBeenCalledTimes(createTaskCalls);+ expect(+ useTaskInputHistoryStore.getState().entries.map((e) => e.text),+ ).toEqual(["Check the build"]);+ },+ );++ it("still creates the task when the history write throws", async () => {+ const addPrompt = vi+ .spyOn(useTaskInputHistoryStore.getState(), "addPrompt")+ .mockImplementation(() => {+ throw new Error("quota exceeded");+ });+ createTaskMock.mockResolvedValueOnce({+ success: true,+ data: { task: fakeTask(), workspace: null },+ });++ try {+ const { result } = renderTaskCreation(textToContent("Check the build"));+ await act(async () => {+ expect(await result.current.handleSubmit()).toBe(true);+ });++ expect(addPrompt).toHaveBeenCalledOnce();+ expect(createTaskMock).toHaveBeenCalledOnce();+ } finally {+ addPrompt.mockRestore();+ }});it("omits subscription billing when Pi is selected", async () => {@@ -224,13 +321,7 @@ describe("useTaskCreation prompt records", () => {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,- };+ const override = autoresearchOverride(brief);createTaskMock.mockImplementationOnce(async (_input, onTaskReady) => {// The late failure: onTaskReady already ran, so the record moved to thediff --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 882678046ca1..22d64a48d6c0 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@@ -312,6 +312,18 @@ export function useTaskCreation({const serializedContent = contentToXml(content).trim();const filePaths = extractFilePaths(content);+ // History is where the person recovers a prompt when creation fails, so+ // it must be written before any preflight call that can fail. The write+ // persists to local storage, which throws when the quota is full, and+ // history is only a recovery aid, so it must not block the task.+ if (plainPromptText) {+ try {+ useTaskInputHistoryStore.getState().addPrompt(plainPromptText);+ } catch (error) {+ log.warn("Failed to save the prompt to history", { error });+ }+ }+// Held for the whole submit, pre-flight awaits included, so a second// Enter lands after `canSubmitBase` has already gone false.setIsCreatingTask(true);@@ -436,12 +448,6 @@ export function useTaskCreation({};try {- if (!contentOverride) {- if (plainPromptText) {- useTaskInputHistoryStore.getState().addPrompt(plainPromptText);- }- }-const settings = useSettingsStore.getState();const defaultedChannelId =bluebirdEnabled && !channelId && !channelName