Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): keep Pi session loading state (#90836)

Jonathan Mieloo631a78446b4d
diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
index 5cd5b1b0b713..bfccf9d7d9be 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
@@ -380,12 +380,18 @@ describe("TaskCreationSaga", () => {
expect(deleteTask).not.toHaveBeenCalled();
});
- it("starts a Pi session without creating an ACP session", async () => {
+ it("starts a Pi session before surfacing a new local task", async () => {
+ let resolvePiSession: () => void = () => {};
+ const piSessionCreated = new Promise<void>((resolve) => {
+ resolvePiSession = resolve;
+ });
const createdTask = createTask({ repository: undefined });
const createTaskRequest = vi.fn().mockResolvedValue(createdTask);
- const saga = makeSaga({ createTask: createTaskRequest });
+ const onTaskReady = vi.fn();
+ piRunner.create.mockImplementationOnce(() => piSessionCreated);
+ const saga = makeSaga({ createTask: createTaskRequest }, { onTaskReady });
- const result = await saga.run({
+ const run = saga.run({
content: "Draft a launch email",
workspaceMode: "local",
runtime: "pi",
@@ -396,7 +402,17 @@ describe("TaskCreationSaga", () => {
allowNoRepo: true,
});
+ await vi.waitFor(() => expect(piRunner.create).toHaveBeenCalledOnce());
+ expect(onTaskReady).not.toHaveBeenCalled();
+ resolvePiSession();
+
+ const result = await run;
+
expect(result.success).toBe(true);
+ expect(onTaskReady).toHaveBeenCalledWith({
+ task: createdTask,
+ workspace: null,
+ });
expect(createTaskRequest).toHaveBeenCalledWith(
expect.objectContaining({ runtime: "pi" }),
);
@@ -416,6 +432,41 @@ describe("TaskCreationSaga", () => {
expect(sessionService.markTaskCreationInFlight).not.toHaveBeenCalled();
});
+ it("starts a Pi session before surfacing a new worktree task", async () => {
+ let resolvePiSession: () => void = () => {};
+ const piSessionCreated = new Promise<void>((resolve) => {
+ resolvePiSession = resolve;
+ });
+ const createdTask = createTask();
+ const onTaskReady = vi.fn();
+ mockHost.addFolder.mockResolvedValue({ id: "folder-1", path: "/repo" });
+ piRunner.create.mockImplementationOnce(() => piSessionCreated);
+ const saga = makeSaga(
+ { createTask: vi.fn().mockResolvedValue(createdTask) },
+ { onTaskReady },
+ );
+
+ const run = saga.run({
+ content: "Fix the login flow",
+ repoPath: "/repo",
+ workspaceMode: "worktree",
+ runtime: "pi",
+ });
+
+ await vi.waitFor(() => expect(piRunner.create).toHaveBeenCalledOnce());
+ expect(onTaskReady).not.toHaveBeenCalled();
+ resolvePiSession();
+
+ const result = await run;
+
+ expect(result).toMatchObject({ success: true });
+ expect(mockHost.createWorkspace).toHaveBeenCalledOnce();
+ expect(onTaskReady).toHaveBeenCalledWith({
+ task: createdTask,
+ workspace: expect.objectContaining({ taskId: createdTask.id }),
+ });
+ });
+
it("uploads cloud Pi attachments before starting the run", async () => {
const createdTask = createTask({ repository: "posthog/posthog" });
const startedTask = createTask({ latest_run: createRun(), runtime: "pi" });
diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
index a89b23464f73..6902ced24997 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
@@ -144,6 +144,8 @@ export class TaskCreationSaga extends Saga<
const workspaceMode =
input.workspaceMode ??
(task.latest_run?.environment === "cloud" ? "cloud" : "local");
+ const shouldDeferLocalPiTaskReady =
+ isPiRuntime && !taskId && workspaceMode !== "cloud";
let workspace: Workspace | null = null;
const branch = input.branch ?? task.latest_run?.branch ?? null;
@@ -152,7 +154,9 @@ export class TaskCreationSaga extends Saga<
if (hasProvisioning) {
this.deps.host.setProvisioningActive(task.id);
- this.notifyTaskReady({ task, workspace });
+ if (!shouldDeferLocalPiTaskReady) {
+ this.notifyTaskReady({ task, workspace });
+ }
}
if (repoPath) {
@@ -211,10 +215,8 @@ export class TaskCreationSaga extends Saga<
}
} catch (error) {
// For a fresh worktree task the prompt is already persisted as the task
- // description and the UI has navigated onto the task. Rolling the saga
- // back here would run task_creation's deleteTask and destroy that task,
- // losing the prompt. Instead keep the task with no workspace (the shape
- // openTask re-provisions from) so the user can retry setup on it.
+ // description. Rolling the saga back here would delete that task and
+ // lose the prompt. Keep the task with no workspace so setup can retry.
if (!hasProvisioning) throw error;
const provisioningError =
error instanceof Error ? error.message : String(error);
@@ -223,6 +225,9 @@ export class TaskCreationSaga extends Saga<
error,
});
this.deps.host.clearProvisioning(task.id);
+ if (shouldDeferLocalPiTaskReady) {
+ this.notifyTaskReady({ task, workspace: null });
+ }
// The in-flight mark is left to TTL-expire on purpose: this state has
// its own retry-prompt UX, and auto-recovery would race the retry.
return { task, workspace: null, provisioningError };
@@ -338,7 +343,11 @@ export class TaskCreationSaga extends Saga<
);
}
- if (!hasProvisioning && !shouldStartCloudRun) {
+ if (
+ !hasProvisioning &&
+ !shouldStartCloudRun &&
+ !shouldDeferLocalPiTaskReady
+ ) {
if (!taskId && workspaceMode === "cloud") {
await this.deps.sessionService.watchCreatedCloudTask(task);
}
@@ -604,6 +613,10 @@ export class TaskCreationSaga extends Saga<
});
}
+ if (shouldDeferLocalPiTaskReady) {
+ this.notifyTaskReady({ task, workspace });
+ }
+
return { task, workspace };
}
diff --git a/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx b/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx
index 095a3daf4ae9..e8bc0b08ac84 100644
--- a/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx
+++ b/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx
@@ -52,7 +52,6 @@ import { useConnectivity } from "@posthog/ui/hooks/useConnectivity";
import { toast } from "@posthog/ui/primitives/toast";
import { TaskDetailSkeleton } from "@posthog/ui/router/routeSkeletons";
import { logger } from "@posthog/ui/shell/logger";
-import { Box, Flex } from "@radix-ui/themes";
import {
type ReactElement,
useCallback,
@@ -613,7 +612,7 @@ export function PiSessionView({ task, isCloud }: PiSessionViewProps) {
);
}
- if (!status && !hasTranscript && !isConnecting) {
+ if (!status && !hasTranscript && (!isConnecting || !isCloud)) {
return <TaskDetailSkeleton />;
}
@@ -640,7 +639,7 @@ export function PiSessionView({ task, isCloud }: PiSessionViewProps) {
const extensionDialog = currentExtensionState.dialogs[0];
return (
- <Flex direction="column" height="100%">
+ <div className="flex h-full flex-col">
{extensionDialog && (
<PiExtensionDialog
key={extensionDialog.id}
@@ -661,7 +660,7 @@ export function PiSessionView({ task, isCloud }: PiSessionViewProps) {
onRestart={restart}
/>
)}
- <Box className="min-h-0 flex-1">
+ <div className="min-h-0 flex-1">
<ChatThread
events={session.events}
isPromptPending={isStreaming}
@@ -670,8 +669,8 @@ export function PiSessionView({ task, isCloud }: PiSessionViewProps) {
promptRecallRef={promptRecallRef}
hasPendingPermission={Boolean(mcpPermission)}
/>
- </Box>
- <Box
+ </div>
+ <div
className="mx-auto w-full px-2 pb-3"
style={{ maxWidth: CHAT_CONTENT_MAX_WIDTH }}
>
@@ -761,7 +760,7 @@ export function PiSessionView({ task, isCloud }: PiSessionViewProps) {
placement="belowEditor"
/>
)}
- </Box>
- </Flex>
+ </div>
+ </div>
);
}
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.tsx
index 3cc32ee0eb9c..4ecbfa99b599 100644
--- 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.tsx
@@ -1,5 +1,5 @@
import { Theme } from "@radix-ui/themes";
-import { render, screen } from "@testing-library/react";
+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
@@ -56,4 +56,32 @@ describe("TaskPendingView hydration gate", () => {
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.tsx
index 5a7ea58ae03f..2fe0f8d6c99a 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
@@ -16,7 +16,7 @@ import {
} from "@posthog/ui/features/task-detail/pendingPromptActions";
import { openTaskInput } from "@posthog/ui/router/useOpenTask";
import { motion } from "framer-motion";
-import { useCallback } from "react";
+import { useCallback, useEffect } from "react";
import {
usePendingTaskPrompt,
usePendingTaskPromptStore,
@@ -30,10 +30,19 @@ interface TaskPendingViewProps {
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);
@@ -54,18 +63,18 @@ export function TaskPendingView({ pendingTaskKey }: TaskPendingViewProps) {
}}
className="relative h-full w-full bg-background"
>
- {pending?.interruptReason ? (
+ {displayedPending?.interruptReason ? (
<InterruptedPromptView
- promptText={pending.promptText}
- attachments={pending.attachments}
- reason={pending.interruptReason}
+ promptText={displayedPending.promptText}
+ attachments={displayedPending.attachments}
+ reason={displayedPending.interruptReason}
onRecover={handleRecover}
onDiscard={handleDiscard}
/>
- ) : pending ? (
+ ) : displayedPending ? (
<PendingChatView
- promptText={pending.promptText}
- attachments={pending.attachments}
+ promptText={displayedPending.promptText}
+ attachments={displayedPending.attachments}
/>
) : !hasHydrated ? (
<div className="absolute inset-0 flex items-center justify-center p-6">
diff --git a/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.ts b/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.ts
index 2f40c6067249..9519858b2023 100644
--- a/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.ts
+++ b/products/desktop/packages/ui/src/shell/pendingTaskPromptStore.ts
@@ -34,11 +34,13 @@ export type PendingTaskPromptInput = Omit<
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;
clear: (key: string) => void;
}
@@ -47,6 +49,7 @@ export const usePendingTaskPromptStore = create<PendingTaskPromptStore>()(
persist(
(set, get) => ({
byKey: {},
+ handoffs: {},
_hasHydrated: false,
setHasHydrated: (hydrated) => set({ _hasHydrated: hydrated }),
set: (key, prompt) =>
@@ -67,9 +70,20 @@ export const usePendingTaskPromptStore = create<PendingTaskPromptStore>()(
return state;
}
const { [fromKey]: _removed, ...rest } = state.byKey;
- return { byKey: { ...rest, [toKey]: entry } };
+ return {
+ byKey: { ...rest, [toKey]: entry },
+ handoffs: { ...state.handoffs, [fromKey]: entry },
+ };
});
},
+ clearHandoff: (key) =>
+ set((state) => {
+ if (!(key in state.handoffs)) {
+ return state;
+ }
+ const { [key]: _removed, ...rest } = state.handoffs;
+ return { handoffs: rest };
+ }),
markInterrupted: (key, reason) =>
set((state) => {
const entry = state.byKey[key];
@@ -118,6 +132,8 @@ 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),
clear: (key: string) => usePendingTaskPromptStore.getState().clear(key),
diff --git a/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.test.ts b/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.test.ts
index 0c5b911e125a..75d8da484317 100644
--- a/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.test.ts
@@ -210,6 +210,8 @@ describe("PiSessionService start", () => {
rootLogger,
);
+ expect(service.getPendingMcpToolPermissions("task-1")).toEqual([]);
+
await service.start({
taskContext: {
taskId: "task-1",
diff --git a/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.ts b/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.ts
index 5da6a6629848..3eb0977bc96a 100644
--- a/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.ts
+++ b/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.ts
@@ -250,7 +250,14 @@ export class PiSessionService extends TypedEventEmitter<PiSessionEvents> {
}
getPendingMcpToolPermissions(taskId: string): McpToolPermissionRequest[] {
- return [...this.requireSession(taskId).pendingMcpPermissions.values()];
+ const session = this.sessions.get(taskId);
+
+ if (!session) {
+ return [];
+ }
+
+ this.touchSession(session);
+ return [...session.pendingMcpPermissions.values()];
}
async respondMcpToolPermission(