: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(tasks): keep task starts and follow-ups visible (#97429)
Georgiy Tarasov096fb6eca247
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.mdindex ae7bbbb4d278..bfb0aebe95c3 100644--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md@@ -29,6 +29,10 @@ If it just needs to _answer a question_ given some context you already have, useA sandboxed agent runs inside an isolated cloud container (Modal in production, Docker locally).The system provisions the sandbox, clones a GitHub repo, starts an agent server, and waits for the agent to finish.+The run thread shows startup state in a progress accordion, with completed steps available in its history.+Before progress arrives, it shows "Setting up sandbox", including when resuming a finished run.+The thread hides empty and whitespace-only assistant messages during streaming and history replay.+```textYour product code│diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex 8861b3cb161b..ae6713529fbf 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -312,8 +312,15 @@ export interface maxThreadLogicActions {clearSandboxAttachments: () => {value: true} // posthogAiContextLogic- bootstrapSandboxRun: (payload: { justCreatedRun?: boolean; runId: string; taskId: string; traceId?: string }) => {+ bootstrapSandboxRun: (payload: {+ justCreatedRun?: boolean+ retainedMessage?: string+ runId: string+ taskId: string+ traceId?: string+ }) => {justCreatedRun?: boolean | undefined+ retainedMessage?: string | undefinedrunId: stringtaskId: stringtraceId?: string | undefineddiff --git a/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.ts b/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.tsindex 0eaaabae0680..b6dc9c2205c2 100644--- a/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.ts+++ b/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.ts@@ -42,7 +42,7 @@ describe('phaiSidePanelComposerSeedLogic', () => {},'/api/projects/:team/tasks/:id/run/': () => {runCount++- return [200, { id: 'new-task' }]+ return [200, { id: 'new-task', latest_run: { id: 'run-1' } }]},},})@@ -99,6 +99,6 @@ describe('phaiSidePanelComposerSeedLogic', () => {expect(createCount).toBe(1)expect(runCount).toBe(1)- expect(trackerLogic.values.activeCreation).toMatchObject({ taskId: 'new-task' })+ expect(trackerLogic.values.activeCreation).toMatchObject({ taskId: 'new-task', runId: 'run-1' })})})diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsxindex f35138ac6e28..8b2f7b01e2fb 100644--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx@@ -45,6 +45,7 @@ function setValues(;(useValues as jest.Mock).mockReturnValue({bootstrapLoading: false,threadItems: [],+ hasThreadItems: !!overrides.threadItems?.length,pendingPermissionRequest: null,respondingToPermission: false,currentRunStatus: 'in_progress',@@ -76,7 +77,21 @@ function renderLiveWithComposer(statusOrOverrides: RunStatus | null | Parametersfunction DraftComposer(): JSX.Element {const [saved, setSaved] = useState('')const draft = useDebouncedDraft(saved, setSaved)- return <textarea data-attr="draft" value={draft.value} onChange={(event) => draft.onChange(event.target.value)} />+ return (+ <>+ <textarea data-attr="draft" value={draft.value} onChange={(event) => draft.onChange(event.target.value)} />+ <button+ onClick={() =>+ draft.submit(() => {+ setSaved('')+ return ''+ })+ }+ >+ Send draft+ </button>+ </>+ )}describe('RunSurface', () => {@@ -121,6 +136,20 @@ describe('RunSurface', () => {})describe('Composer slot', () => {+ it('clears a draft sent before its debounce commits', () => {+ jest.useFakeTimers()+ try {+ render(<DraftComposer />)+ fireEvent.change(screen.getByTestId('draft'), { target: { value: 'Continue' } })+ fireEvent.click(screen.getByText('Send draft'))+ expect(screen.getByTestId('draft')).toHaveValue('')+ act(() => jest.runOnlyPendingTimers())+ expect(screen.getByTestId('draft')).toHaveValue('')+ } finally {+ jest.useRealTimers()+ }+ })+it.each<RunStatus>(['queued', 'in_progress'])('renders the composer children for an active run (%s)',(status) => {@@ -249,26 +278,32 @@ describe('RunSurface', () => {})describe('Thread slot', () => {- it('shows the run-log skeleton while bootstrapping with no thread items yet', () => {- setValues({ bootstrapLoading: true, threadItems: [] })- render(- <RunSurface.Root taskId="task-1" runId="run-1" interaction="read-only">- <RunSurface.Thread />- </RunSurface.Root>- )- expect(screen.getByTestId('run-log-skeleton')).toBeInTheDocument()- expect(screen.queryByTestId('thread')).not.toBeInTheDocument()- })+ it.each([null, { origin_product: 'user_created' }])(+ 'shows the run-log skeleton with no thread items and task=%j',+ (task) => {+ setValues({ bootstrapLoading: true, threadItems: [], task })+ render(+ <RunSurface.Root taskId="task-1" runId="run-1" interaction="read-only">+ <RunSurface.Thread />+ </RunSurface.Root>+ )+ expect(screen.getByTestId('run-log-skeleton')).toBeInTheDocument()+ expect(screen.queryByTestId('thread')).not.toBeInTheDocument()+ }+ )- it('swaps the skeleton for the thread once items arrive', () => {- setValues({ bootstrapLoading: true, threadItems: [{ id: 'x' }] })- render(- <RunSurface.Root taskId="task-1" runId="run-1" interaction="read-only">- <RunSurface.Thread />- </RunSurface.Root>- )- expect(screen.getByTestId('thread')).toBeInTheDocument()- expect(screen.queryByTestId('run-log-skeleton')).not.toBeInTheDocument()- })+ it.each([null, { origin_product: 'user_created' }])(+ 'keeps a populated thread visible while bootstrapping with task=%j',+ (task) => {+ setValues({ bootstrapLoading: true, threadItems: [{ id: 'x' }], task })+ render(+ <RunSurface.Root taskId="task-1" runId="run-1" interaction="read-only">+ <RunSurface.Thread />+ </RunSurface.Root>+ )+ expect(screen.getByTestId('thread')).toBeInTheDocument()+ expect(screen.queryByTestId('run-log-skeleton')).not.toBeInTheDocument()+ }+ )})})diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsxindex e6d9f0f1d924..4a618644df85 100644--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx@@ -90,6 +90,7 @@ function RunSurfaceRoot({const replayOnly = interaction !== 'live'// A pending surface (no run id) must supply `streamKey` to key on; `runId` is the key otherwise.const logicKey = streamKey ?? runId ?? ''+ const { hasThreadItems } = useValues(runStreamLogic({ streamKey: logicKey, conversationId, replayOnly }))// The runtime and scout flag live on the task (not the run), so the surface owns loading it once and// exposing it to the slots. The runner already has the task loaded; an embed fetches it here.@@ -113,7 +114,10 @@ function RunSurfaceRoot({</LemonBanner>)}- return <RunLogSkeleton />+ // A created task's metadata fetch must not replace its already visible optimistic thread.+ if (!hasThreadItems) {+ return <RunLogSkeleton />+ }}if (task && isPiTaskRuntime(task.runtime)) {@@ -189,7 +193,7 @@ function RunSurfaceThread({rowClassName,}: { className?: string; listClassName?: string; rowClassName?: string } = {}): JSX.Element {const { interaction, isScout, taskId, streamKey, runId } = useRunSurfaceContext()- const { bootstrapLoading, threadItems } = useValues(runStreamLogic)+ const { bootstrapLoading, hasThreadItems } = useValues(runStreamLogic)// Feedback identity: always the task, matching `$ai_session_id` on other surfaces.const feedbackSessionId = taskIdconst collectsFeedback = interaction === 'live' && !isScout && !!feedbackSessionId@@ -216,7 +220,7 @@ function RunSurfaceThread({) : null,[feedbackSessionId, feedbackRun])- const showSkeleton = bootstrapLoading && threadItems.length === 0+ const showSkeleton = bootstrapLoading && !hasThreadItemsif (showSkeleton) {return <RunLogSkeleton className={className} listClassName={listClassName} rowClassName={rowClassName} />}diff --git a/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx b/products/posthog_ai/frontend/components/ThreadView.connection.test.tsxindex b7ec2b18a214..476d948d3244 100644--- a/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx+++ b/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx@@ -1,6 +1,6 @@import '@testing-library/jest-dom'-import { cleanup, render, screen, waitFor } from '@testing-library/react'+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { BindLogic, Provider } from 'kea'import { initKeaTests } from '~/test/init'@@ -26,7 +26,7 @@ describe('ThreadView connection state', () => {render(<Provider><BindLogic logic={runStreamLogic} props={props}>- <ThreadView virtualized={false} />+ <ThreadView virtualized={false} showContextUsage /></BindLogic></Provider>)@@ -75,4 +75,89 @@ describe('ThreadView connection state', () => {expect(screen.queryByText('Reconnecting to agent')).toBeNull()expect(screen.queryByText('Connection lost')).toBeNull()})++ it('hides context usage and cost during an optimistic resume and restores them on failure', async () => {+ act(() => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', {+ group: 'setup:previous-run',+ step: 'agent',+ status: 'completed',+ label: 'Started agent',+ }),+ 'replay'+ )+ logic.actions.setContextUsage({ used: 12000, size: 1000000, cost: 0.04 })+ logic.actions.handleTerminalStatus({ status: 'completed', replayedFromHistory: true })+ })+ await waitFor(() => expect(screen.getByTestId('max-sandbox-context-usage')).toBeVisible())++ act(() => logic.actions.startOptimisticResume('Continue'))+ await waitFor(() => expect(screen.queryByTestId('max-sandbox-context-usage')).toBeNull())+ expect(screen.getByText('Setting up sandbox')).toBeVisible()++ act(() => logic.actions.rollbackOptimisticResume())+ await waitFor(() => expect(screen.getByTestId('max-sandbox-context-usage')).toBeVisible())+ expect(screen.getByText('$0.04')).toBeVisible()+ })++ it('uses the startup activity as the state indicator and keeps completed steps expandable', async () => {+ act(() => logic.actions.sseOpened())+ await waitFor(() => expect(screen.getByText('Setting up sandbox')).toBeVisible())++ act(() => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', {+ group: 'setup:run-1',+ step: 'sandbox',+ status: 'in_progress',+ label: 'Restoring sandbox',+ })+ )+ })+ await waitFor(() => expect(screen.getByText('Restoring sandbox')).toBeVisible())+ expect(screen.queryByText('Setting up sandbox')).toBeNull()++ act(() => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', {+ group: 'setup:run-1',+ step: 'sandbox',+ status: 'completed',+ label: 'Restored sandbox',+ })+ )+ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', {+ group: 'setup:run-1',+ step: 'agent',+ status: 'in_progress',+ label: 'Starting agent',+ })+ )+ })+ await waitFor(() => expect(screen.getByText('Starting agent', { exact: true })).toBeVisible())+ expect(screen.getByLabelText('Expand history')).toHaveAttribute('aria-expanded', 'false')+ expect(screen.queryByText('Setting up sandbox')).toBeNull()++ act(() => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', {+ group: 'setup:run-1',+ step: 'agent',+ status: 'completed',+ label: 'Started agent',+ })+ )+ })+ await waitFor(() => expect(screen.getByLabelText('Expand history')).toHaveAttribute('aria-expanded', 'false'))+ expect(screen.getByText('Started agent')).toBeVisible()+ expect(screen.queryByText('Setting up sandbox')).toBeNull()++ act(() => logic.actions.ingestAcpFrame(notification('_posthog/run_started', {})))+ await waitFor(() => expect(screen.queryByText('Setting up sandbox')).toBeNull())+ fireEvent.click(screen.getByLabelText('Expand history'))+ expect(screen.getByText('Restored sandbox')).toBeVisible()+ expect(screen.getAllByText('Started agent')).toHaveLength(2)+ })})diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsxindex f9096aa4534c..4b48ceca1f59 100644--- a/products/posthog_ai/frontend/components/ThreadView.tsx+++ b/products/posthog_ai/frontend/components/ThreadView.tsx@@ -158,7 +158,7 @@ export function ThreadView({const pullRequestUrl = !isThinking ? runArtifacts.prUrl : undefined// Context usage rides the thread footer, but only between turns (idle) — never while the agent is// working, where the thinking line takes the footer. `ContextUsageBar` self-hides without data.- const showContextUsageFooter = showContextUsage && !isThinking && !!contextUsage+ const showContextUsageFooter = showContextUsage && streamPhase === 'idle' && !!contextUsageconst footer = useMemo(() =>showThinking || pullRequestUrl || showContextUsageFooter || showConnectionStatus || footerExtra ? (@@ -315,7 +315,12 @@ const ThreadFooter = memo(function ThreadFooter({return (<div className="flex flex-col gap-1.5">{showConnectionStatus && runConnectionState && <RunAlertActivity {...runConnectionState} />}- {showThinking && <ThinkingIndicator progress={currentProgress} phase={thinkingPhase} />}+ {showThinking && (+ <ThinkingIndicator+ progress={thinkingPhase === 'provisioning' ? null : currentProgress}+ phase={thinkingPhase}+ />+ )}{pullRequestUrl && <PullRequestCard prUrl={pullRequestUrl} branch={prBranch} />}{showContextUsage && <ContextUsageBar />}{extra}diff --git a/products/posthog_ai/frontend/components/composer/useDebouncedDraft.ts b/products/posthog_ai/frontend/components/composer/useDebouncedDraft.tsindex ade32aa8e2d0..07e21a392083 100644--- a/products/posthog_ai/frontend/components/composer/useDebouncedDraft.ts+++ b/products/posthog_ai/frontend/components/composer/useDebouncedDraft.ts@@ -7,7 +7,8 @@ export interface DebouncedDraft {/** Bind to `Composer.Root`'s `onChange` — updates the local echo now, syncs upstream on a debounce. */onChange: (next: string) => void/** Wrap the caller's submit so the latest keystroke is flushed to the owning logic before it reads the draft. */- submit: (send: () => void) => void+ submit: (send: () => string | void) => void+ flush: () => void}/**@@ -39,15 +40,20 @@ export function useDebouncedDraft(externalValue: string, sync: (value: string) =return {value,+ flush: debouncedSync.flush,onChange: (next: string): void => {setValue(next)debouncedSync(next)},- submit: (send: () => void): void => {+ submit: (send: () => string | void): void => {// Flush the pending keystroke synchronously so the send reads the latest draft, not the stale// debounced value; a no-op when nothing is pending (kea already has it).debouncedSync.flush()- send()+ const nextValue = send()+ // A flush and reset can batch back to the original external value, skipping its effect.+ if (typeof nextValue === 'string') {+ setValue(nextValue)+ }},}}diff --git a/products/posthog_ai/frontend/e2e/run-surface.spec.ts b/products/posthog_ai/frontend/e2e/run-surface.spec.tsindex 36881dce26b6..f7d8ec690183 100644--- a/products/posthog_ai/frontend/e2e/run-surface.spec.ts+++ b/products/posthog_ai/frontend/e2e/run-surface.spec.ts@@ -1,8 +1,5 @@-// End-to-end coverage for the three run-surface connection states that only a real browser can prove:-// a terminal run's inline error card, the live reconnecting banner on a stream drop, and the terminal-// "Connection lost" card when the run history keeps failing. The whole tasks/runs API is mocked with-// `page.route` so each state is deterministic; everything else (login, project, feature flags) rides the-// real workspace harness, mirroring the surveys e2e precedent.+// Task and run API responses are mocked so the browser can hold creation, metadata, and stream+// transitions independently. Login, project, and feature flags use the real workspace harness.import { mockFeatureFlags } from '@playwright-utils/mockApi'import { PlaywrightWorkspaceSetupResult, expect, test } from '@playwright-utils/workspace-test-base'@@ -158,6 +155,25 @@ async function openRunDeepLink(page: Page, teamId: string): Promise<void> {const ph = (window as unknown as { posthog?: { reloadFeatureFlags?: () => void } }).posthogph?.reloadFeatureFlags?.()})+ await expect(page.getByRole('heading', { name: 'Run surface e2e task', exact: true })).toBeVisible({+ timeout: 40000,+ })+}++async function acceptConsentInPage(page: Page): Promise<void> {+ await page.addInitScript(() => {+ let appContext: { current_user?: { organization?: { is_ai_data_processing_approved?: boolean } } }+ Object.defineProperty(window, 'POSTHOG_APP_CONTEXT', {+ configurable: true,+ get: () => appContext,+ set: (value: typeof appContext) => {+ if (value.current_user?.organization) {+ value.current_user.organization.is_ai_data_processing_approved = true+ }+ appContext = value+ },+ })+ })}test.describe('Task run surface', () => {@@ -192,6 +208,274 @@ test.describe('Task run surface', () => {await expect(page.getByText('Agent error')).toBeVisible({ timeout: 20000 })})+ for (const [surface, path] of [+ ['task page', 'tasks/new'],+ ['side panel', 'settings/user#panel=max'],+ ]) {+ test(`new tasks start optimistically and recover from failure in the ${surface}`, async ({ page }) => {+ const message = 'Explain how to compare weekly activity.'+ let finishCreation!: (succeeded: boolean) => void+ let creationResponse = new Promise<boolean>((resolve) => {+ finishCreation = resolve+ })+ let revealMetadata!: () => void+ const metadataReady = new Promise<void>((resolve) => {+ revealMetadata = resolve+ })+ let startAgent!: () => void+ const agentReady = new Promise<void>((resolve) => {+ startAgent = resolve+ })+ await acceptConsentInPage(page)+ await mockFeatureFlags(page, {+ [TASKS_FLAG]: true,+ [TASKS_STREAM_VIA_PROXY_FLAG]: false,+ 'phai-sandbox-mode': true,+ })+ await routeTasksApi(page, {+ runStatus: 'queued',+ logs: { status: 200, body: '' },+ stream: { mode: 'hang' },+ })+ await page.route(+ (url) => url.pathname.endsWith('/tasks/'),+ async (route) => {+ if (route.request().method() === 'GET') {+ await fulfillJson({ results: [], count: 0 })(route)+ return+ }+ const succeeded = await creationResponse+ await route.fulfill({+ status: succeeded ? 201 : 500,+ contentType: 'application/json',+ body: JSON.stringify(+ succeeded ? { ...makeTask('queued'), latest_run: null } : { detail: 'Failed' }+ ),+ })+ }+ )+ await page.route((url) => url.pathname.endsWith('/tasks/repositories/'), fulfillJson({ repositories: [] }))+ await page.route(+ (url) => url.pathname.endsWith('/tasks/warm/'),+ (route) => route.fulfill({ status: 503 })+ )+ await page.route((url) => url.pathname.endsWith(`/tasks/${TASK_ID}/run/`), fulfillJson(makeTask('queued')))+ await page.route(+ (url) => url.pathname.endsWith(`/tasks/${TASK_ID}/`),+ async (route) => {+ await metadataReady+ await fulfillJson({ ...makeTask('queued'), created_by: null })(route)+ }+ )+ await page.route(+ (url) => new RegExp(`/runs/${RUN_ID}/stream/?$`).test(url.pathname),+ async (route) => {+ await agentReady+ await route.fulfill({+ contentType: 'text/event-stream',+ body:+ toSse([+ {+ type: 'notification',+ notification: { method: '_posthog/run_started', params: { runId: RUN_ID } },+ },+ {+ type: 'notification',+ notification: { method: '_posthog/user_message', params: { content: message } },+ },+ agentMessageFrame('first-answer', 'Start by grouping activity by week.'),+ ]) + 'data: {"type":"task_run_state","status":"completed"}\n\n',+ })+ }+ )++ await page.goto(`/project/${workspace!.team_id}/${path}`)+ const composer = page.getByTestId('task-composer-input')+ await expect(composer).toBeVisible({ timeout: 40000 })+ await composer.fill(message)+ await composer.press('Enter')+ await expect(page.getByText(message, { exact: true })).toBeVisible()+ await expect(page.getByText('Setting up sandbox', { exact: false })).toBeVisible()+ await expect(page.getByTestId('run-log-skeleton')).toHaveCount(0)++ finishCreation(false)+ await expect(composer).toHaveValue(message)+ await expect(page.getByText('Setting up sandbox', { exact: false })).toHaveCount(0)+ creationResponse = new Promise<boolean>((resolve) => {+ finishCreation = resolve+ })+ await composer.press('Enter')+ await expect(page.getByText(message, { exact: true })).toBeVisible()+ finishCreation(true)++ await expect(page.getByTestId('sandbox-composer-input')).toBeVisible()+ await expect(page.getByText(message, { exact: true })).toHaveCount(1)+ await expect(page.getByText('Setting up sandbox', { exact: false })).toBeVisible()+ await expect(page.getByTestId('run-log-skeleton')).toHaveCount(0)+ await page.screenshot({ path: test.info().outputPath('new-task-starting.png') })++ startAgent()+ await expect(page.getByText('Start by grouping activity by week.', { exact: true })).toBeVisible()+ await expect(page.getByText(message, { exact: true })).toHaveCount(1)+ revealMetadata()+ await expect(page.getByTestId('sandbox-composer-input')).toBeVisible()+ await expect(page.getByTestId('run-log-skeleton')).toHaveCount(0)+ })+ }++ test('resuming a finished sandbox keeps the thread and pending message visible', async ({ page }) => {+ const successorId = '0190a000-0000-4000-8000-0000000000c3'+ const successor = { ...makeRun('queued'), id: successorId, state: { resume_from_run_id: RUN_ID } }+ let acceptRun!: () => void+ const runAccepted = new Promise<void>((resolve) => {+ acceptRun = resolve+ })+ let startAgent!: () => void+ const agentStarted = new Promise<void>((resolve) => {+ startAgent = resolve+ })++ await routeTasksApi(page, {+ runStatus: 'completed',+ logs: {+ status: 200,+ body: toJsonl([+ {+ type: 'notification',+ notification: {+ method: '_posthog/progress',+ params: {+ group: `setup:${RUN_ID}`,+ step: 'agent',+ status: 'completed',+ label: 'Started agent',+ },+ },+ },+ agentMessageFrame('m1', 'The earlier answer stays here.'),+ {+ type: 'notification',+ notification: {+ method: 'session/update',+ params: {+ update: {+ sessionUpdate: 'usage_update',+ used: 12000,+ size: 1000000,+ cost: { amount: 0.04, currency: 'USD' },+ },+ },+ },+ },+ ]),+ },+ stream: { mode: 'hang' },+ })+ await acceptConsentInPage(page)+ await page.route(+ (url) => url.pathname.endsWith(`/tasks/${TASK_ID}/`),+ fulfillJson({ ...makeTask('completed'), created_by: null })+ )+ await page.route(+ (url) => url.pathname.endsWith(`/tasks/${TASK_ID}/warm/`),+ fulfillJson({ run_id: successorId, task_id: TASK_ID })+ )+ await page.route(+ (url) => url.pathname.endsWith(`/tasks/${TASK_ID}/run/`),+ async (route) => {+ await runAccepted+ await fulfillJson({ ...makeTask('queued'), latest_run: successor })(route)+ }+ )+ await page.route((url) => url.pathname.endsWith(`/runs/${successorId}/`), fulfillJson(successor))+ await page.route(+ (url) => url.pathname.endsWith(`/runs/${successorId}/stream_token/`),+ fulfillJson({ token: 'e2e-token', stream_base_url: null })+ )+ await page.route(+ (url) => new RegExp(`/runs/${successorId}/stream/?$`).test(url.pathname),+ async (route) => {+ await agentStarted+ await route.fulfill({+ contentType: 'text/event-stream',+ body:+ toSse([+ {+ type: 'notification',+ notification: {+ method: '_posthog/progress',+ params: {+ group: `setup:${successorId}`,+ step: 'sandbox',+ status: 'completed',+ label: 'Restored sandbox',+ },+ },+ },+ {+ type: 'notification',+ notification: {+ method: '_posthog/progress',+ params: {+ group: `setup:${successorId}`,+ step: 'agent',+ status: 'completed',+ label: 'Started agent',+ },+ },+ },+ {+ type: 'notification',+ notification: { method: '_posthog/run_started', params: { runId: successorId } },+ },+ {+ type: 'notification',+ notification: {+ method: '_posthog/user_message',+ params: { content: 'Continue with the next step.' },+ },+ },+ agentMessageFrame('m2', 'The next step is ready.'),+ ]) + 'data: {"type":"task_run_state","status":"completed"}\n\n',+ })+ }+ )++ await openRunDeepLink(page, workspace!.team_id)+ await expect(page.getByText('The earlier answer stays here.', { exact: true })).toBeVisible({ timeout: 30000 })+ await expect(page.getByTestId('max-sandbox-context-usage')).toBeVisible()+ await expect(page.getByText('Started agent', { exact: true })).toBeVisible()+ const composer = page.getByTestId('sandbox-composer-input')+ await composer.fill('Continue with the next step.')+ await page.getByTestId('sandbox-composer-send').click()+ await expect(page.getByText('Continue with the next step.', { exact: true })).toHaveCount(1)+ await expect(page.getByText('Setting up sandbox', { exact: false })).toBeVisible()+ await expect(composer).toHaveValue('')+ await expect(page.getByTestId('max-sandbox-context-usage')).toHaveCount(0)+ await expect(page.getByTestId('sandbox-composer-send')).toBeDisabled()+ await expect(page.getByTestId('run-log-skeleton')).toHaveCount(0)++ await composer.fill('Keep this newer draft.')+ acceptRun()+ await expect(page.getByTestId('sandbox-composer-send')).toBeEnabled()+ await expect(composer).toHaveValue('Keep this newer draft.')+ await expect(page.getByTestId('max-sandbox-context-usage')).toHaveCount(0)+ await expect(page.getByText('The earlier answer stays here.', { exact: true })).toBeVisible()+ await expect(page.getByText('Continue with the next step.', { exact: true })).toHaveCount(1)+ await expect(page.getByText('Setting up sandbox', { exact: false })).toBeVisible()+ await expect(page.getByTestId('run-log-skeleton')).toHaveCount(0)++ startAgent()+ await expect(page.getByText('The next step is ready.', { exact: true })).toBeVisible()+ await expect(page.getByText('Continue with the next step.', { exact: true })).toHaveCount(1)+ await expect(page.getByText('Restored sandbox', { exact: true })).toHaveCount(0)+ await expect(page.getByText('Started agent', { exact: true })).toHaveCount(2)+ await page.getByRole('button', { name: 'Expand history', exact: true }).click()+ await expect(page.getByText('Restored sandbox', { exact: true })).toBeVisible()+ await page.screenshot({ path: test.info().outputPath('resumed-sandbox-startup-history.png') })+ await expect(composer).toHaveValue('Keep this newer draft.')+ })+test('live stream drop shows the reconnecting banner', async ({ page }) => {// Regression: a clean-EOF drop on an in-progress run must surface the reconnecting banner (the backoff// loop) rather than silently stalling or reading as ordinary thinking.diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.tsindex 71751833ce34..f0915ba248b6 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts@@ -34,6 +34,9 @@ jest.mock('./runStreamLogic', () => {key((p: { streamKey: string }) => p.streamKey),actions({pushHumanMessage: (content: string) => ({ content }),+ startOptimisticResume: (message: string) => ({ message }),+ rollbackOptimisticResume: true,+ attachOptimisticResume: (taskId: string, run: unknown) => ({ taskId, run }),pushConversationCleared: true,respondToPermission: (payload: unknown) => ({ payload }),cancelRun: (run?: unknown) => ({ run }),@@ -682,11 +685,21 @@ describe('runInteractionLogic', () => {})it('starts a fresh run seeded with the message when the run is terminal', async () => {+ let resolveRun!: (value: unknown) => void+ ;(tasksRunCreate as jest.Mock).mockReturnValueOnce(+ new Promise((resolve) => {+ resolveRun = resolve+ })+ )setStatus('completed')logic.actions.setComposerFormValues({ draft: 'continue from here' })+ logic.actions.submitComposerForm()+ expect(logic.values.composerForm.draft).toBe('')+ expect(logic.values.startingRun).toBe(true)+ logic.actions.setComposerFormValues({ draft: 'also check the result' })await expectLogic(logic, () => {- logic.actions.submitComposerForm()+ resolveRun({ latest_run: { id: 'run-2' } })}).toFinishAllListeners()// No live-run signal for a finished run — it resumes into a new run instead.@@ -704,15 +717,49 @@ describe('runInteractionLogic', () => {},expect.objectContaining({ signal: expect.any(AbortSignal) }))- expect(onRunStarted).toHaveBeenCalledWith('run-2')- expect(toolEvents.values.applyBackTargetClaims[RUN_ID]).toBeUndefined()- expect(toolEvents.values.applyBackTargetClaims['run-2']).toEqual([+ expect(onRunStarted).toHaveBeenCalledWith(+ 'run-2',+ expect.objectContaining({ streamKey: RUN_ID, draft: 'also check the result' })+ )+ expect(toolEvents.values.applyBackTargetClaims[RUN_ID]).toEqual([{ targetId: 'insight-1:activation-1', tools: ['create_insight'] },])expect(logic.values.queuedMessages).toEqual([])- expect(logic.values.composerForm.draft).toBe('')+ expect(logic.values.composerForm.draft).toBe('also check the result')})+ it.each(['failure', 'missing run'])(+ 'restores the submitted message ahead of a newer draft after %s',+ async (outcome) => {+ let resolveRun!: (value: unknown) => void+ let rejectRun!: (error: Error) => void+ ;(tasksRunCreate as jest.Mock).mockReturnValueOnce(+ new Promise((resolve, reject) => {+ resolveRun = resolve+ rejectRun = reject+ })+ )+ setStatus('completed')+ logic.actions.setComposerFormValues({ draft: 'continue from here' })+ logic.actions.submitComposerForm()+ expect(logic.values.composerForm.draft).toBe('')+ logic.actions.setComposerFormValues({ draft: 'and check the tests' })++ await expectLogic(logic, () => {+ if (outcome === 'failure') {+ rejectRun(new Error('failed'))+ } else {+ resolveRun({ latest_run: null })+ }+ }).toFinishAllListeners()++ expect(logic.values.composerForm.draft).toBe('continue from here\n\nand check the tests')+ expect(logic.values.startingRun).toBe(false)+ expect(onRunStarted).not.toHaveBeenCalled()+ expect(lemonToast.error).toHaveBeenCalledWith('Failed to start a new run. Please try again.')+ }+ )+it('warms the resumed run while composing and consumes it before submit', async () => {jest.useFakeTimers()setStatus('cancelled')@@ -817,7 +864,7 @@ describe('runInteractionLogic', () => {logic.actions.submitComposerForm()expect(logic.values.startingRun).toBe(true)- expect(logic.values.composerForm.draft).toBe('continue from here')+ expect(logic.values.composerForm.draft).toBe('')expect(attachedContextLogic().values.sentContextKeysByTask[TASK_ID]).toBeUndefined()await expectLogic(logic, () => {@@ -837,7 +884,7 @@ describe('runInteractionLogic', () => {expect((tasksRunCreate as jest.Mock).mock.calls[1].slice(0, 3)).toEqual((tasksRunCreate as jest.Mock).mock.calls[0].slice(0, 3))- expect(onRunStarted).toHaveBeenCalledWith('run-2')+ expect(onRunStarted).toHaveBeenCalledWith('run-2', expect.objectContaining({ streamKey: RUN_ID, draft: '' }))expect(logic.values.composerForm.draft).toBe('')expect(logic.values.startingRun).toBe(false)expect(attachedContextLogic().values.sentContextKeysByTask[TASK_ID]).toEqual(['insight:sig'])@@ -881,7 +928,7 @@ describe('runInteractionLogic', () => {expect(call[3].headers).toEqual({ 'X-PostHog-Warm-Retry': 'synthetic-retry-token' })}expect(logic.values.startingRun).toBe(true)- expect(logic.values.composerForm.draft).toBe('continue from here')+ expect(logic.values.composerForm.draft).toBe('')expect(attachedContextLogic().values.sentContextKeysByTask[TASK_ID]).toBeUndefined()logic.actions.submitComposerForm()expect(tasksRunCreate).toHaveBeenCalledTimes(4)@@ -909,7 +956,10 @@ describe('runInteractionLogic', () => {expect(tasksRunCreate).toHaveBeenCalledTimes(4)expect(logic.values.startingRun).toBe(false)if (outcome === 'recovered') {- expect(onRunStarted).toHaveBeenCalledWith('warm-run')+ expect(onRunStarted).toHaveBeenCalledWith(+ 'warm-run',+ expect.objectContaining({ streamKey: RUN_ID, draft: '' })+ )expect(logic.values.composerForm.draft).toBe('')} else {expect(onRunStarted).not.toHaveBeenCalled()@@ -1024,7 +1074,7 @@ describe('runInteractionLogic', () => {const createRequest = (tasksRunCreate as jest.Mock).mock.calls[0][2] as { pending_user_message: string }expect(createRequest.pending_user_message).toContain('- insight sig ("Signups")')- expect(onRunStarted).toHaveBeenCalledWith('run-2')+ expect(onRunStarted).toHaveBeenCalledWith('run-2', expect.objectContaining({ streamKey: RUN_ID, draft: '' }))// The consumer re-points to the new run: a fresh logic instance keyed by the new runId, same task.// Sent-context bookkeeping is task-scoped, so the first follow-up must not re-wrap the same ref.@@ -1133,6 +1183,47 @@ describe('runInteractionLogic', () => {expect(logic.values.composerForm.draft).toBe('ship it\n\nnext thought')})+ it('flushes a keystroke still buffered in the composer before restoring a failed draft send', async () => {+ // The composer debounces its writes to kea, so text typed in the last moments of an in-flight send+ // is still local. Restoring the failed message cancels that pending sync, so it has to be landed+ // first or it is dropped instead of merged behind the retry.+ let pendingKeystroke = ''+ const attached = runInteractionLogic({+ taskId: TASK_ID,+ runId: 'flush-run',+ onRunStarted,+ flushDraft: () => {+ if (pendingKeystroke) {+ attached.actions.setComposerFormValues({ draft: pendingKeystroke })+ pendingKeystroke = ''+ }+ },+ })+ const unmount = attached.mount()+ try {+ let rejectSend: () => void = () => {}+ ;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(+ new Promise<void>((_, reject) => {+ rejectSend = () => reject(new Error('boom'))+ })+ )++ attached.actions.setComposerFormValues({ draft: 'ship it' })+ attached.actions.submitComposerForm()+ expect(attached.values.composerForm.draft).toBe('')++ pendingKeystroke = 'next thought'++ await expectLogic(attached, () => {+ rejectSend()+ }).toFinishAllListeners()++ expect(attached.values.composerForm.draft).toBe('ship it\n\nnext thought')+ } finally {+ unmount()+ }+ })+it('keeps a follow-up typed during an in-flight queue flush instead of clearing it with the send', async () => {let resolveSend: () => void = () => {};(tasksRunsCommandCreate as jest.Mock).mockReturnValue(diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.tsindex a497dd1e690f..3848130fda2c 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts@@ -27,6 +27,7 @@ import {type ModelChoiceApi,type ReasoningEffortEnumApi,RuntimeAdapterEnumApi,+ type TaskRunDetailDTOApi,type WarmTaskResumeRequestApi,} from 'products/tasks/frontend/generated/api.schemas'@@ -55,6 +56,7 @@ export interface RunInteractionLogicProps {streamKey?: stringinitialDraft?: stringonDraftAdopted?: () => void+ flushDraft?: () => void/** The run's stored model / reasoning effort / launch mode, injected by the consumer. They seed the picker's* display and the config a terminal-run send launches the next run with (override ?? this ?? default). */currentModel?: string | null@@ -64,7 +66,13 @@ export interface RunInteractionLogicProps {currentRuntimeAdapter?: string | null/** Called with the new run's id after a terminal-run send starts a fresh run, so the surface can* re-point selection to it (the run lifecycle / selection is a tasks-scene concern, injected here). */- onRunStarted?: (runId: string) => void+ onRunStarted?: (runId: string, handoff?: RunContinuationHandoff) => void+}++export interface RunContinuationHandoff {+ run: TaskRunDetailDTOApi+ streamKey: string+ draft: string}/** The follow-up staged in the "Up next" buffer while the agent is mid-turn. */@@ -172,6 +180,13 @@ export interface runInteractionLogicActions {requestCancellation: () => {value: true} // runCancellationLogic+ attachOptimisticResume: (+ taskId: string,+ run: TaskRunDetailDTOApi+ ) => {+ run: TaskRunDetailDTOApi+ taskId: string+ } // runStreamLogiccancelPermissionDelivery: () => {value: true} // runStreamLogic@@ -241,9 +256,15 @@ export interface runInteractionLogicActions {optionId: stringrequestId: string} // runStreamLogic+ rollbackOptimisticResume: () => {+ value: true+ } // runStreamLogicsetCurrentMode: (mode: string) => {mode: string} // runStreamLogic+ startOptimisticResume: (message: string) => {+ message: string+ } // runStreamLogicconsumeWarm: () => {value: true} // taskWarmLogic@@ -263,13 +284,6 @@ export interface runInteractionLogicActions {releaseApplyBackTargets: (streamKey: string) => {streamKey: string} // toolStreamEventsLogic- transferApplyBackTargets: (- fromStreamKey: string,- toStreamKey: string- ) => {- fromStreamKey: string- toStreamKey: string- } // toolStreamEventsLogicblockOnConsent: (source?: 'draft' | 'queue' | 'steer') => {source: 'draft' | 'queue' | 'steer'}@@ -511,6 +525,9 @@ export const runInteractionLogic = kea<runInteractionLogicType>([runStreamLogic({ streamKey: props.streamKey ?? props.runId }),['pushHumanMessage',+ 'startOptimisticResume',+ 'rollbackOptimisticResume',+ 'attachOptimisticResume','pushConversationCleared','respondToPermission','cancelRun',@@ -528,7 +545,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([attachedContextLogic,['markContextSent'],toolStreamEventsLogic,- ['claimApplyBackTargets', 'transferApplyBackTargets', 'releaseApplyBackTargets'],+ ['claimApplyBackTargets', 'releaseApplyBackTargets'],taskWarmLogic({ taskId: props.taskId, resumeFromRunId: props.runId }),['noteDraft', 'consumeWarm', 'releaseWarm'],runCancellationLogic({ streamKey: props.streamKey ?? props.runId }),@@ -1115,6 +1132,9 @@ export const runInteractionLogic = kea<runInteractionLogicType>([// Restore unsent content for retry, preserving send order — draft content goes back ahead of// anything typed during the failed send, queue content re-stages ahead of anything staged since.if (source === 'draft') {+ // Land the pending keystroke first: writing the draft cancels the composer's debounced+ // sync, so text typed inside that window would be dropped rather than merged behind.+ props.flushDraft?.()actions.setComposerFormValues({draft: values.composerForm.draft ? `${content}\n\n${values.composerForm.draft}` : content,})@@ -1166,10 +1186,28 @@ export const runInteractionLogic = kea<runInteractionLogicType>([}actions.setStartingRun(true)const streamKey = props.streamKey ?? props.runId- let claimedStreamKey = streamKeyconst pendingContext = values.pendingContextItemsconst disposables = cache.disposablesconst projectId = String(values.currentProjectId)+ const taskId = props.taskId+ const runId = props.runId+ const isCurrent = (): boolean =>+ !disposables.isDisposed &&+ String(values.currentProjectId) === projectId &&+ props.taskId === taskId &&+ props.runId === runId+ let optimisticStarted = false+ let accepted = false+ const stream = runStreamLogic({ streamKey })+ disposables.add(+ () => () => {+ if (optimisticStarted && !accepted && stream.isMounted()) {+ stream.actions.rollbackOptimisticResume()+ }+ },+ 'optimistic-resume',+ { pauseOnPageHidden: false }+ )actions.claimApplyBackTargets(streamKey)try {// Same endpoint as the "Run again" button, but seeded with the user's message and chained@@ -1187,32 +1225,52 @@ export const runInteractionLogic = kea<runInteractionLogicType>([})actions.consumeWarm()+ actions.resetComposerForm()+ actions.startOptimisticResume(content)+ optimisticStarted = trueconst result = await submitWithWarmRunRetry(- (options) => tasksRunCreate(projectId, props.taskId, createRequest, options),+ (options) => tasksRunCreate(projectId, taskId, createRequest, options),disposables)- actions.resetComposerForm()- markPendingContextSent(pendingContext)- const latestRunId = result.latest_run?.id- if (latestRunId) {- actions.transferApplyBackTargets(streamKey, latestRunId)- claimedStreamKey = latestRunId- props.onRunStarted?.(latestRunId)- } else {- actions.releaseApplyBackTargets(streamKey)+ if (!isCurrent()) {+ return+ }+ const run = result.latest_run+ if (!run?.id) {+ throw new Error('The run response did not include a run')}+ accepted = true+ markPendingContextSent(pendingContext)+ props.flushDraft?.()+ const handoff = { run, streamKey, draft: values.composerForm.draft }+ actions.attachOptimisticResume(taskId, run)+ props.onRunStarted?.(run.id, handoff)} catch (error) {- if (disposables.isDisposed) {+ if (!isCurrent()) {return}- actions.releaseApplyBackTargets(claimedStreamKey)+ if (accepted) {+ throw error+ }+ if (optimisticStarted) {+ actions.rollbackOptimisticResume()+ }+ actions.releaseApplyBackTargets(streamKey)+ if (optimisticStarted) {+ props.flushDraft?.()+ actions.setComposerFormValues({+ draft: values.composerForm.draft ? `${content}\n\n${values.composerForm.draft}` : content,+ })+ optimisticStarted = false+ }lemonToast.error(error instanceof ApiError && error.code === 'warm_run_activation_unavailable'? "Couldn't start this run yet. Please try again.": 'Failed to start a new run. Please try again.')} finally {- if (!disposables.isDisposed) {+ disposables.dispose('optimistic-resume')+ if (isCurrent()) {actions.setStartingRun(false)}}diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex 47420611b237..0e493bcc920c 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -10,8 +10,10 @@ import { projectLogic } from 'scenes/projectLogic'import { initKeaTests } from '~/test/init'import { tasksRunsCommandCreate, tasksRunsStreamTokenRetrieve } from 'products/tasks/frontend/generated/api'+import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'import type { AttachedContextItem } from '../types/contextTypes'+import { TaskRunEnvironment, TaskRunStatus } from '../types/taskTypes'import type { PermissionRequestFrame, StoredLogEntry } from '../types/wireTypes'import { contextItemLine, wrapWithPosthogContext } from '../utils/posthogContextBlock'import { computeTurnTrailers } from '../utils/turnTrailers'@@ -498,6 +500,53 @@ describe('runStreamLogic', () => {})describe('assistant message buffering without messageId', () => {+ it('keeps blank assistant chunks hidden until visible text arrives', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(sessionUpdate({ sessionUpdate: 'agent_message_chunk' }))+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: ' \n' } })+ )+ }).toFinishAllListeners()++ expect(logic.values.threadItems).toEqual([])+ expect(logic.values.hasThreadItems).toBe(false)++ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'First answer' } })+ )+ }).toFinishAllListeners()++ expect(logic.values.threadItems).toEqual([+ expect.objectContaining({ type: 'assistant_message', text: ' \nFirst answer', complete: false }),+ ])+ expect(logic.values.hasThreadItems).toBe(true)+ })++ it.each(['live', 'replay'] as const)('hides blank finalized assistant messages during %s', async (source) => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(sessionUpdate({ sessionUpdate: 'agent_message' }), source)+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: ' \n\t' } }),+ source+ )+ }).toFinishAllListeners()++ expect(logic.values.threadItems).toEqual([])+ expect(logic.values.hasThreadItems).toBe(false)++ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'First answer' } }),+ source+ )+ }).toFinishAllListeners()++ expect(logic.values.threadItems).toEqual([+ expect.objectContaining({ type: 'assistant_message', text: 'First answer', complete: true }),+ ])+ })+it('keeps two consecutive turns without a messageId in separate thread items', async () => {const frames: StoredLogEntry[] = [sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'One' } }),@@ -1297,7 +1346,7 @@ describe('runStreamLogic', () => {)})- it('places replayed setup progress below the human turn it belongs to', async () => {+ it('renders replayed setup progress below the human turn', async () => {const frames: StoredLogEntry[] = [notification('_posthog/progress', {sessionId: 's',@@ -1719,6 +1768,18 @@ describe('runStreamLogic', () => {await expectLogic(logic).toFinishAllListeners()})+ it('clears the bootstrap spinner for a terminal run whose history renders no rows', async () => {+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'failed', state: {} } as any)+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])++ await expectLogic(logic, () => {+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()++ expect(logic.values.hasThreadItems).toBe(false)+ expect(logic.values.bootstrapLoading).toBe(false)+ })+it('stores bootstrap errors for inline task-run error UI', async () => {const error = mapHttpStatusToStreamError(404)@@ -1830,6 +1891,184 @@ describe('runStreamLogic', () => {})describe('streamPhase provisioning during open', () => {+ it.each(['completed', 'cancelled', 'failed'] as const)(+ 'keeps the thread optimistic when continuing a %s run',+ async (status) => {+ const nextRun: TaskRunDetailDTOApi = {+ id: 'run-2',+ task: 'task-1',+ stage: null,+ branch: null,+ status: TaskRunStatus.QUEUED,+ environment: TaskRunEnvironment.CLOUD,+ error_message: null,+ output: null,+ artifacts: [],+ state: { resume_from_run_id: 'run-1' },+ }+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', justCreatedRun: true })+ const originalStream = MockStream.latest()+ await originalStream.emitOpen()+ await originalStream.emitMessage(notification('_posthog/run_started', { runId: 'run-1' }), '100-0')+ await originalStream.emitMessage(notification('_posthog/user_message', { content: 'hello' }), '101-0')+ await originalStream.emitMessage(+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'Hi there' } }),+ '102-0'+ )+ if (status === 'completed') {+ await originalStream.emitMessage(notification('_posthog/turn_complete', {}), '103-0')+ }+ await originalStream.emitMessage({ type: 'task_run_state', status })+ const previousItems = logic.values.threadItems++ logic.actions.startOptimisticResume('continue')+ expect(logic.values.threadItems.slice(0, previousItems.length)).toEqual(previousItems)+ expect(logic.values.threadItems.at(-1)).toMatchObject({ type: 'human_message', text: 'continue' })+ expect(logic.values.streamPhase).toBe('provisioning')++ logic.actions.attachOptimisticResume('task-1', nextRun)+ const resumedStream = MockStream.latest()+ await resumedStream.emitOpen()+ expect(resumedStream.options.lastEventId).toBeUndefined()+ expect(resumedStream.options.startLatest).toBe(false)+ expect(logic.values.bootstrappedRunId).toBe('run-2')+ expect(logic.values.streamPhase).toBe('provisioning')+ expect(logic.values.threadItems.slice(0, previousItems.length)).toEqual(previousItems)++ await resumedStream.emitMessage(notification('_posthog/run_started', { runId: 'run-2' }))+ await resumedStream.emitMessage(notification('_posthog/user_message', { content: 'continue' }))+ expect(logic.values.streamPhase).toBe('thinking')+ expect(logic.values.threadItems.filter((item) => item.text === 'continue')).toHaveLength(1)+ await resumedStream.emitMessage(+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'Continuing now' } })+ )+ await resumedStream.emitMessage(notification('_posthog/turn_complete', {}))+ await resumedStream.emitMessage({ type: 'task_run_state', status: 'completed' })++ logic.actions.startOptimisticResume('continue')+ expect(logic.values.streamPhase).toBe('provisioning')+ logic.actions.attachOptimisticResume('task-1', {+ ...nextRun,+ id: 'run-3',+ state: { resume_from_run_id: 'run-2' },+ })+ await MockStream.latest().emitOpen()+ await MockStream.latest().emitMessage(notification('_posthog/user_message', { content: 'continue' }))+ expect(logic.values.threadItems.filter((item) => item.text === 'continue')).toHaveLength(2)+ }+ )++ it('rolls back only the pending message when a resume fails', () => {+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'hello' }), 'replay')+ logic.actions.markTurnComplete()+ logic.actions.handleTerminalStatus({ status: 'completed', replayedFromHistory: true })+ const previousItems = logic.values.threadItems+ logic.actions.startOptimisticResume('continue')+ logic.actions.ingestAcpFrame(+ notification('_posthog/console', { message: 'History finished loading', level: 'info' }),+ 'replay'+ )+ const entryCount = logic.values.log.entries.length+ logic.actions.rollbackOptimisticResume()++ expect(logic.values.log.entries).toHaveLength(entryCount - 1)+ expect(logic.values.threadItems.filter((item) => item.type === 'human_message')).toEqual(previousItems)+ expect(logic.values.streamPhase).toBe('idle')+ expect(logic.values.turnComplete).toBe(true)+ expect(logic.values.awaitingOptimisticAttach).toBe(false)+ })++ it.each([false, true])(+ 'reconciles incomplete history with a persisted successor message: %s',+ async (persisted) => {+ const run = {+ id: 'run-2',+ task: 'task-1',+ stage: null,+ branch: null,+ status: TaskRunStatus.QUEUED,+ environment: TaskRunEnvironment.CLOUD,+ error_message: null,+ output: null,+ artifacts: [],+ state: { resume_from_run_id: 'run-1' },+ runtime_adapter: null,+ model: null,+ reasoning_effort: null,+ log_url: null,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ completed_at: null,+ } satisfies TaskRunDetailDTOApi+ const history = [+ notification('_posthog/run_started', { runId: 'run-1' }),+ notification('_posthog/user_message', { content: 'continue' }),+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'Earlier answer' } }),+ ...(persisted+ ? [+ notification('_posthog/run_started', { runId: 'run-2' }),+ notification('_posthog/user_message', { content: 'continue' }),+ ]+ : []),+ ]+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue(run)+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(history)+ logic.actions.handleTerminalStatus({ status: 'completed', replayedFromHistory: true })+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ logic.actions.startOptimisticResume('continue')+ await expectLogic(logic, () =>+ logic.actions.attachOptimisticResume('task-1', run)+ ).toFinishAllListeners()++ expect(logic.values.threadItems.filter((item) => item.text === 'continue')).toHaveLength(2)+ expect(logic.values.threadItems.some((item) => item.text === 'Earlier answer')).toBe(true)+ expect(logic.values.streamPhase).toBe(persisted ? 'thinking' : 'provisioning')+ // The reconciliation must not wipe the successor's seeded status — a null one hides the+ // composer, and a live run publishes no further state frame until it terminates.+ expect(logic.values.currentRunStatus).toBe('queued')+ expect(logic.values.turnComplete).toBe(false)+ expect(MockStream.latest().options.startLatest).toBe(true)+ await MockStream.latest().emitOpen()+ await MockStream.latest().emitMessage(notification('_posthog/user_message', { content: 'continue' }))+ expect(logic.values.threadItems.filter((item) => item.text === 'continue')).toHaveLength(2)+ }+ )++ it('stops provisioning when the incomplete-history successor is already terminal', async () => {+ const run = {+ id: 'run-2',+ task: 'task-1',+ stage: null,+ branch: null,+ status: TaskRunStatus.FAILED,+ environment: TaskRunEnvironment.CLOUD,+ error_message: 'Failed to start task workflow',+ output: null,+ artifacts: [],+ state: { resume_from_run_id: 'run-1' },+ runtime_adapter: null,+ model: null,+ reasoning_effort: null,+ log_url: null,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ completed_at: '2026-01-01T00:00:01Z',+ } satisfies TaskRunDetailDTOApi+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue(run)+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([+ notification('_posthog/run_started', { runId: 'run-1' }),+ notification('_posthog/user_message', { content: 'continue' }),+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'Earlier answer' } }),+ ])+ logic.actions.handleTerminalStatus({ status: 'completed', replayedFromHistory: true })+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ logic.actions.startOptimisticResume('continue')+ await expectLogic(logic, () => logic.actions.attachOptimisticResume('task-1', run)).toFinishAllListeners()++ expect(logic.values.runOpening).toEqual(false)+ expect(logic.values.streamPhase).toEqual('idle')+ })+it('is provisioning while the open POST is in flight, before any SSE state exists', () => {expect(logic.values.streamPhase).toEqual('idle')@@ -2471,13 +2710,13 @@ describe('runStreamLogic', () => {logic.actions.ingestAcpFrame(notification('_posthog/progress', {sessionId: 's',- step: 'clone',+ step: 'wizard',status: 'in_progress',- label: 'Cloning repository',+ label: 'Running PostHog setup wizard',group: 'setup:run-1',}))- }).toMatchValues({ currentProgress: 'Cloning repository' })+ }).toMatchValues({ currentProgress: 'Running PostHog setup wizard' })expect(logic.values.threadItems).toEqual([{@@ -2486,16 +2725,16 @@ describe('runStreamLogic', () => {progressGroup: 'setup:run-1',progressSteps: [{- key: 'clone',+ key: 'wizard',status: 'in_progress',- label: 'Cloning repository',+ label: 'Running PostHog setup wizard',},],},])})- it('coalesces setup progress by group and updates repeated steps in place', async () => {+ it('coalesces setup progress into one visible activity', async () => {await expectLogic(logic, () => {logic.actions.ingestAcpFrame(notification('_posthog/progress', {@@ -2545,6 +2784,32 @@ describe('runStreamLogic', () => {],},])++ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', {+ step: 'clone',+ status: 'failed',+ label: 'Repository clone failed',+ group: 'setup:run-1',+ })+ )+ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', {+ step: 'preview',+ status: 'in_progress',+ label: 'Starting preview',+ group: 'setup:run-1',+ })+ )+ expect(logic.values.threadItems).toEqual([+ expect.objectContaining({+ progressSteps: [+ { key: 'sandbox', status: 'completed', label: 'Set up sandbox' },+ { key: 'clone', status: 'failed', label: 'Repository clone failed' },+ { key: 'preview', status: 'in_progress', label: 'Starting preview' },+ ],+ }),+ ])})it('clears currentProgress when a step finishes so the milestone label never sticks as live status', async () => {diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex 5f19d025d4c7..00be626343c0 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -23,7 +23,10 @@ import { projectLogic } from 'scenes/projectLogic'import { userLogic } from 'scenes/userLogic'import { tasksRunsCommandCreate, tasksRunsStreamTokenRetrieve } from 'products/tasks/frontend/generated/api'-import type { TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'+import type {+ TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi,+ TaskRunDetailDTOApi,+} from 'products/tasks/frontend/generated/api.schemas'import type { FeatureFlagsSet } from '../../../../frontend/src/lib/logic/featureFlagLogic'import type { UserType } from '../../../../frontend/src/types'@@ -796,6 +799,13 @@ export interface RunLog {toolUpdateIndex: Record<string, number>}+interface OptimisticResume {+ entries: StoredEntry[]+ message: string+ historyComplete: boolean+ turnComplete: boolean+}+export function emptyRunLog(): RunLog {return { entries: [], toolUpdateIndex: {} }}@@ -1432,13 +1442,15 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:}/**- * Whether a folded item renders any content. Empty priming thoughts and step-less progress rows fold- * into the thread but render nothing; drop them here so a virtualized consumer never reserves an empty,- * gap-padded row. Tool items are always paired with an invocation (see `upsertInvocationItem`), and- * `debug` rows are gated separately by `showDebugLogs`, so neither needs a content check here.+ * Empty assistant messages, priming thoughts, and step-less progress rows stay in the log for folding.+ * Hide them from the rendered thread so message wrappers and virtualized consumers cannot reserve+ * empty bubbles or gap-padded rows. Tool items are always paired with an invocation (see+ * `upsertInvocationItem`), and `debug` rows are gated separately by `showDebugLogs`, so neither needs+ * a content check here.*/function rendersThreadItemContent(item: ThreadItem): boolean {switch (item.type) {+ case 'assistant_message':case 'assistant_thought':return !!item.text?.trim()case 'progress':@@ -1471,6 +1483,7 @@ export interface runStreamLogicValues {currentStage: string | nullfoldedThread: FoldedThreadhasGitArtifacts: boolean+ hasThreadItems: booleanisBootstrapResumeRun: booleanisThinking: booleanlatestTurnTraceId: string | null@@ -1518,6 +1531,16 @@ export interface runStreamLogicActions {appendEntries: (entries: StoredEntry[]) => {entries: StoredEntry[]}+ appendResumeBoundary: () => {+ value: true+ }+ attachOptimisticResume: (+ taskId: string,+ run: TaskRunDetailDTOApi+ ) => {+ run: TaskRunDetailDTOApi+ taskId: string+ }autoApprovePermissionRequest: (record: PermissionRequestRecord,optionId: string@@ -1531,8 +1554,15 @@ export interface runStreamLogicActions {bootstrapReplayComplete: () => {value: true}- bootstrapRun: (payload: { justCreatedRun?: boolean; runId: string; taskId: string; traceId?: string }) => {+ bootstrapRun: (payload: {+ justCreatedRun?: boolean+ retainedMessage?: string+ runId: string+ taskId: string+ traceId?: string+ }) => {justCreatedRun?: boolean | undefined+ retainedMessage?: string | undefinedrunId: stringtaskId: stringtraceId?: string | undefined@@ -1624,6 +1654,9 @@ export interface runStreamLogicActions {permissionRunChanged: () => {value: true}+ prepareResumeRun: () => {+ value: true+ }pushConversationCleared: () => {value: true}@@ -1637,6 +1670,9 @@ export interface runStreamLogicActions {pushHumanMessage: (content: string) => {content: string}+ replaceLog: (log: RunLog) => {+ log: RunLog+ }reset: () => {value: true}@@ -1651,6 +1687,9 @@ export interface runStreamLogicActions {optionId: stringrequestId: string}+ rollbackOptimisticResume: () => {+ value: true+ }routePermissionRequest: (record: PermissionRequestRecord,replayedFromHistory?: boolean@@ -1691,6 +1730,9 @@ export interface runStreamLogicActions {sseReconnecting: (attempt: number) => {attempt: number}+ startOptimisticResume: (message: string) => {+ message: string+ }startOptimisticRun: (message?: string) => {message: string | undefined}@@ -1710,6 +1752,7 @@ export interface runStreamLogicMeta {foldedThread: (log: RunLog, isBootstrapResumeRun: boolean) => FoldedThreadlatestTurnTraceId: (threadItems: ThreadItem[]) => string | nullthreadItems: (foldedThread: FoldedThread, showDebugLogs: boolean) => ThreadItem[]+ hasThreadItems: (threadItems: ThreadItem[]) => booleantoolInvocations: (foldedThread: FoldedThread) => Map<string, ToolInvocation>isThinking: (runStarted: boolean,@@ -1803,10 +1846,19 @@ export const runStreamLogic = kea<runStreamLogicType>([* (`dedupeBufferedAgainstHistory`) so the seam neither duplicates nor gaps. `justCreatedRun`* skips the `logs/` round-trip (fresh-run fast path — nothing historical to assemble).*/- bootstrapRun: (payload: { taskId: string; runId: string; justCreatedRun?: boolean; traceId?: string }) =>- payload,+ bootstrapRun: (payload: {+ taskId: string+ runId: string+ justCreatedRun?: boolean+ traceId?: string+ retainedMessage?: string+ }) => payload,openSseForRun: (payload: { taskId: string; runId: string; startLatest?: boolean; traceId?: string }) => payload,- /** Internal: the read-only replay snapshot finished loading — clears the bootstrap spinner. */+ /**+ * Internal: a replay snapshot finished loading and no stream will follow — clears the bootstrap+ * spinner. Covers the read-only viewer and a live instance that bootstrapped an already-terminal+ * run, which never opens SSE and so never gets `sseOpened` to clear the spinner for it.+ */bootstrapReplayComplete: true,/** Internal: the live run history snapshot finished loading or was intentionally skipped. */bootstrapLogReady: true,@@ -1839,6 +1891,7 @@ export const runStreamLogic = kea<runStreamLogicType>([ingestAcpFrame: (entry: StoredLogEntry, source: FrameSource = 'live') => ({ entry, source }),/** Append frames to the ordered log (the single source of truth). */appendEntries: (entries: StoredEntry[]) => ({ entries }),+ replaceLog: (log: RunLog) => ({ log }),/** Records whether the bootstrapped run is a resume run, so the projection can drop its synthetic resume prompt. */markBootstrapResumeRun: (value: boolean) => ({ value }),/**@@ -1935,6 +1988,11 @@ export const runStreamLogic = kea<runStreamLogicType>([* `pushHumanMessage`.*/startOptimisticRun: (message?: string) => ({ message }),+ startOptimisticResume: (message: string) => ({ message }),+ appendResumeBoundary: true,+ rollbackOptimisticResume: true,+ attachOptimisticResume: (taskId: string, run: TaskRunDetailDTOApi) => ({ taskId, run }),+ prepareResumeRun: true,/** Injects a client-side error (terminal failure / stream disconnect) into the log as a `client`-sourced entry. */pushErrorItem: (errorMessage: string, variant: 'error' | 'crash' = 'error') => ({ errorMessage, variant }),/** Echoes a `/clear` boundary the backend just recorded against a finished run, which has no stream to send it back. */@@ -1955,10 +2013,11 @@ export const runStreamLogic = kea<runStreamLogicType>([false,{setRunOpening: (_, { opening }) => opening,+ rollbackOptimisticResume: () => false,openSseForRun: () => false,sseOpened: () => false,handleStreamError: () => false,- handleTerminalStatus: () => false,+ handleTerminalStatus: (state, { replayedFromHistory }) => (replayedFromHistory ? state : false),pushErrorItem: () => false,reset: () => false,},@@ -2005,6 +2064,10 @@ export const runStreamLogic = kea<runStreamLogicType>([// flickering back to queued; only a fresh open (no/terminal status) resets.openSseForRun: (state) => (state && !isTerminalRunStatus(state) ? state : 'queued'),handleTerminalStatus: (_, { status }) => status,+ // The boundary drops the status of the run being left behind, which is always a terminal+ // one. The successor's own seed can already be here — `openSseForRun` runs before the+ // history this reconciles — and wiping it hides the composer for the rest of the run.+ prepareResumeRun: (state) => (state && !isTerminalRunStatus(state) ? state : null),reset: () => null,},],@@ -2031,6 +2094,7 @@ export const runStreamLogic = kea<runStreamLogicType>([emptyRunLog(),{appendEntries: (state, { entries }) => appendToRunLog(state, entries),+ replaceLog: (_, { log }) => log,reset: () => emptyRunLog(),},],@@ -2074,6 +2138,8 @@ export const runStreamLogic = kea<runStreamLogicType>([false,{startOptimisticRun: () => true,+ startOptimisticResume: () => true,+ rollbackOptimisticResume: () => false,bootstrapRun: () => false,reset: () => false,},@@ -2177,6 +2243,7 @@ export const runStreamLogic = kea<runStreamLogicType>([null as string | null,{setCurrentMode: (_, { mode }) => mode,+ prepareResumeRun: () => null,reset: () => null,},],@@ -2185,6 +2252,7 @@ export const runStreamLogic = kea<runStreamLogicType>([{setCurrentProgress: (_, { progress }) => progress,markTurnComplete: () => null,+ prepareResumeRun: () => null,reset: () => null,},],@@ -2195,6 +2263,7 @@ export const runStreamLogic = kea<runStreamLogicType>([null as string | null,{setCurrentStage: (_, { stage }) => stage,+ prepareResumeRun: () => null,reset: () => null,},],@@ -2202,6 +2271,7 @@ export const runStreamLogic = kea<runStreamLogicType>([false,{markRunStarted: () => true,+ prepareResumeRun: () => false,reset: () => false,},],@@ -2228,6 +2298,7 @@ export const runStreamLogic = kea<runStreamLogicType>([markRunStarted: () => false,pushHumanMessage: () => false,markTurnStarted: () => false,+ prepareResumeRun: () => false,reset: () => false,},],@@ -2256,6 +2327,7 @@ export const runStreamLogic = kea<runStreamLogicType>([null as SdkSession | null,{setSdkSession: (_, { session }) => session,+ prepareResumeRun: () => null,reset: () => null,},],@@ -2296,6 +2368,7 @@ export const runStreamLogic = kea<runStreamLogicType>([(item: ThreadItem) => (item.type !== 'debug' || showDebugLogs) && rendersThreadItemContent(item)),],+ hasThreadItems: [(s) => [s.threadItems], (threadItems: ThreadItem[]): boolean => threadItems.length > 0],toolInvocations: [(s) => [s.foldedThread],(foldedThread: FoldedThread): Map<string, ToolInvocation> => foldedThread.toolInvocations,@@ -2335,9 +2408,8 @@ export const runStreamLogic = kea<runStreamLogicType>([* Stream lifecycle phase gating the bottom-of-thread thinking indicator. `provisioning` = the* 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.+ * `ThreadView` uses setup progress as the startup indicator, with a fixed fallback before steps arrive.+ * The playful gerund loader waits for `run_started` to flip the phase to `thinking`.* `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.@@ -2356,6 +2428,9 @@ export const runStreamLogic = kea<runStreamLogicType>([if (replayOnly) {return 'idle'}+ if (runOpening && isTerminalRunStatus(currentRunStatus)) {+ return 'provisioning'+ }const connecting = sseStatus === 'connecting' || sseStatus === 'open' || sseStatus === 'reconnecting'// `runOpening` covers the conversations/open POST window, before any SSE state exists.if ((connecting || runOpening) && !runStarted && !isTerminalRunStatus(currentRunStatus)) {@@ -2469,7 +2544,7 @@ export const runStreamLogic = kea<runStreamLogicType>([],}),listeners(({ values, actions, cache, props }) => ({- bootstrapRun: async ({ taskId, runId, justCreatedRun }, breakpoint) => {+ bootstrapRun: async ({ taskId, runId, justCreatedRun, retainedMessage }, breakpoint) => {if (cache.activeRun && (cache.activeRun.runId !== runId || cache.activeRun.taskId !== taskId)) {actions.cancelPermissionDelivery()actions.permissionRunChanged()@@ -2588,13 +2663,52 @@ export const runStreamLogic = kea<runStreamLogicType>([// The full resume-chain S3 snapshot — replayed as `replay`, so the projection renders// persisted human turns and side-effect telemetry stays suppressed for history.const history = normalizeHistory(entries, runId, isResumeRun(run))- history.forEach((entry) => actions.ingestAcpFrame(entry, 'replay'))+ if (retainedMessage) {+ // Replace the partial snapshot synchronously; ancestor lifecycle frames must not make+ // a successor that is still provisioning appear started or finished.+ actions.replaceLog(emptyRunLog())+ let reachedSuccessor = false+ history.forEach((entry) => {+ if (!reachedSuccessor && entry.source_run_id === runId) {+ actions.appendResumeBoundary()+ actions.prepareResumeRun()+ actions.permissionRunChanged()+ reachedSuccessor = true+ }+ actions.ingestAcpFrame(entry, 'replay')+ })+ if (!reachedSuccessor) {+ actions.appendResumeBoundary()+ actions.prepareResumeRun()+ actions.permissionRunChanged()+ }+ const successorItems = foldLogToThread(+ history+ .filter((entry) => entry.source_run_id === runId)+ .map((entry) => ({ entry, source: 'replay' })),+ { isResumeRun: true }+ ).threadItems+ if (!successorItems.some((item) => item.type === 'human_message' && item.text === retainedMessage)) {+ actions.pushHumanMessage(retainedMessage)+ }+ } else {+ history.forEach((entry) => actions.ingestAcpFrame(entry, 'replay'))+ }if (terminal) {+ if (retainedMessage) {+ // This bootstrap is the resume attach itself, and a terminal run opens no stream, so+ // the provisioning window is over. A replayed terminal status alone must not clear the+ // flag — an ancestor's bootstrap can resolve terminal while the successor still opens.+ actions.setRunOpening(false)+ }// Read-only history — surface the terminal status, do not open SSE. Flag the replay// so the listener records the status without re-emitting termination telemetry.actions.handleTerminalStatus({ status: run.status as RunStatus, replayedFromHistory: true })- actions.bootstrapLogReady()+ // `bootstrapReplayComplete`, not `bootstrapLogReady`: with no SSE to open, `sseOpened`+ // never clears the bootstrap spinner, so a terminal run whose history folds to no+ // renderable rows would sit on the skeleton for the instance's lifetime.+ actions.bootstrapReplayComplete()return}@@ -3250,6 +3364,7 @@ export const runStreamLogic = kea<runStreamLogicType>([},reset: () => {actions.cancelPermissionDelivery()+ cache.optimisticResume = undefined// `log` clears via its own reducer on `reset`, so the projection empties with it. The// per-frame invocation tracker mirrors the log, so it must clear alongside it.cache.trackedToolInvocations = undefined@@ -3275,6 +3390,67 @@ export const runStreamLogic = kea<runStreamLogicType>([actions.pushHumanMessage(message)}},+ appendResumeBoundary: () => {+ // A killed run can end without a turn_complete frame. Close that turn before inserting+ // the successor's message, or the projection moves it ahead of the previous answer.+ if (!values.turnComplete && values.log.entries.length > 0) {+ actions.appendEntries([+ {+ entry: { type: 'notification', notification: { method: '_posthog/turn_complete', params: {} } },+ source: 'client',+ },+ ])+ }+ },+ startOptimisticResume: ({ message }) => {+ const historyComplete = !values.logBootstrapLoading && !values.bootstrapError+ const turnComplete = values.turnComplete+ const previousEntryCount = values.log.entries.length+ actions.appendResumeBoundary()+ actions.setRunOpening(true)+ actions.pushHumanMessage(message)+ cache.optimisticResume = {+ entries: values.log.entries.slice(previousEntryCount),+ message,+ historyComplete,+ turnComplete,+ } satisfies OptimisticResume+ },+ rollbackOptimisticResume: () => {+ const resume = cache.optimisticResume as OptimisticResume | undefined+ if (!resume) {+ return+ }+ cache.optimisticResume = undefined+ actions.replaceLog(+ appendToRunLog(+ emptyRunLog(),+ values.log.entries.filter((entry) => !resume.entries.includes(entry))+ )+ )+ if (resume.turnComplete) {+ actions.markTurnComplete()+ }+ },+ attachOptimisticResume: ({ taskId, run }) => {+ const resume = cache.optimisticResume as OptimisticResume | undefined+ if (!resume) {+ return+ }+ cache.optimisticResume = undefined+ actions.closeSse()+ actions.prepareResumeRun()+ actions.permissionRunChanged()+ cache.trackedToolInvocations = undefined+ actions.markBootstrapResumeRun(true)+ actions.mergeRunArtifacts(extractRunArtifacts(run))+ actions.bootstrapRun({+ taskId,+ runId: run.id,+ justCreatedRun: resume.historyComplete,+ ...(!resume.historyComplete ? { retainedMessage: resume.message } : {}),+ })+ },pushHumanMessage: ({ content }) => {// The echo is always a live turn (replayed human turns render straight from the log), so// stamp the turn start for per-turn duration metrics and append it as a `client`-sourceddiff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsxindex a14920744a50..5a6f55dcb884 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx@@ -7,7 +7,6 @@ import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'import { RunEscapeBoundary } from '../../../components/RunEscapeBoundary'import { runCancellationLogic } from '../../../logics/runCancellationLogic'-import { TaskHeaderActionsSkeleton } from './taskDetailSkeletons'import { TaskRunSceneShell } from './TaskRunSceneShell'export interface TaskCreateThreadProps {@@ -19,8 +18,8 @@ export interface TaskCreateThreadProps {/*** The optimistic create thread shown the instant the user hits send, before the task/run exist. It renders the- * same scene shell as the detail page — in its all-loading state, since the task/title/run don't exist yet, so- * the header shows skeletons — wrapped around the pending `RunSurface` (no `runId`): `taskTrackerSceneLogic` has+ * same scene shell as the detail page, with metadata omitted until the task/run exist,+ * wrapped around the pending `RunSurface` (no `runId`): `taskTrackerSceneLogic` has* already seeded the bound `runStreamLogic` (keyed by `streamKey`) with the typed message + provisioning* indicator via `startOptimisticRun`, so this just renders that thread. Rendering the identical shell here is* what makes the `/tasks/new → /tasks/:id` handoff seamless — once the run is created the scene navigates to the@@ -33,8 +32,6 @@ export function TaskCreateThread({ streamKey, isMobile }: TaskCreateThreadProps)<TaskRunSceneShelltask={null}selectedRun={null}- isHeaderLoading- titleActions={<TaskHeaderActionsSkeleton />}sceneMenuBarEnabled={false}onArchive={() => {}}taskError={null}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsxindex 6a0447e22118..f2cb1197e1fd 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx@@ -23,12 +23,13 @@ export interface TaskDetailPageProps {export function TaskDetailPage({ taskId, isMobile }: TaskDetailPageProps): JSX.Element {const sceneLogic = taskDetailSceneLogic({ taskId })- const { task, taskNotFound, taskError, runs, selectedRun, isTaskPending, isHeaderLoading, runTaskInFlight } =+ const { task, taskNotFound, taskError, latestRun, selectedRun, isTaskPending, isHeaderLoading, runTaskInFlight } =useValues(sceneLogic)const { runTask, deleteTask, loadTask } = useActions(sceneLogic)const { featureFlags } = useValues(featureFlagLogic)const { activeCreation, hasDesktopAccess } = useValues(taskTrackerSceneLogic)const sceneMenuBarEnabled = !!featureFlags[FEATURE_FLAGS.SCENE_MENU_BAR]+ const isActiveCreation = activeCreation?.taskId === taskIdif (taskNotFound && !task) {return <NotFound object="task" />@@ -38,15 +39,16 @@ export function TaskDetailPage({ taskId, isMobile }: TaskDetailPageProps): JSX.Ereturn <NotFound object="task" />}- const latestRun = runs.length > 0 ? runs[0] : nullconst isLatestRunInProgress = latestRun?.status === 'in_progress' || latestRun?.status === 'queued'const isLatestRunCompleted = latestRun?.status === 'completed'- const runButtonText = runs.length === 0 ? 'Run task' : 'Retry task'+ const runButtonText = latestRun ? 'Retry task' : 'Run task'const prUrl = selectedRun?.output?.pr_url as string | undefinedconst titleActions =isHeaderLoading || !task ? (- <TaskHeaderActionsSkeleton />+ isActiveCreation ? undefined : (+ <TaskHeaderActionsSkeleton />+ )) : (<div className="flex items-center gap-2">{hasDesktopAccess && (@@ -89,7 +91,6 @@ export function TaskDetailPage({ taskId, isMobile }: TaskDetailPageProps): JSX.E// When this task was just created optimistically, the seeded run stream lives under the creation's client// `streamKey`. Hand it to the run log so it adopts that instance (and renders the thread immediately)// instead of cold-bootstrapping a fresh, skeleton-flashing one.- const isActiveCreation = activeCreation?.taskId === taskIdconst optimisticStreamKey = isActiveCreation ? activeCreation?.streamKey : undefinedconst optimisticRunId = isActiveCreation ? activeCreation?.runId : undefined@@ -97,7 +98,7 @@ export function TaskDetailPage({ taskId, isMobile }: TaskDetailPageProps): JSX.E<TaskRunSceneShelltask={task}selectedRun={selectedRun}- isHeaderLoading={isHeaderLoading}+ isHeaderLoading={isHeaderLoading && !isActiveCreation}titleActions={titleActions}sceneMenuBarEnabled={sceneMenuBarEnabled}onArchive={deleteTask}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsxindex ea70f6239e47..d620ea49f92d 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx@@ -1,6 +1,6 @@import { BindLogic, useActions, useValues } from 'kea'import { router } from 'kea-router'-import { type RefObject, useEffect, useRef } from 'react'+import { type MutableRefObject, type RefObject, useEffect, useRef } from 'react'import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'import { urls } from 'scenes/urls'@@ -24,6 +24,7 @@ import { useDebouncedDraft } from '../../../components/composer/useDebouncedDrafimport { RunEscapeBoundary, type RunEscapeBoundaryProps } from '../../../components/RunEscapeBoundary'import { useForegroundStream } from '../../../hooks/useForegroundStream'import { runCancellationLogic } from '../../../logics/runCancellationLogic'+import type { RunContinuationHandoff } from '../../../logics/runInteractionLogic'import { taskDetailSceneLogic } from '../taskDetailSceneLogic'export interface TaskRunChatProps {@@ -36,7 +37,7 @@ export interface TaskRunChatProps {*/streamKey?: string/** Called after a fresh run starts, in addition to the `taskDetailSceneLogic` re-pointing below. */- onRunStarted?: (runId: string) => void+ onRunStarted?: (runId: string, handoff?: RunContinuationHandoff) => voidescapeScope?: RunEscapeBoundaryProps['scope']initialDraft?: stringonDraftAdopted?: () => void@@ -61,28 +62,44 @@ export function TaskRunChat({onDraftAdopted,autoFocus,}: TaskRunChatProps): JSX.Element {- const { setSelectedRunId, loadTaskRuns } = useActions(taskDetailSceneLogic({ taskId }))+ const { setSelectedRunId, loadTaskRuns, continueWithRun } = useActions(taskDetailSceneLogic({ taskId }))const { selectedRun, task } = useValues(taskDetailSceneLogic({ taskId }))const { user } = useValues(userLogic)+ const flushDraftRef = useRef<() => void>(() => {})// Staff can view tasks they don't own (support/debugging); those are read-only — hide the composer so// they can't try to drive a run they can't control (the backend rejects the write anyway).const readOnly = !!user?.is_staff && !!task?.created_by && task.created_by.id !== user.id+ // The scene logic is keyed by task, so `selectedRun` can name a different run than this surface renders+ // — the side panel opens `task.latest_run` while the page follows a `?runId=` link or a newer run. Read+ // the run's setup only when the two agree; a mismatch would launch the successor on another run's config.+ const runConfig = selectedRun?.id === runId ? selectedRun : undefinedconst logicProps: RunInteractionLogicProps = {taskId,runId,streamKey,initialDraft,onDraftAdopted,- currentModel: selectedRun?.state?.model,- currentEffort: selectedRun?.state?.reasoning_effort,- currentMode: selectedRun?.state?.initial_permission_mode,- currentRuntimeAdapter: selectedRun?.runtime_adapter,- onRunStarted: (newRunId) => {- setSelectedRunId(newRunId, taskId)- loadTaskRuns()+ flushDraft: () => flushDraftRef.current(),+ currentModel:+ runConfig?.model ?? (typeof runConfig?.state?.model === 'string' ? runConfig.state.model : undefined),+ currentEffort:+ runConfig?.reasoning_effort ??+ (typeof runConfig?.state?.reasoning_effort === 'string' ? runConfig.state.reasoning_effort : undefined),+ currentMode:+ typeof runConfig?.state?.initial_permission_mode === 'string'+ ? runConfig.state.initial_permission_mode+ : undefined,+ currentRuntimeAdapter: runConfig?.runtime_adapter,+ onRunStarted: (newRunId, handoff) => {+ if (handoff) {+ continueWithRun(handoff)+ } else {+ setSelectedRunId(newRunId, taskId)+ loadTaskRuns()+ }// The embedded panel renders from its own creation state, so it must be re-pointed// when a fresh run starts.- onRunStarted?.(newRunId)+ onRunStarted?.(newRunId, handoff)},}@@ -93,6 +110,7 @@ export function TaskRunChat({readOnly={readOnly}escapeScope={escapeScope}autoFocus={autoFocus}+ flushDraftRef={flushDraftRef}/></BindLogic>)@@ -103,11 +121,13 @@ function TaskRunChatContent({readOnly,escapeScope,autoFocus,+ flushDraftRef,}: {logicProps: RunInteractionLogicPropsreadOnly: booleanescapeScope: RunEscapeBoundaryProps['scope']autoFocus?: boolean+ flushDraftRef: MutableRefObject<() => void>}): JSX.Element {const textAreaRef = useRef<HTMLTextAreaElement>(null)const { handleEscape } = useActions(runInteractionLogic(logicProps))@@ -144,7 +164,12 @@ function TaskRunChatContent({<RunSurface.Composer isStopping={!!cancellationState}>{/* The composer owns the per-keystroke draft in an isolated child so typing never re-rendersthe thread/virtualizer rendered as its sibling above — that cascade is what made the input lag. */}- <LiveComposer logicProps={logicProps} textAreaRef={textAreaRef} autoFocus={autoFocus} />+ <LiveComposer+ logicProps={logicProps}+ textAreaRef={textAreaRef}+ autoFocus={autoFocus}+ flushDraftRef={flushDraftRef}+ /></RunSurface.Composer>)}</RunEscapeBoundary>@@ -156,10 +181,12 @@ function LiveComposer({logicProps,textAreaRef,autoFocus,+ flushDraftRef,}: {logicProps: RunInteractionLogicPropstextAreaRef: RefObject<HTMLTextAreaElement>autoFocus?: boolean+ flushDraftRef: MutableRefObject<() => void>}): JSX.Element {const {composerForm,@@ -193,6 +220,9 @@ function LiveComposer({} = useActions(runInteractionLogic(logicProps))const draft = useDebouncedDraft(composerForm.draft, (value) => setComposerFormValues({ draft: value }))+ useEffect(() => {+ flushDraftRef.current = draft.flush+ }, [flushDraftRef, draft.flush])return (<>@@ -204,7 +234,12 @@ function LiveComposer({textAreaRef={textAreaRef}value={draft.value}onChange={draft.onChange}- onSubmit={() => draft.submit(submitComposerForm)}+ onSubmit={() =>+ draft.submit(() => {+ submitComposerForm()+ return runInteractionLogic(logicProps).values.composerForm.draft+ })+ }loading={isSubmitting}stopLoading={!!cancellationState}isTurnActive={isBusy}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsxindex 29002d031304..e7b353b2d535 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsx@@ -26,9 +26,31 @@ export function TaskRunLog({optimisticRunId?: string}): JSX.Element | null {const logic = taskDetailSceneLogic({ taskId })- const { runs, selectedRun, selectedRunId, runsError, selectedRunError, selectedRunNotFound, isRunPending } =- useValues(logic)- const { loadTaskRuns, loadSelectedTaskRun } = useActions(logic)+ const {+ runs,+ selectedRun,+ selectedRunId,+ runsError,+ selectedRunError,+ selectedRunNotFound,+ isRunPending,+ runContinuation,+ } = useValues(logic)+ const { loadTaskRuns, loadSelectedTaskRun, clearContinuationDraft } = useActions(logic)++ if (runContinuation && selectedRunId === runContinuation.run.id) {+ return (+ <div className="flex-1 min-h-0">+ <TaskRunChat+ taskId={taskId}+ runId={runContinuation.run.id}+ streamKey={runContinuation.streamKey}+ initialDraft={runContinuation.draft}+ onDraftAdopted={() => clearContinuationDraft(runContinuation.run.id)}+ />+ </div>+ )+ }// Optimistic-create handoff: render the run immediately on the seeded stream, bypassing the runs-list// load (no skeleton re-flash). `selectedRunId ?? optimisticRunId` tracks the live id — the created rundiff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsxindex 75abb2c3d426..55e1f1a3b581 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunMetadata.tsx@@ -4,22 +4,25 @@ import { TZLabel } from 'lib/components/TZLabel'import { dayjs } from 'lib/dayjs'import { humanFriendlyDuration } from 'lib/utils/durations'+import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'+import { modelCatalogueLogic } from '../../../logics/modelCatalogueLogic'-import { TaskRun } from '../../../types/taskTypes'import { getEffortLabel, getModelLabel } from '../../../utils/composerModels'/** Created / completed / duration / model row shown above the run log for the selected run. */-export function TaskRunMetadata({ selectedRun }: { selectedRun: TaskRun }): JSX.Element {+export function TaskRunMetadata({ selectedRun }: { selectedRun: TaskRunDetailDTOApi }): JSX.Element {const { catalogue } = useValues(modelCatalogueLogic)return (<div className="items-center gap-4 text-xs text-muted hidden lg:flex">- <dl className="inline-flex gap-1 items-center">- <dt className="m-0">Created:</dt>- <dd className="m-0 inline-flex items-center">- <TZLabel time={selectedRun.created_at} showSeconds />- </dd>- </dl>+ {selectedRun.created_at && (+ <dl className="inline-flex gap-1 items-center">+ <dt className="m-0">Created:</dt>+ <dd className="m-0 inline-flex items-center">+ <TZLabel time={selectedRun.created_at} showSeconds />+ </dd>+ </dl>+ )}{selectedRun.completed_at && (<dl className="inline-flex gap-1 items-center"><dt className="m-0">Completed:</dt>@@ -28,7 +31,7 @@ export function TaskRunMetadata({ selectedRun }: { selectedRun: TaskRun }): JSX.</dd></dl>)}- {selectedRun.completed_at && (+ {selectedRun.completed_at && selectedRun.created_at && (<dl className="inline-flex gap-1 items-center"><dt className="m-0">Duration:</dt><dd className="m-0 inline-flex items-center">diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsxindex f1ad0090737f..9622dbb2ff91 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx@@ -23,7 +23,9 @@ import {ScenePanelInfoSection,} from '~/layout/scenes/SceneLayout'-import { Task, TaskRun } from '../../../types/taskTypes'+import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'++import type { Task } from '../../../types/taskTypes'import { TaskDebugLogsMenu } from './TaskDebugLogsMenu'import { TaskDebugLogsPanelToggle } from './TaskDebugLogsPanelToggle'import { TaskPanelSkeleton, TaskRunMetadataSkeleton } from './taskDetailSkeletons'@@ -34,11 +36,11 @@ export interface TaskRunSceneShellProps {/** The loaded task, or `null` while loading (or during an optimistic create, before it exists). */task: Task | null/** The run whose metadata heads the thread, or `null` while loading. */- selectedRun: TaskRun | null+ selectedRun: TaskRunDetailDTOApi | null/** Drives the title/panel/metadata skeletons — the single unified loading affordance for the header. */- isHeaderLoading: boolean+ isHeaderLoading?: boolean/** Title-bar action buttons (or their skeleton). Supplied by the caller so the shell stays presentational. */- titleActions: JSX.Element+ titleActions?: JSX.ElementsceneMenuBarEnabled: booleanonArchive: () => voidtaskError: string | null@@ -52,13 +54,12 @@ export interface TaskRunSceneShellProps {/*** The task-run scene chrome — scene panel, title header, run metadata, divider — around a run-log slot.* Purely presentational: both the detail page (wired from `taskDetailSceneLogic`) and the optimistic- * create thread (wired all-loading) render it, so the `/tasks/new → /tasks/:id` handoff shows byte-identical- * shell while only the continuous thread underneath persists.+ * create thread render it, so the thread keeps the same layout across the `/tasks/new → /tasks/:id` handoff.*/export function TaskRunSceneShell({task,selectedRun,- isHeaderLoading,+ isHeaderLoading = false,titleActions,sceneMenuBarEnabled,onArchive,@@ -83,9 +84,9 @@ export function TaskRunSceneShell({</SceneMenuBar>)}<ScenePanel>- {isHeaderLoading || !task ? (+ {isHeaderLoading ? (<TaskPanelSkeleton />- ) : (+ ) : task ? (<><ScenePanelInfoSection><div className="flex flex-col gap-3">@@ -121,7 +122,7 @@ export function TaskRunSceneShell({</ButtonPrimitive></ScenePanelActionsSection></>- )}+ ) : null}</ScenePanel>{taskError && !task ? (diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.tsindex 57abb7f97a2a..41fd1d5e9124 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.ts@@ -197,6 +197,64 @@ describe('taskDetailSceneLogic', () => {})describe('progressive selected run loading', () => {+ it('selects a successor before the refreshed list arrives and isolates historical selection', async () => {+ const logic = taskDetailSceneLogic({ taskId: 'task-123' })+ const other = taskDetailSceneLogic({ taskId: 'task-other' })+ logic.mount()+ other.mount()+ await expectLogic(logic).toFinishAllListeners()+ const previous = createMockRun('run-previous', TaskRunStatus.COMPLETED)+ logic.actions.loadTaskRunsSuccess([previous])+ const run = {+ ...createMockRun('run-successor', TaskRunStatus.QUEUED),+ runtime_adapter: null,+ reasoning_effort: null,+ artifacts: [],+ }++ logic.actions.continueWithRun({ run, streamKey: previous.id, draft: 'A newer draft' })+ expect(logic.values.selectedRun).toEqual(run)+ expect(logic.values.isRunPending).toBe(false)+ expect(other.values.runContinuation).toBe(null)+ expect(other.values.selectedRunId).toBe(null)++ await expectLogic(logic).toFinishAllListeners()+ logic.actions.loadTaskRunsSuccess([previous])+ expect(logic.values.selectedRunId).toBe(run.id)+ expect(logic.values.selectedRun).toEqual(run)+ logic.actions.setSelectedRunId(previous.id, 'task-123')+ expect(logic.values.runContinuation).toBe(null)+ expect(logic.values.selectedRun).toEqual(previous)+ logic.unmount()+ other.unmount()+ })++ it('treats a queued successor as the latest run while the list still holds the failed predecessor', async () => {+ const logic = taskDetailSceneLogic({ taskId: 'task-123' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ const previous = createMockRun('run-previous', TaskRunStatus.FAILED)+ logic.actions.loadTaskRunsSuccess([previous])+ expect(logic.values.latestRun).toEqual(previous)++ const successor = {+ ...createMockRun('run-successor', TaskRunStatus.QUEUED),+ runtime_adapter: null,+ reasoning_effort: null,+ artifacts: [],+ }+ logic.actions.continueWithRun({ run: successor, streamKey: previous.id, draft: '' })+ expect(logic.values.latestRun).toEqual(successor)++ await expectLogic(logic).toFinishAllListeners()+ logic.actions.loadTaskRunsFailure('Could not load task runs', new ApiError('nope', 500))+ expect(logic.values.latestRun).toEqual(successor)++ logic.actions.loadTaskRunsSuccess([successor, previous])+ expect(logic.values.latestRun).toEqual(successor)+ logic.unmount()+ })+it('uses runs from the list without refetching selected run detail', async () => {const logic = taskDetailSceneLogic({ taskId: 'task-123' })logic.mount()diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.tsindex f0859143351f..064d0ed6feea 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.ts@@ -18,8 +18,11 @@ import { router } from 'kea-router'import api from 'lib/api'import { isUUIDLike } from 'lib/utils/guards'+import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'+import { isApiNotFound, loadErrorMessage } from '../../lib/load-error'import { phDebugQueryParams } from '../../lib/ph-debug'+import type { RunContinuationHandoff } from '../../logics/runInteractionLogic'import { TaskLogicProps, taskLogic } from '../../logics/taskLogic'import { tasksLogic } from '../../logics/tasksLogic'import { TaskRun } from '../../types/taskTypes'@@ -38,10 +41,12 @@ export interface taskDetailSceneLogicValues {isHeaderLoading: booleanisRunPending: booleanisTaskPending: boolean+ latestRun: TaskRunDetailDTOApi | null+ runContinuation: RunContinuationHandoff | nullruns: TaskRun[]runsError: string | nullrunsLoading: boolean- selectedRun: TaskRun | null+ selectedRun: TaskRunDetailDTOApi | nullselectedRunData: TaskRun | nullselectedRunDataLoading: booleanselectedRunError: string | null@@ -73,6 +78,12 @@ export interface taskDetailSceneLogicActions {updateTask: (args_0: { data: TaskUpsertProps }) => {data: TaskUpsertProps} // taskLogic+ clearContinuationDraft: (runId: string) => {+ runId: string+ }+ continueWithRun: (handoff: RunContinuationHandoff) => {+ handoff: RunContinuationHandoff+ }loadSelectedTaskRun: () => anyloadSelectedTaskRunFailure: (error: string,@@ -120,14 +131,20 @@ export interface taskDetailSceneLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {taskId: (arg: any) => any- selectedRun: (selectedRunData: TaskRun | null, runs: TaskRun[], selectedRunId: string | null) => TaskRun | null+ selectedRun: (+ selectedRunData: TaskRun | null,+ runs: TaskRun[],+ selectedRunId: string | null,+ runContinuation: RunContinuationHandoff | null+ ) => TaskRunDetailDTOApi | null+ latestRun: (runs: TaskRun[], runContinuation: RunContinuationHandoff | null) => TaskRunDetailDTOApi | nullcanEditRepository: (runs: TaskRun[]) => booleanisTaskPending: (taskLoading: boolean, task: Task | null) => booleanisRunPending: (runsLoading: boolean,runs: TaskRun[],selectedRunDataLoading: boolean,- selectedRun: TaskRun | null+ selectedRun: TaskRunDetailDTOApi | null) => booleanisHeaderLoading: (isTaskPending: boolean, isRunPending: boolean) => booleantitle: (task: Task | null) => string@@ -157,6 +174,8 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([actions({setSelectedRunId: (runId: TaskRun['id'] | null, taskId: string) => ({ runId, taskId }),updateRun: (run: TaskRun) => ({ run }),+ continueWithRun: (handoff: RunContinuationHandoff) => ({ handoff }),+ clearContinuationDraft: (runId: string) => ({ runId }),}),reducers(({ props }) => ({@@ -164,6 +183,17 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([null as TaskRun['id'] | null,{setSelectedRunId: (state, { runId, taskId }) => (taskId === props.taskId ? runId : state),+ continueWithRun: (state, { handoff }) => (handoff.run.task === props.taskId ? handoff.run.id : state),+ },+ ],+ runContinuation: [+ null as RunContinuationHandoff | null,+ {+ continueWithRun: (state, { handoff }) => (handoff.run.task === props.taskId ? handoff : state),+ clearContinuationDraft: (state, { runId }) =>+ state?.run.id === runId ? { ...state, draft: '' } : state,+ setSelectedRunId: (state, { runId, taskId }) =>+ taskId === props.taskId && state?.run.id !== runId ? null : state,},],runs: [@@ -238,15 +268,35 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([selectors({taskId: [() => [(_, props) => props.taskId], (taskId) => taskId],selectedRun: [- (s) => [s.selectedRunData, s.runs, s.selectedRunId],- (selectedRunData: TaskRun | null, runs: TaskRun[], selectedRunId: TaskRun['id'] | null): TaskRun | null => {+ (s) => [s.selectedRunData, s.runs, s.selectedRunId, s.runContinuation],+ (+ selectedRunData: TaskRun | null,+ runs: TaskRun[],+ selectedRunId: TaskRun['id'] | null,+ continuation: RunContinuationHandoff | null+ ): TaskRunDetailDTOApi | null => {if (selectedRunData && selectedRunData.id === selectedRunId) {return selectedRunData}if (!selectedRunId) {return null}- return runs.find((run) => run.id === selectedRunId) ?? null+ return (+ runs.find((run) => run.id === selectedRunId) ??+ (continuation?.run.id === selectedRunId ? continuation.run : null)+ )+ },+ ],+ // The newest run, for the run actions in the header. A handoff successor is selected before the+ // refreshed runs list holds it — and stays out of that list for good when the refresh fails — so+ // prefer it over the terminal predecessor still sitting at the head of the stale list.+ latestRun: [+ (s) => [s.runs, s.runContinuation],+ (runs: TaskRun[], continuation: RunContinuationHandoff | null): TaskRunDetailDTOApi | null => {+ if (continuation && !runs.some((run) => run.id === continuation.run.id)) {+ return continuation.run+ }+ return runs[0] ?? null},],canEditRepository: [@@ -265,8 +315,8 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([runsLoading: boolean,runs: TaskRun[],selectedRunDataLoading: boolean,- selectedRun: TaskRun | null- ): boolean => (runsLoading && runs.length === 0) || (selectedRunDataLoading && !selectedRun),+ selectedRun: TaskRunDetailDTOApi | null+ ): boolean => !selectedRun && ((runsLoading && runs.length === 0) || selectedRunDataLoading),],// The header (task panel + title + run metadata) and the run log share the runs-loading phase, so// both resolve together: one skeleton-only loading state, no piecemeal pop-in.@@ -283,6 +333,11 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([}),listeners(({ actions, values, props }) => ({+ continueWithRun: ({ handoff }) => {+ if (handoff.run.task === props.taskId) {+ actions.loadTaskRuns()+ }+ },setSelectedRunId: ({ runId, taskId }) => {if (taskId !== props.taskId || !runId) {return@@ -303,6 +358,9 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([actions.loadTaskRuns()},loadTaskRunsSuccess: ({ runs }) => {+ if (values.runContinuation?.run.id === values.selectedRunId) {+ return+ }// Default to the latest run. An explicit ?runId deep-link (e.g. from an Inbox signal report)// still wins so those links land on the run they reference; we just never write it ourselves.const runIdFromUrl = router.values.searchParams.runIddiff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.tsindex 3d10674511fa..9597463d310f 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts@@ -10,7 +10,7 @@ import { initKeaTests } from '~/test/init'import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'-import { attachedContextLogic } from '../../api/logics'+import { attachedContextLogic, runStreamLogic } from '../../api/logics'import { composerSeedLogic } from '../../logics/composerSeedLogic'import { runCancellationLogic } from '../../logics/runCancellationLogic'import { toolStreamEventsLogic } from '../../logics/toolStreamEventsLogic'@@ -71,7 +71,7 @@ describe('taskTrackerSceneLogic', () => {},'/api/projects/:team/tasks/:id/run/': async ({ request }) => {runBody = (await request.json()) as Record<string, any>- return [200, { id: 'new-task', latest_run: 'run-1' }]+ return [200, { id: 'new-task', latest_run: { id: 'run-1' } }]},},})@@ -111,6 +111,10 @@ describe('taskTrackerSceneLogic', () => {logic.actions.setNewTaskData({ description: 'A synthetic task' })logic.actions.submitNewTask()const streamKey = logic.values.activeCreation!.streamKey+ expect(runStreamLogic({ streamKey }).values.threadItems).toEqual([+ expect.objectContaining({ type: 'human_message', text: 'A synthetic task' }),+ ])+ expect(runStreamLogic({ streamKey }).values.streamPhase).toBe('provisioning')const cancellation = runCancellationLogic({ streamKey })const unmount = cancellation.mount()try {@@ -165,6 +169,50 @@ describe('taskTrackerSceneLogic', () => {expect(logic.values.hasDesktopAccess).toBe(false)})+ it.each(['task', 'run', 'missing_run'] as const)(+ 'restores the composer and startup draft when %s creation fails',+ async (failure) => {+ let finishRequest!: () => void+ const request = new Promise<void>((resolve) => {+ finishRequest = resolve+ })+ useMocks({+ post: {+ '/api/projects/:team/tasks/': async () => {+ if (failure === 'task') {+ await request+ return [500, { detail: 'Task creation failed' }]+ }+ return [201, { id: 'new-task', latest_run: null }]+ },+ '/api/projects/:team/tasks/:id/run/': async () => {+ await request+ return failure === 'run'+ ? [500, { detail: 'Run creation failed' }]+ : [200, { id: 'new-task', latest_run: null }]+ },+ },+ })+ logic.mount()+ router.actions.push('/tasks/new')+ logic.actions.setNewTaskData({ description: 'Explain the example chart' })+ logic.actions.submitNewTask()+ const streamKey = logic.values.activeCreation!.streamKey+ expect(runStreamLogic({ streamKey }).values.streamPhase).toBe('provisioning')+ logic.actions.setStartupDraft('Include a weekly comparison')++ await expectLogic(logic, finishRequest).toFinishAllListeners()++ expect(logic.values.activeCreation).toBeNull()+ expect(logic.values.newTaskData.description).toBe(+ 'Explain the example chart\n\nInclude a weekly comparison'+ )+ expect(logic.values.isSubmittingTask).toBe(false)+ expect(router.values.location.pathname).toContain('/tasks/new')+ expect(toolEvents.values.applyBackTargetClaims[streamKey]).toBeUndefined()+ }+ )+// PostHog AI can run without a repo: a description-only submit must still create and run the task with a// null repository, not bail. Guards against re-adding a "Repository is required" gate on the send path.it('creates and runs a task with no repository selected', async () => {@@ -210,7 +258,7 @@ describe('taskTrackerSceneLogic', () => {},'/api/projects/:team/tasks/:id/run/': async ({ request }) => {runBody = (await request.json()) as Record<string, any>- return [200, { id: 'new-task', latest_run: 'run-1' }]+ return [200, { id: 'new-task', latest_run: { id: 'run-1' } }]},},})@@ -567,7 +615,7 @@ describe('taskTrackerSceneLogic', () => {createBody = (await request.json()) as Record<string, any>return [200, { id: 'new-task', ...createBody }]},- '/api/projects/:team/tasks/:id/run/': () => [200, { id: 'new-task' }],+ '/api/projects/:team/tasks/:id/run/': () => [200, { id: 'new-task', latest_run: { id: 'run-1' } }],},})diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex 4606d4a3cbf9..23b926279479 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -32,6 +32,7 @@ import { composerSeedLogic } from '../../logics/composerSeedLogic'import type { ComposerSeed } from '../../logics/composerSeedLogic'import { modelCatalogueLogic } from '../../logics/modelCatalogueLogic'import { runCancellationLogic } from '../../logics/runCancellationLogic'+import type { RunContinuationHandoff } from '../../logics/runInteractionLogic'import { runnerPanelLogic } from '../../logics/runnerPanelLogic'import type { ActiveCreation } from '../../logics/runnerPanelLogic'import { taskRunDefaultsLogic } from '../../logics/taskRunDefaultsLogic'@@ -410,7 +411,11 @@ export interface taskTrackerSceneLogicActions {submitNewTaskSuccess: () => {value: true}- updateActiveCreationRun: (runId: string) => {+ updateActiveCreationRun: (+ runId: string,+ handoff?: RunContinuationHandoff+ ) => {+ handoff: RunContinuationHandoff | undefinedrunId: string}}@@ -513,7 +518,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([openExistingTask: (task: Task) => ({ task }),// Re-points the panel at a fresh run started from the composer on a reopened terminal task// (the run surface's own re-pointing targets the detail scene, which the panel doesn't render).- updateActiveCreationRun: (runId: string) => ({ runId }),+ updateActiveCreationRun: (runId: string, handoff?: RunContinuationHandoff) => ({ runId, handoff }),blockOnConsent: true,clearConsentBlock: true,// Pulls any pending `composerSeedLogic` seed into the composer (prefill + optional auto-submit).@@ -834,6 +839,9 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([if (disposables.isDisposed) {return}+ if (!runId) {+ throw new Error('Run creation did not return a run ID')+ }// Mark the seeded non-text refs sent under the created task, so the run's first follow-up// (sent via `runInteractionLogic`) doesn't re-wrap them. Text items always resend.@@ -871,7 +879,13 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([return}actions.releaseApplyBackTargets(streamKey)- actions.clearActiveCreation()+ if (values.activeCreation?.streamKey === streamKey) {+ const draft = values.activeCreation.draft+ if (draft) {+ actions.setNewTaskData({ description: [values.newTaskData.description, draft].join('\n\n') })+ }+ actions.clearActiveCreation()+ }if (error instanceof ApiError && error.code === 'warm_run_activation_unavailable') {lemonToast.error("Couldn't start this run yet. Please try again.")}@@ -895,11 +909,16 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([actions.setHistoryExpanded(false)router.actions.push(`/tasks/${task.id}`)},- updateActiveCreationRun: ({ runId }) => {+ updateActiveCreationRun: ({ runId, handoff }) => {if (!values.activeCreation?.taskId) {return}- actions.setActiveCreation({ streamKey: runId, taskId: values.activeCreation.taskId, runId })+ actions.setActiveCreation({+ streamKey: handoff?.streamKey ?? values.activeCreation.streamKey,+ taskId: values.activeCreation.taskId,+ runId,+ draft: handoff?.draft ?? values.activeCreation.draft,+ })},// A seed arriving while this composer is already mounted (the panel was open when the host set it).// `setSeed` is connected from this instance's props-keyed seed logic — the bare `composerSeedLogic`diff --git a/products/posthog_ai/frontend/types/taskTypes.ts b/products/posthog_ai/frontend/types/taskTypes.tsindex 1f5f36bb12eb..4da48e3a6a38 100644--- a/products/posthog_ai/frontend/types/taskTypes.ts+++ b/products/posthog_ai/frontend/types/taskTypes.ts@@ -1,6 +1,6 @@import { Optional } from 'lib/utils/types'-import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'+import { type TaskRunDetailDTOApi, TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'export function isPiTaskRuntime(runtime: TaskRuntimeEnumApi | undefined): boolean {return runtime === TaskRuntimeEnumApi.Pi@@ -50,35 +50,9 @@ export enum TaskRunEnvironment {CLOUD = 'cloud',}-export interface TaskRunArtifact {- id?: string- name: string- type: string- source?: string- size?: number- content_type?: string- storage_path: string- uploaded_at: string-}--export interface TaskRun {- id: string- task: string- stage: string | null- branch: string | null+export interface TaskRun extends TaskRunDetailDTOApi {status: TaskRunStatusenvironment: TaskRunEnvironment- runtime_adapter: string | null- model: string | null- reasoning_effort: string | null- log_url: string | null- error_message: string | null- output: Record<string, any> | null- state: Record<string, any>- artifacts: TaskRunArtifact[]- created_at: string- updated_at: string- completed_at: string | null}export interface Task {