: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
feat(phai): show optimistic "spinning up sandbox" indicator on send (#66062)
Georgiy Tarasov03d2903f70ce
diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.tsindex ef84f08c862c..9401ca442d0b 100644--- a/frontend/src/scenes/max/maxThreadLogic.test.ts+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts@@ -3534,6 +3534,20 @@ describe('maxThreadLogic', () => {expect(maxLogicInstance.values.activeStreamingThreads).toEqual(0)})+ it('lights the optimistic boot indicator before the open POST and clears it once the SSE opens', async () => {+ jest.spyOn(api.conversations, 'open').mockResolvedValue(sandboxRunResponse)++ await expectLogic(logic, () => {+ logic.actions.streamConversation(+ { agent_mode: null, is_sandbox: true, content: 'hello', conversation: MOCK_CONVERSATION_ID },+ 0+ )+ }).toDispatchActions(['setSandboxRunOpening', 'openSandboxSse'])++ // openSandboxSse clears the optimistic flag via the reducer, so it never sticks on success.+ expect(runStreamLogic({ streamKey: MOCK_CONVERSATION_ID }).values.runOpening).toEqual(false)+ })+it('releases the lock immediately and surfaces an error when the send POST fails', async () => {jest.spyOn(api.conversations, 'open').mockRejectedValue(new Error('boom'))@@ -3545,6 +3559,8 @@ describe('maxThreadLogic', () => {}).toDispatchActions(['pushSandboxError', 'decrActiveStreamingThreads'])expect(maxLogicInstance.values.activeStreamingThreads).toEqual(0)+ // The boot indicator must not stick once the failed send unwinds.+ expect(runStreamLogic({ streamKey: MOCK_CONVERSATION_ID }).values.runOpening).toEqual(false)expect(runStreamLogic({ streamKey: MOCK_CONVERSATION_ID }).values.threadItems.some((item) =>diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex a21ce71d975c..a06441186588 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -212,6 +212,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>(['openSseForRun as openSandboxSse','pushHumanMessage as pushSandboxHumanMessage','pushErrorItem as pushSandboxError',+ 'setRunOpening as setSandboxRunOpening','bootstrapRun as bootstrapSandboxRun','reset as resetSandboxStream','cancelRun as cancelSandboxRun',@@ -717,6 +718,10 @@ export const maxThreadLogic = kea<maxThreadLogicType>([value: `The user selected a mode: "${getModeDisplayName(values.agentMode)}". It was in the legacy implementation. Acknowledge the mode if the user refers to it.`,})}+ // Optimistic boot indicator: light the "spinning up sandbox" provisioning state+ // for the duration of the open POST, before any SSE state exists. `openSandboxSse`+ // (success) clears it via the reducer; the failure/no-handle paths clear it below.+ actions.setSandboxRunOpening(true)// Single create-or-resume opener: it creates the conversation row on first use,// starts/continues the Run, and returns the (task, run) handle. A message always// provisions a run (a null handle only happens on a warm with a full pool).@@ -763,7 +768,9 @@ export const maxThreadLogic = kea<maxThreadLogicType>([posthog.captureException(e)actions.pushSandboxError('Failed to send your message. Please try again.')}- // The POST failed or no run was started — nothing will stream, release the lock now.+ // The POST failed or no run was started — nothing will stream. Drop the optimistic boot+ // indicator and release the lock now.+ actions.setSandboxRunOpening(false)actions.decrActiveStreamingThreads()releaseStreamingLock()returndiff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsxindex 274001df5df6..201752036f6e 100644--- a/products/posthog_ai/frontend/components/ThreadView.tsx+++ b/products/posthog_ai/frontend/components/ThreadView.tsx@@ -55,13 +55,16 @@ export function ThreadView({threadItems,toolInvocations,isThinking,- showThinkingIndicator,+ streamPhase,runArtifacts,turnComplete,currentRunStatus,contextUsage,} = useValues(runStreamLogic)const turnCancelled = currentRunStatus === 'cancelled'+ const hasActiveProgressItem = threadItems.some(+ (item) => item.type === 'progress' && item.progressSteps?.some((step) => step.status === 'in_progress')+ )// Header/footer are kept as memoized leaf components with stable element identity so they don't rebuild// `VirtualizedThread`'s `renderRow` (and re-sweep visible rows) on every streamed frame. Each is wrapped@@ -77,6 +80,10 @@ export function ThreadView({[branch, baseBranch, repo])+ // `provisioning` (conversations/open POST + cold boot before run_started) also shows the indicator,+ // gated by !hasActiveProgressItem so real `_posthog/progress` boot steps take precedence.+ const showThinking = (streamPhase === 'thinking' || streamPhase === 'provisioning') && !hasActiveProgressItem+ const thinkingPhase = streamPhase === 'provisioning' ? 'provisioning' : 'thinking'// Post-turn only: a reconnect refetch can fold in a pr_url mid-run, so gate on !isThinking.const pullRequestUrl = !isThinking ? runArtifacts.prUrl : undefined// Context usage rides the thread footer, but only between turns (idle) — never while the agent is@@ -84,17 +91,18 @@ export function ThreadView({const showContextUsageFooter = showContextUsage && !isThinking && !!contextUsageconst footer = useMemo(() =>- showThinkingIndicator || pullRequestUrl || showContextUsageFooter ? (+ showThinking || pullRequestUrl || showContextUsageFooter ? (<VirtualizedThread.Row className={rowClassName}><ThreadFooter- showThinking={showThinkingIndicator}+ showThinking={showThinking}+ thinkingPhase={thinkingPhase}pullRequestUrl={pullRequestUrl}prBranch={branch}showContextUsage={showContextUsageFooter}/></VirtualizedThread.Row>) : undefined,- [showThinkingIndicator, pullRequestUrl, branch, showContextUsageFooter]+ [showThinking, thinkingPhase, pullRequestUrl, branch, showContextUsageFooter])const renderItem = useCallback(@@ -150,11 +158,13 @@ const ThreadHeader = memo(function ThreadHeader({*/const ThreadFooter = memo(function ThreadFooter({showThinking,+ thinkingPhase,pullRequestUrl,prBranch,showContextUsage,}: {showThinking: boolean+ thinkingPhase: 'thinking' | 'provisioning'pullRequestUrl?: stringprBranch?: stringshowContextUsage?: boolean@@ -164,7 +174,7 @@ const ThreadFooter = memo(function ThreadFooter({// items keep the same vertical rhythm as the thread.return (<div className="flex flex-col gap-1.5">- {showThinking && <ThinkingIndicator progress={currentProgress} />}+ {showThinking && <ThinkingIndicator progress={currentProgress} phase={thinkingPhase} />}{pullRequestUrl && <PullRequestCard prUrl={pullRequestUrl} branch={prBranch} />}{showContextUsage && <ContextUsageBar />}</div>@@ -173,12 +183,19 @@ const ThreadFooter = memo(function ThreadFooter({/*** Bottom-of-thread "what's it doing right now" line for sandbox conversations. Reflects the latest- * `_posthog/progress` message when present, otherwise the canned thinking rotation.+ * `_posthog/progress` message when present; during `provisioning` (the conversations/open POST / cold+ * boot before `run_started`) it shows a fixed "spinning up" message, otherwise the canned thinking rotation.*/-function ThinkingIndicator({ progress }: { progress: string | null }): JSX.Element {+function ThinkingIndicator({+ progress,+ phase,+}: {+ progress: string | null+ phase: 'thinking' | 'provisioning'+}): JSX.Element {// One roll per mount — re-rolling on every progress transition would visibly swap the verb.const fallbackMessage = useMemo(() => getRandomThinkingMessage(), [])- const message = progress?.trim() ? progress : fallbackMessage+ const message = progress?.trim() ? progress : phase === 'provisioning' ? 'Spinning up sandbox…' : fallbackMessage// Match the LangGraph loader: a bubble-free reasoning line (muted brain icon + muted text),// static (no shimmer), via the shared Activity primitive — not a MessageTemplate bubble.return <ReasoningAnswer content={message} id="sandbox-thinking" completed={false} showCompletionIcon={false} />diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex 8d7be3a44314..74b81f945b72 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -1397,6 +1397,48 @@ describe('runStreamLogic', () => {})})+ describe('streamPhase provisioning during open', () => {+ it('is provisioning while the open POST is in flight, before any SSE state exists', () => {+ expect(logic.values.streamPhase).toEqual('idle')++ // The conversations/open POST has started — no SSE/run status yet.+ logic.actions.setRunOpening(true)+ expect(logic.values.sseStatus).toEqual('idle')+ expect(logic.values.currentRunStatus).toEqual(null)+ expect(logic.values.streamPhase).toEqual('provisioning')+ })++ it.each([+ ['a stream error', (): void => logic.actions.handleStreamError({ errorTitle: 'x', retryable: true })],+ ['an injected error item', (): void => logic.actions.pushErrorItem('boom')],+ ])('clears the optimistic flag on %s', (_case, act) => {+ logic.actions.setRunOpening(true)+ expect(logic.values.runOpening).toEqual(true)++ act()+ expect(logic.values.runOpening).toEqual(false)+ })++ it('clears the optimistic flag once the SSE opens (openSseForRun)', async () => {+ logic.actions.setRunOpening(true)+ expect(logic.values.runOpening).toEqual(true)++ // openSseForRun runs an async listener that opens a stream — await it so no work leaks.+ await expectLogic(logic, () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()+ expect(logic.values.runOpening).toEqual(false)+ })++ it('lets run_started win over the optimistic flag (thinking, not provisioning)', () => {+ logic.actions.setRunOpening(true)+ expect(logic.values.streamPhase).toEqual('provisioning')++ logic.actions.ingestAcpFrame(notification('_posthog/run_started', {}))+ expect(logic.values.streamPhase).toEqual('thinking')+ })+ })+describe('terminal-status handling', () => {it('closes the SSE and stops reconnects on a terminal task_run_state', async () => {logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex 872ae1df4f3c..18541b60cdff 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -1100,6 +1100,12 @@ export const runStreamLogic = kea<runStreamLogicType>([/** Internal: the live run history snapshot finished loading or was intentionally skipped. */bootstrapLogReady: true,closeSse: true,+ /**+ * The conversations/open POST is in flight — drives the optimistic "spinning up" indicator+ * before any SSE state exists. The caller (maxThreadLogic) flips it on before the POST and off+ * on the no-handle/failure paths; the success path lets `openSseForRun` clear it via the reducer.+ */+ setRunOpening: (opening: boolean) => ({ opening }),sseConnecting: true,sseOpened: true,sseReconnecting: (attempt: number) => ({ attempt }),@@ -1205,6 +1211,21 @@ export const runStreamLogic = kea<runStreamLogicType>([reset: true,}),reducers({+ // True while the conversations/open POST is in flight, before any SSE state exists. Folds into+ // `streamPhase` as provisioning so the thread shows the optimistic "spinning up" indicator+ // immediately on send. Cleared once a real stream lifecycle takes over (or ends/errors).+ runOpening: [+ false,+ {+ setRunOpening: (_, { opening }) => opening,+ openSseForRun: () => false,+ sseOpened: () => false,+ handleStreamError: () => false,+ handleTerminalStatus: () => false,+ pushErrorItem: () => false,+ reset: () => false,+ },+ ],sseStatus: ['idle' as RunSseStatus,{@@ -1516,22 +1537,32 @@ export const runStreamLogic = kea<runStreamLogicType>([],/*** Stream lifecycle phase gating the bottom-of-thread thinking indicator. `provisioning` = the- * cold-boot window — the stream is opening or open but the agent hasn't started yet (the- * workflow is still setting up the sandbox); it holds the gerund loader off until `run_started`- * so it can't show before a turn begins. Boot UX is surfaced by `_posthog/progress` items, not- * a dedicated indicator. `thinking` = the agent is working a turn (mirrors `isThinking`), and is+ * cold-boot window — the conversations/open POST is in flight (`runOpening`), or the stream is+ * opening/open but the agent hasn't started yet (the workflow is still setting up the sandbox).+ * `ThreadView` shows a fixed "spinning up" indicator here until a real `_posthog/progress`+ * boot step lands (which then takes over) or `run_started` flips the phase to `thinking`. The+ * playful gerund loader is held off until `thinking` so it never shows before a turn begins.+ * `thinking` = the agent is working a turn (mirrors `isThinking`), and is* what `ThreadView` gates the gerund loader on; `idle` otherwise (terminal, errored, or* not yet connecting). A read-only viewer is always `idle` — it never streams.*/streamPhase: [- (s, p) => [s.runStarted, s.isThinking, s.currentRunStatus, s.sseStatus, p.replayOnly!],- (runStarted, isThinking, currentRunStatus, sseStatus, replayOnly): 'provisioning' | 'thinking' | 'idle' => {+ (s, p) => [s.runStarted, s.isThinking, s.currentRunStatus, s.sseStatus, s.runOpening, p.replayOnly!],+ (+ runStarted,+ isThinking,+ currentRunStatus,+ sseStatus,+ runOpening,+ replayOnly+ ): 'provisioning' | 'thinking' | 'idle' => {// A read-only snapshot never provisions or thinks — there is no live stream behind it.if (replayOnly) {return 'idle'}const connecting = sseStatus === 'connecting' || sseStatus === 'open' || sseStatus === 'reconnecting'- if (connecting && !runStarted && !isTerminalRunStatus(currentRunStatus)) {+ // `runOpening` covers the conversations/open POST window, before any SSE state exists.+ if ((connecting || runOpening) && !runStarted && !isTerminalRunStatus(currentRunStatus)) {return 'provisioning'}if (isThinking) {