:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(phai): open task thread optimistically on send (#67099)
Georgiy Tarasov990482718b81
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 92494ce3acf8..29f2a084a523 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4372,6 +4372,18 @@ snapshots:hash: v1.k794b7964.2c8b08cca3b552e3ee3670eb19b017cd9b760982dff9128cde00bb8ae9029b8b.0_A_iSZDzamyJr0nr6qMXHrLFSVxf2C2WO2ZfzGkjnAproducts-posthog-ai-queuedmessagelist--single--light:hash: v1.k794b7964.80c03908f588a87222265093441fb1a923d47c312fdc4936d9396b1759a44232.-zIaOwO0H_QNqp98fu2Of3ZE-TL8tCQdVLfWQoun2ws+ products-posthog-ai-runalertactivity--agent-crash--dark:+ hash: v1.k794b7964.76173d0e37304db146985034c13118b964b58aacd67f79b1b23fd749f2812968.5t-_qtjRmaGwTtCDO9QtDFA0ldYjlMnxtpgt5kxfoeA+ products-posthog-ai-runalertactivity--agent-crash--light:+ hash: v1.k794b7964.ce4475c7b2f43b0682b4f2eff9a5b15e8e94617845294dbbe24a389def860158.Lmo5t2PJwGNDO8_541yNP6G4xmu31tWSzlPw8zjUlaU+ products-posthog-ai-runalertactivity--agent-error--dark:+ hash: v1.k794b7964.893f31390faab297522f3f0593f11c97d1620d8a93345cdd35a671022004afcb.k60ZZKqBakEQc0k2f3q6PVZ-BE4N02ZDWT-pOri-yHo+ products-posthog-ai-runalertactivity--agent-error--light:+ hash: v1.k794b7964.99976cce79d3f860b23d1d4773d1ba45301682a03fe4c0c33b5f9e67f8db119a.oWckFqDvm-e7ifE-r6cqFdmRVrFvzp2Z8ucNCQIN5t4+ products-posthog-ai-runalertactivity--connection-lost--dark:+ hash: v1.k794b7964.8bdb645a7ba358ded15342e3b1e255074ed71de360a3cddc22e7fe11ecb67753._AA7m1NZ3G3rq30siy0ZpzZvgsPp1o8sb_incGK0-o4+ products-posthog-ai-runalertactivity--connection-lost--light:+ hash: v1.k794b7964.80ee310e5db116a96505ff364d55e68a8e07922ea08eca9e1ccfdc44c79abf37.DwLSFQhTYea47P0SPTaP50bRj-ELceiUVBOU98i0wEQproducts-workflows-customerioimportmodal--all-steps-completed--dark:hash: v1.k794b7964.679720cf72d72cd35bb4c4a2e86094627df27ff2798b4244c5d29a6a767f3861.AvZ-0V3qNglzE2ZWUOcEjHFnSe9Qs68t-u03-ytn7VIproducts-workflows-customerioimportmodal--all-steps-completed--light:diff --git a/products/posthog_ai/frontend/README.md b/products/posthog_ai/frontend/README.mdindex 4148677dcbe2..14ccdaf92155 100644--- a/products/posthog_ai/frontend/README.md+++ b/products/posthog_ai/frontend/README.md@@ -73,7 +73,8 @@ import { Composer, QueuedMessageList } from 'products/posthog_ai/frontend/api/primport { runInteractionLogic } from 'products/posthog_ai/frontend/api/logics'// Bind runInteractionLogic (the follow-up/queue facade) keyed by the same runId RunSurface.Root binds.-const { draft, isSubmitting, queuedMessages } = useValues(runInteractionLogic(props))+const { draft, isSubmitting, isBusy, queuedMessages } = useValues(runInteractionLogic(props))+const { cancelRun } = useActions(runInteractionLogic(props));<RunSurface.Root taskId={task.id} runId={run.id} interaction="live"><div className="@container/thread flex flex-col h-full overflow-hidden"><div className="flex-1 min-h-0">@@ -81,7 +82,14 @@ const { draft, isSubmitting, queuedMessages } = useValues(runInteractionLogic(pr</div><RunSurface.Resources /><RunSurface.Composer>- <Composer.Root value={draft} onChange={setDraft} onSubmit={submit} loading={isSubmitting}>+ <Composer.Root+ value={draft}+ onChange={setDraft}+ onSubmit={submit}+ loading={isSubmitting}+ isTurnActive={isBusy}+ onStop={() => cancelRun()}+ >{/* …Composer.Frame / Field / Textarea / Submit… */}</Composer.Root></RunSurface.Composer>@@ -90,6 +98,10 @@ const { draft, isSubmitting, queuedMessages } = useValues(runInteractionLogic(pr</RunSurface.Root>```+Pass `isTurnActive` + `onStop` to make the send button a **Stop** button while the agent is working a turn and+the input is empty (clicking cancels the run); with drafted text it stays **Send** and queues the follow-up.+Omit both for a send-only composer.+### Custom layout via the `RunSurface` compound`RunSurface.Root` (Tier 1, `api/runSurface`) binds the stream logic and bootstraps the run; the slots@@ -98,6 +110,42 @@ const { draft, isSubmitting, queuedMessages } = useValues(runInteractionLogic(prcomposer children for an interactive one. For something even more bespoke, drop to the Tier 2 primitives(`ThreadView`, `ResourcesBar`, `Composer.*`, `ContextUsageBar`) and bind `runStreamLogic` yourself.+### Optimistically open a run before it exists++To show the thread the instant a user hits send — their message + a "spinning up" indicator — before the+create/run round-trips finish, mount `RunSurface.Root` in its **pending** state (a `null` `runId` keyed by a+client `streamKey`), seed it via `runStreamLogic.startOptimisticRun(message)`, then supply the real `runId`+once created; the surface attaches it (preserving the seed) and the live SSE echo dedups the message.++```tsx+import { runStreamLogic } from 'products/posthog_ai/frontend/api/logics'+import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'++const streamKey = `draft-${uuid()}`+const stream = runStreamLogic({ streamKey })+stream.mount() // hold it across the render swap; release when done+stream.actions.startOptimisticRun(message) // empty → "spinning up" + the typed message++// render the pending surface (no run yet):+;<RunSurface.Root taskId="" runId={null} streamKey={streamKey} interaction="live">+ <RunSurface.Thread />+</RunSurface.Root>++// …after api create/run resolve, set runId on the same surface to attach + stream it.+```++The attach is **idempotent and seed-preserving** via `runStreamLogic`'s `bootstrappedRunId` /+`awaitingOptimisticAttach` state — so the run can be adopted by a _different_ surface that mounts later, not+only by an in-place `runId` flip. A consumer that navigates (e.g. `/tasks/new → /tasks/:id`) keeps the seeded+instance alive (hold the manual `.mount()`), then has the destination surface bind the **same `streamKey`** plus+the real `runId`: `RunSurface.Root` sees the instance is already bootstrapped for that run and adopts it without+a `reset()` — no skeleton re-flash, the thread is continuous across the unmount/mount. If that destination also+drives `runInteractionLogic`, pass it the same `streamKey` (a `streamKey ?? runId` connect-key) so the composer+reads the exact stream the thread renders; `runInteractionLogic` still keys its own per-run state by `runId`.++The tasks runner composes exactly this (`scenes/TaskTracker/taskTrackerSceneLogic.ts` + `TaskCreateThread` for+the pending phase, then `TaskDetailPage → TaskRunLog → TaskRunChat` adopting the seeded stream after navigation).+### Bespoke / compact thread via `Thread.*` atoms```tsxdiff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.tsindex 8b232142f979..470da81ca0cf 100644--- a/products/posthog_ai/frontend/api/primitives.ts+++ b/products/posthog_ai/frontend/api/primitives.ts@@ -59,6 +59,7 @@ export {} from '../components/ActivityPrimitives'export type { ActivityStatus } from '../components/ActivityPrimitives'export { RunActivity } from '../components/RunActivity'+export { RunAlertActivity } from '../components/RunAlertActivity'export { PermissionInput } from '../components/PermissionInput'export { QuestionInput } from '../components/QuestionInput'diff --git a/products/posthog_ai/frontend/components/RunAlertActivity.stories.tsx b/products/posthog_ai/frontend/components/RunAlertActivity.stories.tsxnew file mode 100644index 000000000000..a43a4e5c00fc--- /dev/null+++ b/products/posthog_ai/frontend/components/RunAlertActivity.stories.tsx@@ -0,0 +1,43 @@+import type { Meta, StoryObj } from '@storybook/react'++import { RunAlertActivity } from './RunAlertActivity'++// Logic-free leaf — the one card for every run stream/connection alert, driven entirely by props (no kea+// binding), so each story is just `args`. `reconnecting` renders a live Spinner and drives the thread footer;+// the failed kinds render inline in the thread for genuine agent failures.+const meta: Meta<typeof RunAlertActivity> = {+ title: 'Products/PostHog AI/RunAlertActivity',+ component: RunAlertActivity,+ tags: ['autodocs'],+ render: (args) => (+ <div className="max-w-180 mx-auto p-4">+ <RunAlertActivity {...args} />+ </div>+ ),+}+export default meta++type Story = StoryObj<typeof RunAlertActivity>++/** Terminal state after reconnect attempts are exhausted — title only, no detail to surface. */+export const ConnectionLost: Story = {+ args: { kind: 'connection_failed' },+}++/** Genuine agent failure — the detail message rides the always-visible region, not the collapsed body. */+export const AgentError: Story = {+ args: { kind: 'agent_error', message: 'The agent hit an unexpected error while running a tool.' },+}++/** The agent process died mid-run — same failed card, distinct title. */+export const AgentCrash: Story = {+ args: { kind: 'agent_crash', message: 'The agent stopped unexpectedly. Restart the run to continue.' },+}++/** Live reconnect banner with the attempt counter. */+export const Reconnecting: Story = {+ args: { kind: 'reconnecting', attempt: 2, maxAttempts: 10 },+ // The reconnecting icon is an indefinitely-spinning Spinner the VR snapshot runner would wait forever to+ // settle, so exclude this story from the snapshot run (same precedent as Composer's Loading story).+ tags: ['test-skip'],+}diff --git a/products/posthog_ai/frontend/components/RunAlertActivity.test.tsx b/products/posthog_ai/frontend/components/RunAlertActivity.test.tsxnew file mode 100644index 000000000000..b216fdff9c4b--- /dev/null+++ b/products/posthog_ai/frontend/components/RunAlertActivity.test.tsx@@ -0,0 +1,27 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'++import { RunAlertActivity } from './RunAlertActivity'++describe('RunAlertActivity', () => {+ afterEach(cleanup)++ it('shows the reconnect attempt counter while reconnecting', () => {+ render(<RunAlertActivity kind="reconnecting" attempt={2} maxAttempts={10} />)++ expect(screen.getByText('Reconnecting to agent')).toBeInTheDocument()+ expect(screen.getByText('Attempt 2 of 10')).toBeInTheDocument()+ })++ it.each([+ ['connection_failed', 'Connection lost'],+ ['agent_error', 'Agent error'],+ ['agent_crash', 'Agent stopped unexpectedly'],+ ] as const)('renders the %s title with its detail message', (kind, title) => {+ render(<RunAlertActivity kind={kind} message="boom" />)++ expect(screen.getByText(title)).toBeInTheDocument()+ expect(screen.getByText('boom')).toBeInTheDocument()+ })+})diff --git a/products/posthog_ai/frontend/components/RunAlertActivity.tsx b/products/posthog_ai/frontend/components/RunAlertActivity.tsxnew file mode 100644index 000000000000..22b9b3a93020--- /dev/null+++ b/products/posthog_ai/frontend/components/RunAlertActivity.tsx@@ -0,0 +1,62 @@+import { IconWarning } from '@posthog/icons'+import { Spinner } from '@posthog/lemon-ui'++import { MarkdownMessage } from '../messages/MarkdownMessage'+import type { RunAlertKind, RunConnectionState } from '../types/streamTypes'+import { Activity } from './ActivityPrimitives'++interface RunAlertActivityProps extends RunConnectionState {+ /** Stable id for the underlying `Activity` (drives markdown substep ids). Defaults per kind. */+ id?: string+}++const TITLES: Record<RunAlertKind, string> = {+ reconnecting: 'Reconnecting to agent',+ connection_failed: 'Connection lost',+ agent_error: 'Agent error',+ agent_crash: 'Agent stopped unexpectedly',+}++/**+ * The single Activity-based card for every run stream/connection alert, used in two places:+ * - the thread footer (selector-driven, `runStreamLogic.runConnectionState`) for the live `reconnecting`+ * banner (attempt counter + backoff) and its terminal `connection_failed` state, and+ * - inline in the thread (`ThreadRow`) for genuine agent failures (`agent_error` / `agent_crash`).+ *+ * It replaces the old inline red `AssistantFailureMessage` bubble for the sandbox runtime. A failed card's+ * `Activity` body auto-collapses, so the detail message rides the always-visible `children` region (mirrors+ * `ToolActivity`'s failed-error pattern) rather than the collapsible `details`.+ */+export function RunAlertActivity({ kind, id, attempt, maxAttempts, message }: RunAlertActivityProps): JSX.Element {+ const activityId = id ?? `run-alert-${kind}`++ if (kind === 'reconnecting') {+ const subtitle = attempt && maxAttempts ? `Attempt ${attempt} of ${maxAttempts}` : 'Attempting to reconnect…'+ return (+ <Activity+ id={activityId}+ title={TITLES.reconnecting}+ subtitle={subtitle}+ status="in_progress"+ icon={<Spinner className="size-3" />}+ />+ )+ }++ return (+ <Activity+ id={activityId}+ title={TITLES[kind]}+ status="failed"+ icon={<IconWarning className="size-4 text-danger" />}+ animate={false}+ showCompletionIcon={false}+ >+ {message ? (+ <div className="text-danger">+ <MarkdownMessage content={message} id={`${activityId}-message`} />+ </div>+ ) : null}+ </Activity>+ )+}diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsxindex 2a68e6c37783..b219e98cf95f 100644--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx@@ -15,8 +15,15 @@ import { ThreadView } from './ThreadView'export interface RunSurfaceProps {taskId: string- runId: string- /** Stable logic key; defaults to `runId` (the run is the unit being viewed). */+ /**+ * The run to bootstrap and stream. Pass `null`/`''` to mount in a **pending** state — the thread renders+ * whatever's seeded in the bound `runStreamLogic` (an optimistic first message + provisioning via+ * `startOptimisticRun`) and never bootstraps; supply the real id once created to attach it on the same+ * instance (seed-preserving fast path). Requires an explicit `streamKey` while pending, since there's no+ * run id to key on.+ */+ runId: string | null+ /** Stable logic key; defaults to `runId` (the run is the unit being viewed). Required when `runId` is pending. */streamKey?: string/** Telemetry tag only — omit for conversation-less runs (automation, Slack, signals, PR-triggered). */conversationId?: string@@ -38,8 +45,8 @@ export interface RunSurfaceProps {// the slots are presentational and the composer UI is supplied by the consumer as children.interface RunSurfaceContextValue {- /** Original run id passed to `bootstrapRun`. */- rawRunId: string+ /** Original run id passed to `bootstrapRun`; `null`/`''` while the surface is pending (no run yet). */+ rawRunId: string | null/** Logic key (used for child stream keys). */runId: stringinteraction: 'live' | 'read-only'@@ -77,7 +84,8 @@ function RunSurfaceRoot({children,}: RunSurfaceRootProps): JSX.Element {const replayOnly = interaction !== 'live'- const logicKey = streamKey ?? runId+ // A pending surface (no run id) must supply `streamKey` to key on; `runId` is the key otherwise.+ const logicKey = streamKey ?? runId ?? ''// The scout flag lives 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, a live embed fetches it here. Only the@@ -85,10 +93,11 @@ function RunSurfaceRoot({const { task, taskLoading } = useValues(taskLogic({ taskId }))const { loadTask } = useActions(taskLogic({ taskId }))useEffect(() => {- if (interaction === 'live' && !task && !taskLoading) {+ // `taskId &&`: a pending surface (optimistic create) has no task yet — don't fetch an empty id.+ if (interaction === 'live' && taskId && !task && !taskLoading) {loadTask()}- }, [interaction, task, taskLoading, loadTask])+ }, [interaction, taskId, task, taskLoading, loadTask])const isScout = task?.origin_product === OriginProduct.SIGNALS_SCOUTreturn (@@ -112,15 +121,48 @@ function RunSurfaceRoot({function RunSurfaceBootstrap({ taskId }: { taskId: string }): null {const { rawRunId, interaction } = useRunSurfaceContext()const { bootstrapRun, reset } = useActions(runStreamLogic)+ // The bootstrap decision reads logic-resident state (not a per-component ref) so it survives the+ // optimistic create-thread → detail-page component swap onto the same `streamKey` instance.+ const { bootstrappedRunId, awaitingOptimisticAttach, currentProjectId } = useValues(runStreamLogic)useEffect(() => {+ // Pending: no run to bootstrap yet — leave the seeded optimistic thread (first message ++ // provisioning indicator) untouched until the consumer supplies the real id.+ if (!rawRunId) {+ return+ }+ // Wait for the project to resolve before bootstrapping — firing without it races to an+ // unretryable "No current project" error; the effect re-runs once `currentProjectId` lands.+ if (currentProjectId === null) {+ return+ }+ // Already bootstrapped this run on this instance — idempotent across re-renders and across a+ // consumer swap that adopts the same seeded instance (no reset, so the seed/stream survives).+ if (bootstrappedRunId === rawRunId) {+ return+ }+ if (awaitingOptimisticAttach) {+ // Attaching a freshly-created run to a seeded optimistic instance: skip the reset so the seed+ // survives, and take the fresh-run fast path. The live SSE echo dedups the seeded message.+ bootstrapRun({ taskId, runId: rawRunId, justCreatedRun: true })+ return+ }// Reset first so a reused instance (stable streamKey, changed run) replays/streams the new run// cleanly; the bound logic keys read-only instances apart from any live stream of the same run.// `interaction` is in the deps so a status transition (live → terminal) re-bootstraps the right// mode — the bound logic re-keys on it, so `bootstrapRun`/`reset` are fresh references anyway.reset()bootstrapRun({ taskId, runId: rawRunId })- }, [taskId, rawRunId, interaction, bootstrapRun, reset])+ }, [+ taskId,+ rawRunId,+ interaction,+ bootstrappedRunId,+ awaitingOptimisticAttach,+ currentProjectId,+ bootstrapRun,+ reset,+ ])return null}diff --git a/products/posthog_ai/frontend/components/ThreadRow.tsx b/products/posthog_ai/frontend/components/ThreadRow.tsxindex 5a1e3b60c69b..8c1110f3b8b0 100644--- a/products/posthog_ai/frontend/components/ThreadRow.tsx+++ b/products/posthog_ai/frontend/components/ThreadRow.tsx@@ -7,13 +7,13 @@ import { TaskExecutionStatus as ExecutionStatus } from '~/queries/schema/schema-import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'import { runStreamLogic } from '../logics/runStreamLogic'-import { AssistantFailureMessage } from '../messages/AssistantFailureMessage'import { DebugMessage } from '../messages/DebugMessage'import { MarkdownMessage } from '../messages/MarkdownMessage'import { MessageTemplate } from '../messages/MessageTemplate'import { ReasoningAnswer } from '../messages/ReasoningAnswer'import type { ProgressStep, ThreadItem } from '../types/streamTypes'import { RunActivity } from './RunActivity'+import { RunAlertActivity } from './RunAlertActivity'import { CompactBoundaryItem, StatusItem, TaskNotificationItem } from './ThreadItems'import { ToolCallCard } from './tool/ToolCallCard'import { resolveToolCall } from './tool/toolResolver'@@ -147,7 +147,13 @@ export const ThreadRow = memo(function ThreadRow({return <ToolCallCard message={message} turnComplete={turnComplete} turnCancelled={turnCancelled} />}if (item.type === 'error') {- return <AssistantFailureMessage id={item.id} content={item.errorMessage} />+ return (+ <RunAlertActivity+ id={item.id}+ kind={item.variant === 'crash' ? 'agent_crash' : 'agent_error'}+ message={item.errorMessage}+ />+ )}if (item.type === 'status') {return <StatusItem item={item} />diff --git a/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx b/products/posthog_ai/frontend/components/ThreadView.connection.test.tsxnew file mode 100644index 000000000000..c5f8e862ea51--- /dev/null+++ b/products/posthog_ai/frontend/components/ThreadView.connection.test.tsx@@ -0,0 +1,78 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen, waitFor } from '@testing-library/react'+import { BindLogic, Provider } from 'kea'++import { initKeaTests } from '~/test/init'++import { runStreamLogic } from '../logics/runStreamLogic'+import type { StoredLogEntry } from '../types/wireTypes'+import { ThreadView } from './ThreadView'++// runStreamLogic.test.ts's frame builder isn't exported — copy the one-liner rather than import it.+function notification(method: string, params: Record<string, unknown>): StoredLogEntry {+ return { type: 'notification', notification: { method, params } }+}++describe('ThreadView connection state', () => {+ let logic: ReturnType<typeof runStreamLogic.build>+ const props = { streamKey: 'run-1', conversationId: 'run-1', replayOnly: false }++ beforeEach(() => {+ initKeaTests()+ logic = runStreamLogic(props)+ logic.mount()+ // virtualized={false} so react-window rows render in document flow under jsdom.+ render(+ <Provider>+ <BindLogic logic={runStreamLogic} props={props}>+ <ThreadView virtualized={false} />+ </BindLogic>+ </Provider>+ )+ })++ afterEach(() => {+ cleanup()+ logic?.unmount()+ })++ // Reconnecting projects runConnectionState → footer RunAlertActivity, and its showConnectionStatus gate+ // must suppress the thinking indicator so a mid-run reconnect doesn't read as normal thinking.+ it('renders the reconnecting banner and suppresses the thinking indicator', async () => {+ logic.actions.sseReconnecting(2)++ await waitFor(() => {+ expect(screen.getByText('Reconnecting to agent')).toBeInTheDocument()+ })+ // maxAttempts flows from the selector (MAX_SSE_RECONNECT_ATTEMPTS = 10), not a hand-passed prop.+ expect(screen.getByText('Attempt 2 of 10')).toBeInTheDocument()+ // Reconnecting drives streamPhase to 'provisioning'; without the gate its "Setting up sandbox" line shows.+ expect(screen.queryByText('Setting up sandbox')).toBeNull()+ })++ // A non-retryable stream error sets sseStatus='error', which the selector projects as connection_failed.+ it('renders the connection-failed banner on a non-retryable stream error', async () => {+ logic.actions.handleStreamError({ errorTitle: 'x', retryable: false })++ await waitFor(() => {+ expect(screen.getByText('Connection lost')).toBeInTheDocument()+ })+ })++ // A folded _posthog/error frame renders inline through ThreadRow's RunAlertActivity swap (agent_error kind).+ it('renders an inline agent-error card for a _posthog/error frame', async () => {+ logic.actions.ingestAcpFrame(notification('_posthog/error', { message: 'boom' }), 'replay')++ await waitFor(() => {+ expect(screen.getByText('Agent error')).toBeInTheDocument()+ })+ expect(screen.getByText('boom')).toBeInTheDocument()+ })++ // A fresh, healthy mount must paint no connection banner.+ it('shows no connection banner on a fresh mount', () => {+ expect(screen.queryByText('Reconnecting to agent')).toBeNull()+ expect(screen.queryByText('Connection lost')).toBeNull()+ })+})diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsxindex 201752036f6e..d7506a19e40b 100644--- a/products/posthog_ai/frontend/components/ThreadView.tsx+++ b/products/posthog_ai/frontend/components/ThreadView.tsx@@ -1,5 +1,7 @@import { useValues } from 'kea'-import { memo, useCallback, useMemo } from 'react'+import { memo, useCallback, useEffect, useMemo, useState } from 'react'++import { inStorybookTestRunner } from 'lib/utils/dom'import { runStreamLogic } from '../logics/runStreamLogic'import { ReasoningAnswer } from '../messages/ReasoningAnswer'@@ -7,6 +9,7 @@ import type { ThreadItem } from '../types/streamTypes'import { getRandomThinkingMessage } from '../utils/thinkingMessages'import { ContextUsageBar } from './ContextUsageBar'import { PullRequestCard } from './PullRequestCard'+import { RunAlertActivity } from './RunAlertActivity'import { RunContext } from './RunContext'import { ThreadRow } from './ThreadRow'import { VirtualizedThread } from './VirtualizedThread'@@ -60,6 +63,7 @@ export function ThreadView({turnComplete,currentRunStatus,contextUsage,+ runConnectionState,} = useValues(runStreamLogic)const turnCancelled = currentRunStatus === 'cancelled'const hasActiveProgressItem = threadItems.some(@@ -77,12 +81,18 @@ export function ThreadView({<ThreadHeader branch={branch} baseBranch={baseBranch} repo={repo} /></VirtualizedThread.Row>) : undefined,- [branch, baseBranch, repo]+ [branch, baseBranch, repo, rowClassName])+ // The connection banner (reconnecting / connection-failed) owns the footer line when present, so it+ // takes precedence over the thinking indicator (a mid-run reconnect otherwise reads as normal thinking).+ const showConnectionStatus = !!runConnectionState// `provisioning` (conversations/open POST + cold boot before run_started) also shows the indicator,// gated by !hasActiveProgressItem so real `_posthog/progress` boot steps take precedence.- const showThinking = (streamPhase === 'thinking' || streamPhase === 'provisioning') && !hasActiveProgressItem+ const showThinking =+ (streamPhase === 'thinking' || streamPhase === 'provisioning') &&+ !hasActiveProgressItem &&+ !showConnectionStatusconst thinkingPhase = streamPhase === 'provisioning' ? 'provisioning' : 'thinking'// Post-turn only: a reconnect refetch can fold in a pr_url mid-run, so gate on !isThinking.const pullRequestUrl = !isThinking ? runArtifacts.prUrl : undefined@@ -91,7 +101,7 @@ export function ThreadView({const showContextUsageFooter = showContextUsage && !isThinking && !!contextUsageconst footer = useMemo(() =>- showThinking || pullRequestUrl || showContextUsageFooter ? (+ showThinking || pullRequestUrl || showContextUsageFooter || showConnectionStatus ? (<VirtualizedThread.Row className={rowClassName}><ThreadFootershowThinking={showThinking}@@ -99,10 +109,19 @@ export function ThreadView({pullRequestUrl={pullRequestUrl}prBranch={branch}showContextUsage={showContextUsageFooter}+ showConnectionStatus={showConnectionStatus}/></VirtualizedThread.Row>) : undefined,- [showThinking, thinkingPhase, pullRequestUrl, branch, showContextUsageFooter]+ [+ showThinking,+ thinkingPhase,+ pullRequestUrl,+ branch,+ showContextUsageFooter,+ showConnectionStatus,+ rowClassName,+ ])const renderItem = useCallback(@@ -162,18 +181,23 @@ const ThreadFooter = memo(function ThreadFooter({pullRequestUrl,prBranch,showContextUsage,+ showConnectionStatus,}: {showThinking: booleanthinkingPhase: 'thinking' | 'provisioning'pullRequestUrl?: stringprBranch?: stringshowContextUsage?: boolean+ showConnectionStatus?: boolean}): JSX.Element {- const { currentProgress } = useValues(runStreamLogic)+ // `runConnectionState` is self-subscribed here (like `currentProgress`) so the frequently-updating+ // reconnect attempt counter stays isolated to this leaf and never destabilizes `ThreadView`'s footer.+ const { currentProgress, runConnectionState } = useValues(runStreamLogic)// `gap-1.5` matches the thread's inter-row gap (`VirtualizedThread`'s `gap` default) so stacked footer// items keep the same vertical rhythm as the thread.return (<div className="flex flex-col gap-1.5">+ {showConnectionStatus && runConnectionState && <RunAlertActivity {...runConnectionState} />}{showThinking && <ThinkingIndicator progress={currentProgress} phase={thinkingPhase} />}{pullRequestUrl && <PullRequestCard prUrl={pullRequestUrl} branch={prBranch} />}{showContextUsage && <ContextUsageBar />}@@ -193,10 +217,29 @@ function ThinkingIndicator({progress: string | nullphase: 'thinking' | 'provisioning'}): JSX.Element {- // One roll per mount — re-rolling on every progress transition would visibly swap the verb.- const fallbackMessage = useMemo(() => getRandomThinkingMessage(), [])- const message = progress?.trim() ? progress : phase === 'provisioning' ? 'Spinning up sandbox…' : fallbackMessage- // Match the LangGraph loader: a bubble-free reasoning line (muted brain icon + muted text),- // static (no shimmer), via the shared Activity primitive — not a MessageTemplate bubble.- return <ReasoningAnswer content={message} id="sandbox-thinking" completed={false} showCompletionIcon={false} />+ const [fallbackMessage, setFallbackMessage] = useState(() => getRandomThinkingMessage())++ // Re-roll the gerund every 5s while genuinely thinking; static "Spinning up sandbox…" during provisioning+ // doesn't need it, and rotating in Storybook would make snapshots non-deterministic.+ useEffect(() => {+ if (phase !== 'thinking' || inStorybookTestRunner()) {+ return+ }+ const interval = setInterval(() => setFallbackMessage(getRandomThinkingMessage()), 5000)+ return () => clearInterval(interval)+ }, [phase])++ const message = progress?.trim() ? progress : phase === 'provisioning' ? 'Setting up sandbox' : fallbackMessage+ // Match the LangGraph loader: a bubble-free reasoning line (muted brain icon + muted text), via the+ // shared Activity primitive — not a MessageTemplate bubble. Shimmers only while genuinely thinking;+ // provisioning stays static since it's infra boot, not model reasoning.+ return (+ <ReasoningAnswer+ content={message}+ id="sandbox-thinking"+ completed={false}+ showCompletionIcon={false}+ animate={phase === 'thinking' || phase === 'provisioning'}+ />+ )}diff --git a/products/posthog_ai/frontend/components/composer/Composer.test.tsx b/products/posthog_ai/frontend/components/composer/Composer.test.tsxindex 6f49d8c78cda..5d47cce12b55 100644--- a/products/posthog_ai/frontend/components/composer/Composer.test.tsx+++ b/products/posthog_ai/frontend/components/composer/Composer.test.tsx@@ -7,6 +7,7 @@ import { Composer } from './Composer'describe('Composer', () => {const onChange = jest.fn()const onSubmit = jest.fn()+ const onStop = jest.fn()beforeEach(() => {jest.clearAllMocks()@@ -76,6 +77,22 @@ describe('Composer', () => {expect(onSubmit).toHaveBeenCalledTimes(1)})+ it('turns the send button into a Stop button while a turn is active with empty input', () => {+ const { container } = renderComposer({ value: '', isTurnActive: true, onStop })+ // Enabled (no "Type a message first"), and clicking cancels the run rather than submitting the form.+ expect(getSend(container)).not.toHaveAttribute('aria-disabled', 'true')+ fireEvent.click(getSend(container))+ expect(onStop).toHaveBeenCalledTimes(1)+ expect(onSubmit).not.toHaveBeenCalled()+ })++ it('sends instead of stopping when a turn is active but the input has text', () => {+ const { container } = renderComposer({ value: 'follow up', isTurnActive: true, onStop })+ fireEvent.click(getSend(container))+ expect(onSubmit).toHaveBeenCalledTimes(1)+ expect(onStop).not.toHaveBeenCalled()+ })+it('throws when a part is rendered outside Composer.Root', () => {// Silence the expected React error boundary log.const spy = jest.spyOn(console, 'error').mockImplementation(() => {})diff --git a/products/posthog_ai/frontend/components/composer/Composer.tsx b/products/posthog_ai/frontend/components/composer/Composer.tsxindex 6ca5633e9446..b0d1f0f8f85a 100644--- a/products/posthog_ai/frontend/components/composer/Composer.tsx+++ b/products/posthog_ai/frontend/components/composer/Composer.tsx@@ -11,7 +11,7 @@ import {useRef,} from 'react'-import { IconArrowRight } from '@posthog/icons'+import { IconArrowRight, IconStopFilled } from '@posthog/icons'import { LemonButton, LemonTextArea } from '@posthog/lemon-ui'import { cn } from 'lib/utils/css-classes'@@ -29,6 +29,10 @@ interface ComposerContextValue {disabled: boolean/** Empty input / loading / caller's `disabledReason`, collapsed to a single reason (undefined when sendable). */sendDisabledReason: string | undefined+ /** True when the send button should swap to a Stop button (active turn + empty input + an `onStop` handler). */+ showStop: boolean+ /** Cancels the active turn; drives the Stop button that replaces send when `showStop`. */+ onStop: (() => void) | undefined/** Focuses the textarea when blocked, otherwise calls the caller's `onSubmit`. */submit: () => voidtextAreaRef: RefObject<HTMLTextAreaElement>@@ -57,6 +61,10 @@ export interface ComposerRootProps {disabled?: boolean/** Extra reason to block sending, beyond the internally-handled empty input. */disabledReason?: string+ /** True while the agent is actively working a turn. With empty input, the send button becomes a Stop button. */+ isTurnActive?: boolean+ /** Cancels the active turn. Wired to the Stop button that replaces send when `isTurnActive` and input is empty. */+ onStop?: () => void/** Renders the sticky page-level chrome (bordered, blurred, bottom-pinned) around the input. */isSticky?: boolean/** Follow-up variant: tighter frame border/radius and send-button offset. */@@ -79,6 +87,8 @@ const ComposerRoot = forwardRef<HTMLFormElement, ComposerRootProps>(function Comloading = false,disabled = false,disabledReason,+ isTurnActive = false,+ onStop,isSticky = false,isThreadVisible = false,className,@@ -96,6 +106,10 @@ const ComposerRoot = forwardRef<HTMLFormElement, ComposerRootProps>(function Comconst sendDisabledReason = !value.trim() ? 'Type a message first' : loading ? 'Sending…' : disabledReason+ // While a turn is active with no drafted text, the send button becomes a Stop button (cancel the run)+ // rather than a disabled "Type a message first" — a follow-up with text still sends/queues as usual.+ const showStop = isTurnActive && !value.trim() && !loading && !!onStop+// Focuses the textarea when blocked, otherwise submits — shared by the native form submit and the// textarea keyboard shortcuts.const submit = useCallback(() => {@@ -113,12 +127,26 @@ const ComposerRoot = forwardRef<HTMLFormElement, ComposerRootProps>(function Comloading,disabled,sendDisabledReason,+ showStop,+ onStop,submit,textAreaRef,id,isThreadVisible,}),- [value, onChange, loading, disabled, sendDisabledReason, submit, textAreaRef, id, isThreadVisible]+ [+ value,+ onChange,+ loading,+ disabled,+ sendDisabledReason,+ showStop,+ onStop,+ submit,+ textAreaRef,+ id,+ isThreadVisible,+ ])// The relative wrapper is the positioning context for the absolutely-placed Submit + Placeholder. It's a@@ -308,7 +336,7 @@ export interface ComposerSubmitProps {/** The absolutely-positioned send cluster, sibling of Frame inside Root's relative wrapper. */function ComposerSubmit({ icon, tooltip, className, ...rest }: ComposerSubmitProps): JSX.Element {- const { sendDisabledReason, loading, isThreadVisible } = useComposerContext()+ const { sendDisabledReason, loading, showStop, onStop, isThreadVisible } = useComposerContext()return (<divdata-slot="composer-submit"@@ -318,16 +346,30 @@ function ComposerSubmit({ icon, tooltip, className, ...rest }: ComposerSubmitProclassName)}>- <LemonButton- type="primary"- size="small"- htmlType="submit"- icon={icon ?? <IconArrowRight />}- loading={loading}- disabledReason={sendDisabledReason}- tooltip={sendDisabledReason ? undefined : (tooltip ?? "Let's go!")}- {...rest}- />+ {showStop ? (+ // Stop the active turn. `htmlType="button"` so it never submits the (empty) form; the Enter+ // shortcut still routes through `submit` and just focuses, so Stop stays a click-only affordance.+ <LemonButton+ type="secondary"+ size="small"+ htmlType="button"+ icon={<IconStopFilled />}+ onClick={() => onStop?.()}+ tooltip="Stop"+ {...rest}+ />+ ) : (+ <LemonButton+ type="primary"+ size="small"+ htmlType="submit"+ icon={icon ?? <IconArrowRight />}+ loading={loading}+ disabledReason={sendDisabledReason}+ tooltip={sendDisabledReason ? undefined : (tooltip ?? "Let's go!")}+ {...rest}+ />+ )}</div>)}diff --git a/products/posthog_ai/frontend/e2e/run-surface.spec.ts b/products/posthog_ai/frontend/e2e/run-surface.spec.tsnew file mode 100644index 000000000000..4e93873cc5c8--- /dev/null+++ b/products/posthog_ai/frontend/e2e/run-surface.spec.ts@@ -0,0 +1,226 @@+// 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.++import { mockFeatureFlags } from '@playwright-utils/mockApi'+import { PlaywrightWorkspaceSetupResult, expect, test } from '@playwright-utils/workspace-test-base'+import { Page, Route } from '@playwright/test'++// Flag keys mirror `FEATURE_FLAGS.TASKS` / `FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY` (frontend/src/lib/constants).+// Inlined as literals rather than imported: pulling `lib/constants` into a Node-run Playwright spec drags its+// heavy `types.ts` value-import graph into the test bundle. These keys are stable feature-flag wire strings.+const TASKS_FLAG = 'tasks'+const TASKS_STREAM_VIA_PROXY_FLAG = 'tasks-stream-via-proxy'++// Fixed UUIDs so the `?runId=` deep link clears `taskDetailSceneLogic`'s `isUUIDLike` guard deterministically.+const TASK_ID = '0190a000-0000-4000-8000-0000000000a1'+const RUN_ID = '0190a000-0000-4000-8000-0000000000b2'++interface AcpFrame {+ type: 'notification'+ timestamp?: string+ notification: Record<string, unknown>+}++interface StreamMock {+ // 'body' delivers the frames then EOFs (a clean-EOF live drop); 'hang' never responds so the SSE open+ // stalls short of `sseOpened` — used when a different signal (terminal status, exhausted history) should+ // drive the surface state without the reconnect loop flapping.+ mode: 'body' | 'hang'+ body?: string+}++interface TasksApiMock {+ runStatus: string+ logs: { status: number; body: string }+ stream: StreamMock+}++function agentMessageFrame(messageId: string, text: string): AcpFrame {+ return {+ type: 'notification',+ notification: {+ method: 'session/update',+ params: { update: { sessionUpdate: 'agent_message', messageId, content: { type: 'text', text } } },+ },+ }+}++// A persisted `_posthog/error` frame — the synthetic backend/agent error the run log carries; `foldLogToThread`+// folds it into an inline error card titled "Agent error".+function posthogErrorFrame(message: string): AcpFrame {+ return { type: 'notification', notification: { method: '_posthog/error', params: { message } } }+}++// The `logs/` endpoint replays JSONL — one `StoredLogEntry` per line.+function toJsonl(frames: AcpFrame[]): string {+ return frames.map((frame) => JSON.stringify(frame)).join('\n')+}++// The `stream/` endpoint is `text/event-stream` — one `data:` event per frame. No terminal `task_run_state`+// or `stream-end` sentinel, so once the atomic body is read the reader hits a clean EOF (a drop).+function toSse(frames: AcpFrame[]): string {+ return frames.map((frame) => `data: ${JSON.stringify(frame)}\n\n`).join('')+}++function makeRun(status: string): Record<string, unknown> {+ return {+ id: RUN_ID,+ task: TASK_ID,+ stage: null,+ branch: null,+ status,+ environment: 'cloud',+ log_url: null,+ error_message: null,+ output: null,+ state: {},+ artifacts: [],+ created_at: '2026-07-01T00:00:00Z',+ updated_at: '2026-07-01T00:00:00Z',+ completed_at: status === 'in_progress' ? null : '2026-07-01T00:01:00Z',+ }+}++function makeTask(status: string): Record<string, unknown> {+ return {+ id: TASK_ID,+ task_number: 1,+ slug: 'run-surface-e2e',+ title: 'Run surface e2e task',+ description: '',+ origin_product: 'user_created',+ repository: null,+ github_integration: null,+ json_schema: null,+ internal: false,+ latest_run: makeRun(status),+ created_at: '2026-07-01T00:00:00Z',+ updated_at: '2026-07-01T00:00:00Z',+ created_by: { id: 1, uuid: 'user-1', distinct_id: 'user-1', first_name: 'Test', email: '[email protected]' },+ }+}++function fulfillJson(body: unknown): (route: Route) => Promise<void> {+ return (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(body) })+}++async function routeTasksApi(page: Page, mock: TasksApiMock): Promise<void> {+ const run = makeRun(mock.runStatus)+ // Each pattern is `$`-anchored on the pathname so it matches exactly one endpoint despite the shared+ // `/runs/:id/` prefix (mutually exclusive, so Playwright's route ordering doesn't matter).+ const taskRe = new RegExp(`/tasks/${TASK_ID}/$`)+ const runsRe = new RegExp(`/tasks/${TASK_ID}/runs/$`)+ const runRe = new RegExp(`/tasks/${TASK_ID}/runs/${RUN_ID}/$`)+ const tokenRe = new RegExp(`/runs/${RUN_ID}/stream_token/$`)+ const logsRe = new RegExp(`/runs/${RUN_ID}/logs/$`)+ const streamRe = new RegExp(`/runs/${RUN_ID}/stream/$`)++ await page.route((url) => taskRe.test(url.pathname), fulfillJson(makeTask(mock.runStatus)))+ await page.route(+ (url) => runsRe.test(url.pathname),+ fulfillJson({ results: [run], count: 1, next: null, previous: null })+ )+ await page.route((url) => runRe.test(url.pathname), fulfillJson(run))+ // No `stream_base_url` ⇒ `resolveStreamTarget` returns null ⇒ streaming stays on the mockable Django+ // `stream/` route even when the proxy gate (flag or preflight `is_debug`) is on.+ await page.route((url) => tokenRe.test(url.pathname), fulfillJson({ token: 'e2e-token', stream_base_url: null }))+ await page.route(+ (url) => logsRe.test(url.pathname),+ (route) => route.fulfill({ status: mock.logs.status, contentType: 'application/jsonl', body: mock.logs.body })+ )++ if (mock.stream.mode === 'hang') {+ // Leave the request pending forever; the bootstrap aborts it once the history retries exhaust.+ await page.route(+ (url) => streamRe.test(url.pathname),+ () => new Promise<void>(() => {})+ )+ } else {+ const body = mock.stream.body ?? ''+ await page.route(+ (url) => streamRe.test(url.pathname),+ (route) => route.fulfill({ status: 200, contentType: 'text/event-stream', body })+ )+ }+}++async function openRunDeepLink(page: Page, teamId: string): Promise<void> {+ await page.goto(`/project/${teamId}/tasks/${TASK_ID}?runId=${RUN_ID}`)+ // The fresh workspace has no tasks flag; force posthog-js to re-fetch so the mocked flag lands and the+ // scene's `FEATURE_FLAGS.TASKS` gate opens.+ await page.evaluate(() => {+ const ph = (window as unknown as { posthog?: { reloadFeatureFlags?: () => void } }).posthog+ ph?.reloadFeatureFlags?.()+ })+}++test.describe('Task run surface', () => {+ let workspace: PlaywrightWorkspaceSetupResult | null = null++ test.beforeAll(async ({ playwrightSetup }) => {+ workspace = await playwrightSetup.createWorkspace({ skip_onboarding: true, no_demo_data: true })+ })++ test.beforeEach(async ({ page, playwrightSetup }) => {+ await playwrightSetup.login(page, workspace!)+ await mockFeatureFlags(page, { [TASKS_FLAG]: true, [TASKS_STREAM_VIA_PROXY_FLAG]: false })+ })++ test('terminal replay surfaces the agent error inline', async ({ page }) => {+ // Regression: a terminal run's persisted `_posthog/error` frame must fold into the inline "Agent error"+ // card on replay — not be dropped, and not depend on a live SSE (a terminal run never opens one).+ await routeTasksApi(page, {+ runStatus: 'completed',+ logs: {+ status: 200,+ body: toJsonl([+ agentMessageFrame('m1', 'Doing the thing'),+ posthogErrorFrame('The agent hit an unexpected error'),+ ]),+ },+ stream: { mode: 'hang' },+ })++ await openRunDeepLink(page, workspace!.team_id)++ await expect(page.getByText('Agent error')).toBeVisible({ timeout: 20000 })+ })++ 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.+ await routeTasksApi(page, {+ runStatus: 'in_progress',+ logs: { status: 200, body: toJsonl([agentMessageFrame('m1', 'Working on it')]) },+ stream: {+ mode: 'body',+ body: toSse([agentMessageFrame('s1', 'Streaming'), agentMessageFrame('s2', 'Still streaming')]),+ },+ })++ await openRunDeepLink(page, workspace!.team_id)++ // Assert only the first reconnecting window — `reconnectAttempt` resets to 0 on each reopen so the banner+ // cycles; a single visibility check on the title keeps it deterministic.+ await expect(page.getByText('Reconnecting to agent')).toBeVisible({ timeout: 20000 })+ })++ test('exhausted run history shows connection lost', async ({ page }) => {+ // Regression: exhausting the history-fetch retries on an in-progress run must tear the SSE down and+ // surface the terminal "Connection lost" card — not spin forever or render a live-only, historyless thread.+ await routeTasksApi(page, {+ runStatus: 'in_progress',+ logs: { status: 500, body: '' },+ // Stall the SSE open so only the exhausted history drives the terminal state (no reconnect flapping).+ stream: { mode: 'hang' },+ })++ await openRunDeepLink(page, workspace!.team_id)++ // The history retries back off ~2s + ~4s before giving up, so allow generous headroom.+ await expect(page.getByText('Connection lost')).toBeVisible({ timeout: 30000 })+ })+})diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.tsindex 7fbc99e27219..775bd71fab2f 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts@@ -22,6 +22,13 @@ import { isTerminalRunStatus, runStreamLogic } from './runStreamLogic'export interface RunInteractionLogicProps {taskId: stringrunId: string+ /**+ * Optional override for the bound `runStreamLogic` key. The logic still keys its own per-run state by+ * `runId` (queue, model/effort overrides), but connects to the stream under `streamKey ?? runId` so it+ * can adopt an optimistic-create instance seeded under a client `streamKey` — sharing the exact stream+ * `RunSurface` binds, never diverging from it. API calls still use the real `runId`.+ */+ streamKey?: string/** The run's stored model / reasoning effort, 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@@ -67,11 +74,11 @@ export const runInteractionLogic = kea<runInteractionLogicType>([values: [projectLogic,['currentProjectId'],- runStreamLogic({ streamKey: props.runId }),+ runStreamLogic({ streamKey: props.streamKey ?? props.runId }),['currentRunStatus', 'pendingPermissionRequest', 'respondingToPermission', 'isThinking'],],actions: [- runStreamLogic({ streamKey: props.runId }),+ runStreamLogic({ streamKey: props.streamKey ?? props.runId }),['pushHumanMessage', 'respondToPermission', 'cancelRun', 'markTurnComplete'],],})),diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex 74b81f945b72..f9a018184009 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -16,6 +16,7 @@ import {extractRunArtifacts,mapHttpStatusToStreamError,MAX_CUMULATIVE_RECONNECT_ATTEMPTS,+ MAX_HISTORY_FETCH_ATTEMPTS,MAX_SSE_RECONNECT_ATTEMPTS,mergeResourceProducts,mergeRunArtifacts,@@ -185,6 +186,9 @@ describe('runStreamLogic', () => {let logic: ReturnType<typeof runStreamLogic.build>beforeEach(() => {+ // featureFlagLogic persists flags to localStorage; clear before init so a flag set by one+ // test (e.g. `enableProxy()`) can't leak into a later test's flag-off assertions.+ window.localStorage.clear()initKeaTests()// The logic mirrors the live resume cursor to sessionStorage — clear it so a cursor written// by one test can't seed another test's reconnect.@@ -1897,18 +1901,25 @@ describe('runStreamLogic', () => {viewer.unmount()})- it('surfaces an error item when the snapshot fetch fails and opens no SSE', async () => {+ it('retries the snapshot then surfaces the connection-failed banner (not an inline error), no SSE', async () => {jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)- jest.spyOn(api.tasks.runs, 'getLogEntries').mockRejectedValue({ status: 500 })+ const getLogEntriesSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockRejectedValue({ status: 500 })+ jest.useFakeTimers()const viewer = mountViewer('run-ro-error')viewer.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-4' })+ // Advance past the inter-attempt backoff so every retry runs and the terminal state lands.+ await jest.advanceTimersByTimeAsync(10_000)await flushPromises()- expect(viewer.values.threadItems.some((item) => item.type === 'error')).toEqual(true)+ expect(getLogEntriesSpy).toHaveBeenCalledTimes(MAX_HISTORY_FETCH_ATTEMPTS)+ // The failure drives the footer banner via `runConnectionState`, not a spammy inline error item.+ expect(viewer.values.runConnectionState?.kind).toEqual('connection_failed')+ expect(viewer.values.threadItems.some((item) => item.type === 'error')).toEqual(false)expect(MockStream.connections.length).toEqual(0)expect(viewer.values.bootstrapLoading).toEqual(false)+ jest.useRealTimers()viewer.unmount()})@@ -2600,7 +2611,7 @@ describe('runStreamLogic', () => {})describe('stream-disconnect telemetry', () => {- it('captures sandbox_stream_disconnected with attempt counters and pushes a visible error item', async () => {+ it('captures sandbox_stream_disconnected and surfaces the banner without spamming error items', async () => {jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)@@ -2627,21 +2638,40 @@ describe('runStreamLogic', () => {execution_type: 'sandbox',}))- expect(logic.values.threadItems.some((item) => item.type === 'error')).toEqual(true)+ // The failure surfaces via the single footer banner, NOT an appended inline error item (the+ // old behavior stacked a fresh red bubble on every drop — the spam this change removes).+ expect(logic.values.runConnectionState?.kind).toEqual('connection_failed')+ expect(logic.values.threadItems.some((item) => item.type === 'error')).toEqual(false)})- it('reports was_bootstrapping=true when the snapshot fails before the agent starts', async () => {+ it('projects the reconnect attempt counter into runConnectionState for the footer banner', () => {+ logic.actions.sseReconnecting(3)+ expect(logic.values.runConnectionState).toEqual({+ kind: 'reconnecting',+ attempt: 3,+ maxAttempts: MAX_SSE_RECONNECT_ATTEMPTS,+ })+ })++ it('retries the snapshot before teardown and reports was_bootstrapping=true on exhaustion', async () => {const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)- jest.spyOn(api.tasks.runs, 'getLogEntries').mockRejectedValue({ status: 500 })+ const getLogEntriesSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockRejectedValue({ status: 500 })+ jest.useFakeTimers()logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ // The snapshot is retried before the live stream is torn down; advance past the backoff.+ await jest.advanceTimersByTimeAsync(10_000)await flushPromises()+ // A transient history blip must not tear down on the first failure — only exhausting the retries does.+ expect(getLogEntriesSpy).toHaveBeenCalledTimes(MAX_HISTORY_FETCH_ATTEMPTS)// The history fetch failed during bootstrap and no `_posthog/run_started` ever arrived, so// the provisioning flag is still set even though the SSE briefly opened (connect-first).const disconnect = captureSpy.mock.calls.find((c) => c[0] === 'sandbox_stream_disconnected')expect(disconnect?.[1]).toEqual(expect.objectContaining({ was_bootstrapping: true }))++ jest.useRealTimers()})})@@ -3114,6 +3144,17 @@ describe('runStreamLogic', () => {})})+ it('never mints a token or sets a proxy target when the rollout is off', async () => {+ // The flag is off by default here. Opening the stream must take the same-origin Django+ // path (no token mint, no proxy target) — guards against re-adding a debug/non-flag force+ // that would break flag-off streaming (the reported local bug).+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()++ expect(tasksRunsStreamTokenRetrieve).not.toHaveBeenCalled()+ expect(MockStream.latest().options.proxyTarget).toBeUndefined()+ })+it('re-mints the read token and retries once on a 401 from the proxy leg', async () => {enableProxy();(tasksRunsStreamTokenRetrieve as jest.Mock).mockResolvedValue({diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex 18541b60cdff..1b35d17bc7df 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -1,5 +1,5 @@import { type EventSourceMessage, createParser } from 'eventsource-parser'-import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { type BreakPointFunction, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import posthog from 'posthog-js'import api from 'lib/api'@@ -23,6 +23,7 @@ import type {RunArtifacts,ProgressStatus,ProgressStep,+ RunConnectionState,SdkSession,ThreadItem,ThreadItemType,@@ -70,9 +71,19 @@ export interface RunStreamLogicProps {}/** Reconnect/backoff constants for the SSE drop-recovery loop. */-export const MAX_SSE_RECONNECT_ATTEMPTS = 5+export const MAX_SSE_RECONNECT_ATTEMPTS = 10export const SSE_RECONNECT_BASE_DELAY_MS = 2_000export const SSE_RECONNECT_MAX_DELAY_MS = 30_000+/**+ * Retries for the one-shot `logs/` history snapshot fetch. A transient blip here must not tear down an+ * otherwise-healthy live SSE (which is connected first); only exhausting these attempts does.+ */+export const MAX_HISTORY_FETCH_ATTEMPTS = 3+/**+ * Re-mint budget for the proxy read token on a 401 handshake — kept separate from the reconnect budget so+ * bumping reconnects to 10 doesn't balloon the number of token re-mints per open.+ */+export const MAX_STREAM_TOKEN_REMINTS = 5/*** Cumulative cap across all drops in a run — bounds runaway clean-EOF loops that keep dodging the* per-drop counter (a connection that opens, immediately drops, and reopens resets `reconnectAttempt`@@ -374,6 +385,30 @@ export function foldUsageAggregate(existing: ContextUsage | null, update: Sessioreturn next}+/**+ * Fetch the run's `logs/` snapshot, retrying transient failures with capped backoff (§case 5). Returns the+ * raw entries on success, or `{ historyError }` once the attempts are exhausted — a sentinel object, not a+ * throw, so the caller's teardown branch is driven by an ordinary check and a kea `breakpoint(ms)` delay+ * (which throws to cancel a superseded bootstrap) propagates through untouched.+ */+async function fetchLogEntriesWithRetry(+ taskId: string,+ runId: string,+ breakpoint: BreakPointFunction+): Promise<unknown[] | { historyError: unknown }> {+ for (let attempt = 1; ; attempt++) {+ try {+ return await api.tasks.runs.getLogEntries(taskId, runId)+ } catch (error) {+ if (attempt >= MAX_HISTORY_FETCH_ATTEMPTS) {+ return { historyError: error }+ }+ }+ // Outside the try so a supersession cancel (breakpoint throw) is never mistaken for a fetch failure.+ await breakpoint(reconnectDelayMs(attempt))+ }+}+/** Refetch the run's status (plus any git artifacts it now exposes); on failure return the mapped error envelope. */async function fetchRunStatus(taskId: string,@@ -1079,7 +1114,7 @@ export const runStreamLogic = kea<runStreamLogicType>([featureFlagLogic,['featureFlags'],preflightLogic,- ['preflight', 'isDev'],+ ['isDev'],userLogic,['user'],],@@ -1198,6 +1233,15 @@ export const runStreamLogic = kea<runStreamLogicType>([markTurnComplete: true,/** Echoes the user's own message into the thread as a `client`-sourced log entry (the wire never replays a live turn). */pushHumanMessage: (content: string) => ({ content }),+ /**+ * Open a run optimistically before its real id exists: flips the thread to the provisioning+ * indicator and, when a first message is given, renders it immediately as the human bubble. The+ * composable seam for an optimistic-create UI — mount a surface keyed by a client `streamKey`,+ * call this on send, then attach the real run (`bootstrapRun({ justCreatedRun: true })`) once+ * created; the live SSE echo dedups the seeded message. Pure composition of `setRunOpening` ++ * `pushHumanMessage`.+ */+ startOptimisticRun: (message?: string) => ({ message }),/** 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 }),/** Union the products an answer was grounded in — accumulates across the whole session. */@@ -1307,6 +1351,26 @@ export const runStreamLogic = kea<runStreamLogicType>([reset: () => false,},],+ // The run id this instance last bootstrapped, so the surface can adopt an already-bootstrapped+ // instance (the optimistic-create handoff) instead of resetting and re-bootstrapping it. Logic-+ // resident (not a per-component ref) so the decision survives the create-thread → detail swap.+ bootstrappedRunId: [+ null as string | null,+ {+ bootstrapRun: (_, { runId }) => runId,+ reset: () => null,+ },+ ],+ // True between an optimistic seed (`startOptimisticRun`) and its attach (`bootstrapRun`): the+ // surface uses it to take the seed-preserving fast path when the real run id arrives.+ awaitingOptimisticAttach: [+ false,+ {+ startOptimisticRun: () => true,+ bootstrapRun: () => false,+ reset: () => false,+ },+ ],// Live-mode bootstrapping remains true after the SSE opens and only clears once the// historical log snapshot has been replayed. Fresh runs explicitly skip history.logBootstrapLoading: [@@ -1618,14 +1682,44 @@ export const runStreamLogic = kea<runStreamLogicType>([],/*** Gates routing the live stream through the standalone agent-proxy (the durable-streaming- * rollout). Local dev disables the analytics SDK, so DEBUG instances opt in unconditionally —- * the server still owns the final proxy-vs-Django decision via `stream_token` (no base URL- * ⇒ Django), so opting in here is safe even where the proxy isn't deployed.+ * rollout). Purely flag-driven: off ⇒ stream directly from Django and never mint a+ * `stream_token`; on ⇒ resolve a proxy target. The server still owns the final+ * proxy-vs-Django decision via `stream_token` (no base URL ⇒ Django), so a flag-on client+ * where the proxy isn't deployed falls back safely. Frontend flags evaluate in local dev, so+ * a dev exercises the proxy by enabling `tasks-stream-via-proxy` for their user.*/streamViaProxyEnabled: [- (s) => [s.featureFlags, s.preflight],- (featureFlags, preflight): boolean =>- !!featureFlags[FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY] || !!preflight?.is_debug,+ (s) => [s.featureFlags],+ (featureFlags): boolean => !!featureFlags[FEATURE_FLAGS.TASKS_STREAM_VIA_PROXY],+ ],+ /**+ * The live connection banner view-model (footer `RunAlertActivity`), or null when the connection is+ * healthy. `reconnecting` drives the attempt-counter card during the backoff loop; `connection_failed`+ * is its terminal state (retries/cumulative exhausted, a non-retryable open, or a bootstrap-fetch+ * failure — including read-only replay, which surfaces via `sseStatus='error'`). A terminal run's own+ * failure/crash is an inline `error` item, not a banner, so it's excluded here.+ */+ runConnectionState: [+ (s, p) => [s.sseStatus, s.reconnectAttempt, s.bootstrapError, s.currentRunStatus, p.replayOnly!],+ (sseStatus, reconnectAttempt, bootstrapError, currentRunStatus, replayOnly): RunConnectionState | null => {+ if (isTerminalRunStatus(currentRunStatus)) {+ return null+ }+ if (!replayOnly && sseStatus === 'reconnecting') {+ return {+ kind: 'reconnecting',+ attempt: reconnectAttempt,+ maxAttempts: MAX_SSE_RECONNECT_ATTEMPTS,+ }+ }+ if (sseStatus === 'error') {+ const detail = bootstrapError+ ? [bootstrapError.errorTitle, bootstrapError.errorMessage].filter(Boolean).join(' — ')+ : undefined+ return { kind: 'connection_failed', message: detail || undefined }+ }+ return null+ },],}),listeners(({ values, actions, cache, props }) => ({@@ -1652,13 +1746,14 @@ export const runStreamLogic = kea<runStreamLogicType>([actions.markBootstrapResumeRun(isResumeRun(replayRun))actions.mergeRunArtifacts(extractRunArtifacts(replayRun))- let replayEntries: unknown[]- try {- replayEntries = await api.tasks.runs.getLogEntries(taskId, runId)- } catch (error) {- actions.handleStreamError(mapHttpStatusToStreamError((error as { status?: number })?.status))+ const replayResult = await fetchLogEntriesWithRetry(taskId, runId, breakpoint)+ if (!Array.isArray(replayResult)) {+ actions.handleStreamError(+ mapHttpStatusToStreamError((replayResult.historyError as { status?: number })?.status)+ )return}+ const replayEntries = replayResultbreakpoint()if (values.log.entries.length === 0) {replayEntries@@ -1723,20 +1818,21 @@ export const runStreamLogic = kea<runStreamLogicType>([actions.openSseForRun({ taskId, runId, startLatest: true })}- let entries: unknown[]- try {- entries = await api.tasks.runs.getLogEntries(taskId, runId)- } catch (error) {- // The snapshot failed; for an in-progress run the SSE is already open, so tear it- // down too — a thread of live-only frames with no history is more confusing than a- // clean, retryable error.+ // Retry the snapshot before giving up (§case 5) — a transient blip shouldn't kill the live SSE.+ const historyResult = await fetchLogEntriesWithRetry(taskId, runId, breakpoint)+ if (!Array.isArray(historyResult)) {+ // Retries exhausted; for an in-progress run the SSE is already open, so tear it down too —+ // a thread of live-only frames with no history is more confusing than a clean, retryable error.cache.bufferingLiveFrames = falsecache.bufferedLiveFrames = undefinedcache.disposables.dispose('reconnect-backoff')cache.disposables.dispose('event-source')- actions.handleStreamError(mapHttpStatusToStreamError((error as { status?: number })?.status))+ actions.handleStreamError(+ mapHttpStatusToStreamError((historyResult.historyError as { status?: number })?.status)+ )return}+ const entries = historyResultbreakpoint()// The full resume-chain S3 snapshot — replayed as `replay`, so the projection renders@@ -1914,11 +2010,7 @@ export const runStreamLogic = kea<runStreamLogicType>([// surfacing an auth error. Bounded so a genuinely revoked user can't loop; on// exhaustion it falls through to the normal drop handling (whose Django fallback// surfaces a real 401 as a retryable error).- if (- status === 401 &&- proxyTarget &&- (cache.streamTokenRefreshes ?? 0) < MAX_SSE_RECONNECT_ATTEMPTS- ) {+ if (status === 401 && proxyTarget && (cache.streamTokenRefreshes ?? 0) < MAX_STREAM_TOKEN_REMINTS) {cache.streamTokenRefreshes = ((cache.streamTokenRefreshes as number | undefined) ?? 0) + 1return streamRun(signal)}@@ -2252,12 +2344,12 @@ export const runStreamLogic = kea<runStreamLogicType>([duration_ms: startedAt !== undefined ? Date.now() - startedAt : undefined,})},- handleStreamError: ({ errorTitle, errorMessage, retryable }) => {- // The composer-unlock is already wired off this action in maxThreadLogic; today it- // unlocks silently. Push a visible, retryable error line so the user knows the stream- // dropped — and capture the disconnect telemetry that mirrors the cloud client's+ handleStreamError: ({ errorTitle, retryable }) => {+ // A stream/connection failure no longer appends an inline error item (which stacked up as+ // spam on a flapping stream). It sets `sseStatus='error'` + the error envelope via the reducers,+ // which the `runConnectionState` selector projects into the single footer `RunAlertActivity`+ // card. Here we only capture the disconnect telemetry that mirrors the cloud client's// CLOUD_STREAM_DISCONNECTED (the relay can't see a client-side reconnect-budget exhaustion).- actions.pushErrorItem(errorMessage ? `${errorTitle}: ${errorMessage}` : errorTitle)const activeRun = cache.activeRun as { taskId: string; runId: string } | undefinedposthog.capture('sandbox_stream_disconnected', {conversation_id: props.conversationId,@@ -2297,6 +2389,12 @@ export const runStreamLogic = kea<runStreamLogicType>([cache.disposables.dispose('reconnect-backoff')cache.disposables.dispose('event-source')},+ startOptimisticRun: ({ message }) => {+ actions.setRunOpening(true)+ if (message) {+ actions.pushHumanMessage(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/logics/taskLogic.ts b/products/posthog_ai/frontend/logics/taskLogic.tsindex 4948b36cbba6..028a9c6362e1 100644--- a/products/posthog_ai/frontend/logics/taskLogic.ts+++ b/products/posthog_ai/frontend/logics/taskLogic.ts@@ -2,8 +2,6 @@ import { kea, key, listeners, path, props, reducers } from 'kea'import { loaders } from 'kea-loaders'import { router } from 'kea-router'-import { lemonToast } from '@posthog/lemon-ui'-import api from 'lib/api'import { isApiNotFound, loadErrorMessage } from '../lib/load-error'@@ -33,20 +31,16 @@ export const taskLogic = kea<taskLogicType>([}},runTask: async () => {- const response = await api.tasks.run(props.taskId)- lemonToast.success('Task run started')- return response+ return await api.tasks.run(props.taskId)},deleteTask: async () => {await api.tasks.delete(props.taskId)- lemonToast.success('Task archived')tasksLogic.findAllMounted().forEach((logic) => logic.actions.loadTasks())router.actions.push('/tasks')return null},updateTask: async ({ data }: { data: TaskUpsertProps }) => {const updatedTask = await api.tasks.update(props.taskId, data)- lemonToast.success('Task updated')tasksLogic.findAllMounted().forEach((logic) => logic.actions.loadTasks())return updatedTask},diff --git a/products/posthog_ai/frontend/logics/tasksLogic.ts b/products/posthog_ai/frontend/logics/tasksLogic.tsindex 7ca588b5aaa2..4efc40f90f62 100644--- a/products/posthog_ai/frontend/logics/tasksLogic.ts+++ b/products/posthog_ai/frontend/logics/tasksLogic.ts@@ -65,7 +65,6 @@ export const tasksLogic = kea<tasksLogicType>([},createTask: async ({ data }: { data: TaskUpsertProps }) => {const newTask = await api.tasks.create(data)- lemonToast.success('Task created successfully')void addProductIntent({product_type: ProductKey.TASKS,intent_context: ProductIntentContext.TASK_CREATED,@@ -74,7 +73,6 @@ export const tasksLogic = kea<tasksLogicType>([},deleteTask: async ({ taskId }: { taskId: string }) => {await api.tasks.delete(taskId)- lemonToast.success('Task deleted')return values.tasks.filter((t) => t.id !== taskId)},},diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.tsxindex a094d7b7a241..301124e18896 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.tsx@@ -1,3 +1,5 @@+import { useValues } from 'kea'+import { AllowTrainingCallout } from 'lib/components/AllowTrainingCallout/AllowTrainingCallout'import { useWindowSize } from 'lib/hooks/useWindowSize'import { sceneConfigurations } from 'scenes/scenes'@@ -10,6 +12,7 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'import { TaskComposer } from './components/TaskComposer'+import { TaskCreateThread } from './components/TaskCreateThread'import { TaskDetailPage } from './components/TaskDetailPage'import { TasksListColumn } from './components/TasksListColumn'import { taskTrackerSceneLogic } from './taskTrackerSceneLogic'@@ -29,10 +32,18 @@ export const scene: SceneExport<TaskTrackerProps> = {export function TaskTracker({ taskId }: TaskTrackerProps): JSX.Element {const { isWindowLessThan } = useWindowSize()const isMobile = isWindowLessThan('lg')+ const { activeCreation } = useValues(taskTrackerSceneLogic)const selectedTaskId = taskId && taskId !== 'new' ? taskId : null- const rightPane = selectedTaskId ? <TaskDetailPage taskId={selectedTaskId} isMobile={false} /> : <TaskComposer />+ // While an optimistic create is in flight (and no task is selected), the thread opens immediately in place+ // of the composer — see `taskTrackerSceneLogic.submit`.+ const composerPane = activeCreation ? (+ <TaskCreateThread streamKey={activeCreation.streamKey} isMobile={isMobile} />+ ) : (+ <TaskComposer />+ )+ const rightPane = selectedTaskId ? <TaskDetailPage taskId={selectedTaskId} isMobile={false} /> : composerPaneif (isMobile) {// Single column: detail, composer, or the list (with a "Create a new task" row).@@ -47,6 +58,19 @@ export function TaskTracker({ taskId }: TaskTrackerProps): JSX.Element {)}if (taskId === 'new') {+ // Optimistic create renders the same scene shell as the detail page (which carries its own+ // SceneContent + back button), so wrap it like the detail branch — not the composer's+ // SceneContent — to keep the create → detail handoff seamless and avoid nesting SceneContent.+ if (activeCreation) {+ return (+ <div className="flex flex-col h-full min-h-0">+ <AllowTrainingCallout featureName="Tasks" />+ <div className="flex flex-1 min-h-0 flex-col overflow-hidden">+ <TaskCreateThread streamKey={activeCreation.streamKey} isMobile />+ </div>+ </div>+ )+ }return (<SceneContent className="h-full"><SceneBreadcrumbBackButtondiff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.test.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.test.tsxnew file mode 100644index 000000000000..8b1922e9b2e8--- /dev/null+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.test.tsx@@ -0,0 +1,69 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++// Stub the Quill-based pickers: this test is about which branch control RepositorySelector renders for a+// given repo-list load state, not the pickers' internals. Stubbing also keeps githubBranchSearchLogic and+// the branches request out of the test.+jest.mock('lib/integrations/GitHubRepositoryCombobox', () => ({+ GitHubRepositoryCombobox: () => <div data-attr="repo-combobox" />,+}))+jest.mock('lib/integrations/GitHubBranchCombobox', () => ({+ GitHubBranchCombobox: () => <div data-attr="branch-combobox" />,+}))++describe('RepositorySelector', () => {+ // Imported lazily (after initKeaTests sets the current team) because the module builds a team-scoped+ // authorize URL at import time.+ let RepositorySelector: (typeof import('./RepositorySelector'))['RepositorySelector']+ let releaseRepos: () => void++ beforeEach(async () => {+ const reposLoaded = new Promise<void>((resolve) => {+ releaseRepos = resolve+ })+ useMocks({+ get: {+ '/api/environments/:team/integrations/': {+ results: [{ id: 7, kind: 'github', display_name: 'acme', config: {} }],+ },+ // Gate the repo list so the loading → loaded transition is deterministic.+ '/api/environments/:team/integrations/7/github_repos/': async () => {+ await reposLoaded+ return [+ 200,+ { repositories: [{ id: 1, name: 'widgets', full_name: 'acme/widgets' }], has_more: false },+ ]+ },+ },+ })+ initKeaTests()+ ;({ RepositorySelector } = await import('./RepositorySelector'))+ })++ afterEach(() => {+ // Let the gated request settle so it can't leak into the next test.+ releaseRepos()+ cleanup()+ })++ // On load a persisted repo is restored before its integration's repo list has fetched. The branch picker+ // must stay the disabled "Branch" button while the repos load, and only become interactive once they have.+ // Guards against reverting the `!repositoriesLoading` gate (which left the branch picker active mid-load).+ it('keeps the branch picker disabled until the repository list has loaded', async () => {+ render(<RepositorySelector value={{ integrationId: 7, repository: 'acme/widgets' }} onChange={jest.fn()} />)++ // Repo list still loading: the disabled fallback shows, not the interactive branch combobox.+ // (Quill's Button marks itself non-interactive with aria-disabled, not the native disabled attribute.)+ expect(await screen.findByRole('button', { name: 'Branch' })).toHaveAttribute('aria-disabled', 'true')+ expect(screen.queryByTestId('branch-combobox')).not.toBeInTheDocument()++ // Repo list loaded: the interactive branch combobox replaces the fallback.+ releaseRepos()+ expect(await screen.findByTestId('branch-combobox')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Branch' })).not.toBeInTheDocument()+ })+})diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.tsxindex c6697ebe3d59..9defe1fa2476 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/RepositorySelector.tsx@@ -7,6 +7,7 @@ import { Button, ButtonGroup } from '@posthog/quill-primitives'import api from 'lib/api'import { GitHubBranchCombobox } from 'lib/integrations/GitHubBranchCombobox'import { GitHubRepositoryCombobox } from 'lib/integrations/GitHubRepositoryCombobox'+import { githubRepositorySearchLogic } from 'lib/integrations/githubRepositorySearchLogic'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { urls } from 'scenes/urls'@@ -103,29 +104,61 @@ export function RepositorySelector({ value, onChange }: RepositorySelectorProps))}{value.integrationId ? (- <ButtonGroup>- <GitHubRepositoryCombobox- integrationId={value.integrationId}- value={value.repository ?? ''}- onChange={handleRepositoryChange}- placeholder="No repo"- showNoneOption- />- {value.repository ? (- <GitHubBranchCombobox- integrationId={value.integrationId}- repo={value.repository}- value={value.branch ?? ''}- onChange={handleBranchChange}- />- ) : (- <Button variant="outline" size="sm" disabled aria-label="Branch">- <IconGitBranch className="shrink-0" />- Branch- </Button>- )}- </ButtonGroup>+ <RepositoryBranchPickers+ integrationId={value.integrationId}+ value={value}+ onRepositoryChange={handleRepositoryChange}+ onBranchChange={handleBranchChange}+ />) : null}</div>)}++interface RepositoryBranchPickersProps {+ integrationId: number+ value: RepositoryConfig+ onRepositoryChange: (repository: string | null) => void+ onBranchChange: (branch: string | null) => void+}++/**+ * Joined [repo ▾][branch ▾] group for a chosen integration. The branch picker stays a hard-disabled button+ * until the repository list has loaded AND a repo is selected: on a fresh load a persisted repo is restored+ * before its integration's repo list finishes fetching, and a branch can't be meaningfully picked while the+ * repo picker itself is still in its "Loading repos…" state.+ */+function RepositoryBranchPickers({+ integrationId,+ value,+ onRepositoryChange,+ onBranchChange,+}: RepositoryBranchPickersProps): JSX.Element {+ // Same keyed instance GitHubRepositoryCombobox mounts, so this shares its load state — no extra fetch.+ const { loading: repositoriesLoading } = useValues(githubRepositorySearchLogic({ id: integrationId }))++ return (+ <ButtonGroup>+ <GitHubRepositoryCombobox+ integrationId={integrationId}+ value={value.repository ?? ''}+ onChange={onRepositoryChange}+ placeholder="No repo"+ showNoneOption+ />+ {value.repository && !repositoriesLoading ? (+ <GitHubBranchCombobox+ integrationId={integrationId}+ repo={value.repository}+ value={value.branch ?? ''}+ onChange={onBranchChange}+ />+ ) : (+ <Button variant="outline" size="sm" disabled aria-label="Branch">+ <IconGitBranch className="shrink-0" />+ Branch+ </Button>+ )}+ </ButtonGroup>+ )+}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsxnew file mode 100644index 000000000000..cb04c77e3f1a--- /dev/null+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx@@ -0,0 +1,42 @@+import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'++import { TaskHeaderActionsSkeleton } from './taskDetailSkeletons'+import { TaskRunSceneShell } from './TaskRunSceneShell'++export interface TaskCreateThreadProps {+ /** Client stream key the optimistic `runStreamLogic` was seeded under (see `taskTrackerSceneLogic.submit`). */+ streamKey: string+ /** Mobile composer pane renders this too; forwarded to the shell for the back button. */+ isMobile: boolean+}++/**+ * 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+ * 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+ * detail page, which adopts the same seeded stream so only the continuous thread underneath persists.+ */+export function TaskCreateThread({ streamKey, isMobile }: TaskCreateThreadProps): JSX.Element {+ return (+ <TaskRunSceneShell+ task={null}+ selectedRun={null}+ isHeaderLoading+ titleActions={<TaskHeaderActionsSkeleton />}+ sceneMenuBarEnabled={false}+ onArchive={() => {}}+ taskError={null}+ onRetry={() => {}}+ isMobile={isMobile}+ >+ <div className="@container/thread flex flex-col h-full -mx-4">+ <RunSurface.Root taskId="" runId={null} streamKey={streamKey} interaction="live">+ <RunSurface.Thread className="flex-1 min-h-0" listClassName="py-4" rowClassName="px-4" />+ </RunSurface.Root>+ </div>+ </TaskRunSceneShell>+ )+}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsxindex 3e3dfb1664e3..d82ce2292859 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx@@ -1,36 +1,17 @@import { useActions, useValues } from 'kea'-import { IconArchive, IconExternal, IconGithub, IconPlay } from '@posthog/icons'-import { LemonButton, LemonDivider } from '@posthog/lemon-ui'+import { IconExternal, IconGithub, IconPlay } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'import { NotFound } from 'lib/components/NotFound'-import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'import { FEATURE_FLAGS } from 'lib/constants'-import { dayjs } from 'lib/dayjs'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'-import { urls } from 'scenes/urls'--import { SceneContent } from '~/layout/scenes/components/SceneContent'-import {- SceneMenuBar,- SceneMenuBarItem,- SceneMenuBarMenu,- SceneMenuBarSeparator,-} from '~/layout/scenes/components/SceneMenuBar'-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import {- ScenePanel,- ScenePanelActionsSection,- ScenePanelDivider,- ScenePanelInfoSection,-} from '~/layout/scenes/SceneLayout'import { taskDetailSceneLogic } from '../taskDetailSceneLogic'-import { TaskHeaderActionsSkeleton, TaskPanelSkeleton, TaskRunMetadataSkeleton } from './taskDetailSkeletons'-import { TaskErrorBanner } from './TaskErrorBanner'+import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'+import { TaskHeaderActionsSkeleton } from './taskDetailSkeletons'import { TaskRunLog } from './TaskRunLog'-import { TaskRunMetadata } from './TaskRunMetadata'+import { TaskRunSceneShell } from './TaskRunSceneShell'export interface TaskDetailPageProps {taskId: string@@ -43,6 +24,7 @@ export function TaskDetailPage({ taskId, isMobile }: TaskDetailPageProps): JSX.Econst { task, taskNotFound, taskError, runs, selectedRun, isTaskPending, isHeaderLoading } = useValues(sceneLogic)const { runTask, deleteTask, loadTask } = useActions(sceneLogic)const { featureFlags } = useValues(featureFlagLogic)+ const { activeCreation } = useValues(taskTrackerSceneLogic)const sceneMenuBarEnabled = !!featureFlags[FEATURE_FLAGS.SCENE_MENU_BAR]if (taskNotFound && !task) {@@ -90,111 +72,26 @@ export function TaskDetailPage({ taskId, isMobile }: TaskDetailPageProps): JSX.E</div>)- return (- <SceneContent className="h-full min-h-0 gap-y-0">- {sceneMenuBarEnabled && task && (- <SceneMenuBar>- <SceneMenuBarMenu label="File" dataAttr="task-menubar-file">- <SceneMenuBarFileItems dataAttrKey="task" />- <SceneMenuBarSeparator />- <SceneMenuBarItem variant="destructive" onClick={deleteTask} data-attr="task-menubar-archive">- <IconArchive />- Archive task- </SceneMenuBarItem>- </SceneMenuBarMenu>- </SceneMenuBar>- )}- <ScenePanel>- {isHeaderLoading || !task ? (- <TaskPanelSkeleton />- ) : (- <>- <ScenePanelInfoSection>- <div className="flex flex-col gap-3">- <div>- <div className="text-xs text-muted mb-1">Task ID</div>- <div className="font-mono text-sm">{task.slug}</div>- </div>- <div>- <div className="text-xs text-muted mb-1">Repository</div>- <div className="text-sm">{task.repository}</div>- </div>- <div>- <div className="text-xs text-muted mb-1">Created by</div>- <div className="text-sm">- {task.created_by?.first_name || task.created_by?.email || 'Unknown'}- </div>- </div>- <div>- <div className="text-xs text-muted mb-1">Created</div>- <div className="text-sm">{dayjs(task.created_at).format('MMM D, YYYY HH:mm')}</div>- </div>- </div>- </ScenePanelInfoSection>-- <ScenePanelDivider />-- <ScenePanelActionsSection>- <ButtonPrimitive menuItem variant="danger" onClick={deleteTask}>- <IconArchive />- Archive task- </ButtonPrimitive>- </ScenePanelActionsSection>- </>- )}- </ScenePanel>-- {taskError && !task ? (- <TaskErrorBanner- title="We couldn't load this task."- message={taskError}- onRetry={loadTask}- dataAttr="task-load-error"- className="max-w-200"- />- ) : (- <>- {taskError && (- <TaskErrorBanner- title="We couldn't load this task."- message={taskError}- onRetry={loadTask}- dataAttr="task-load-error"- className="max-w-200"- />- )}-- <header className="flex flex-col gap-y-2 mt-4">- <SceneTitleSection- name={task?.title || 'Task'}- description={null}- resourceType={{ type: 'task' }}- isLoading={isHeaderLoading}- canEdit={false}- forceBackTo={- isMobile- ? {- key: 'tasks',- name: 'Tasks',- path: urls.taskTracker(),- }- : undefined- }- actions={titleActions}- />-- {isHeaderLoading ? (- <TaskRunMetadataSkeleton />- ) : (- selectedRun && <TaskRunMetadata selectedRun={selectedRun} />- )}+ // 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 === taskId+ const optimisticStreamKey = isActiveCreation ? activeCreation?.streamKey : undefined+ const optimisticRunId = isActiveCreation ? activeCreation?.runId : undefined- <LemonDivider className="hidden lg:block mb-0 mt-2" />- </header>-- <TaskRunLog taskId={taskId} />- </>- )}- </SceneContent>+ return (+ <TaskRunSceneShell+ task={task}+ selectedRun={selectedRun}+ isHeaderLoading={isHeaderLoading}+ titleActions={titleActions}+ sceneMenuBarEnabled={sceneMenuBarEnabled}+ onArchive={deleteTask}+ taskError={taskError}+ onRetry={loadTask}+ isMobile={isMobile}+ >+ <TaskRunLog taskId={taskId} optimisticStreamKey={optimisticStreamKey} optimisticRunId={optimisticRunId} />+ </TaskRunSceneShell>)}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsxindex c553b7f7037d..79a45f6cd45a 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx@@ -13,6 +13,12 @@ import { ComposerModelEffortPickers } from './ComposerModelEffortPickers'export interface TaskRunChatProps {taskId: stringrunId: string+ /**+ * Override for the bound run-stream key. Defaults to `runId`; set to an optimistic-create client+ * `streamKey` so this surface adopts that already-seeded/streaming instance instead of bootstrapping a+ * fresh one. Passed to both `RunSurface.Root` and `runInteractionLogic` so they never diverge.+ */+ streamKey?: string}/**@@ -23,12 +29,13 @@ export interface TaskRunChatProps {* re-points scene selection to it. `RunSurface.Root` owns bootstrap: it reads the run status from the tasks* API and never opens SSE for an already-terminal run.*/-export function TaskRunChat({ taskId, runId }: TaskRunChatProps): JSX.Element {+export function TaskRunChat({ taskId, runId, streamKey }: TaskRunChatProps): JSX.Element {const { setSelectedRunId, loadTaskRuns } = useActions(taskDetailSceneLogic({ taskId }))const { selectedRun } = useValues(taskDetailSceneLogic({ taskId }))const logicProps: RunInteractionLogicProps = {taskId,runId,+ streamKey,currentModel: selectedRun?.state?.model,currentEffort: selectedRun?.state?.reasoning_effort,onRunStarted: (newRunId) => {@@ -45,16 +52,29 @@ export function TaskRunChat({ taskId, runId }: TaskRunChatProps): JSX.Element {}function TaskRunChatContent({ logicProps }: { logicProps: RunInteractionLogicProps }): JSX.Element {- const { composerForm, isSubmitting, queuedMessages, isTerminal, selectedModel, selectedEffort } = useValues(+ const { composerForm, isSubmitting, isBusy, queuedMessages, isTerminal, selectedModel, selectedEffort } = useValues(runInteractionLogic(logicProps))- const { setComposerFormValues, submitComposerForm, updateQueuedMessage, removeQueuedMessage, setModel, setEffort } =- useActions(runInteractionLogic(logicProps))+ const {+ setComposerFormValues,+ submitComposerForm,+ cancelRun,+ updateQueuedMessage,+ removeQueuedMessage,+ setModel,+ setEffort,+ } = useActions(runInteractionLogic(logicProps))return (- // `RunSurface.Root` binds `runStreamLogic` keyed by `runId`; `runInteractionLogic` connects to the same- // key, so the composer slot's gating reads the right stream. Don't introduce a diverging `streamKey`.- <RunSurface.Root taskId={logicProps.taskId} runId={logicProps.runId} interaction="live">+ // `RunSurface.Root` and `runInteractionLogic` deliberately share the same stream key (`streamKey ?? runId`,+ // resolved inside each): the composer slot's gating must read the exact stream the thread renders. The+ // optional `streamKey` lets both adopt an optimistic-create instance — keep them aligned, never diverging.+ <RunSurface.Root+ taskId={logicProps.taskId}+ runId={logicProps.runId}+ streamKey={logicProps.streamKey}+ interaction="live"+ ><div className="@container/thread flex flex-col h-full -mx-4"><RunSurface.Thread className="flex-1 min-h-0" listClassName="py-4" rowClassName="px-4" /><RunSurface.Composer>@@ -64,6 +84,8 @@ function TaskRunChatContent({ logicProps }: { logicProps: RunInteractionLogicProonChange={(value) => setComposerFormValues({ draft: value })}onSubmit={submitComposerForm}loading={isSubmitting}+ isTurnActive={isBusy}+ onStop={() => cancelRun()}>{queuedMessages.length > 0 && (<Composer.Banner>diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsxindex 1f86c94ea5c3..29002d031304 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsx@@ -14,12 +14,34 @@ import { TaskRunChat } from './TaskRunChat'* `TaskRunChat`. The skeleton is the only loading affordance here — once it hands off to `TaskRunChat`, the* eager `RunSurface` shows the same `RunLogSkeleton` during its own bootstrap, so the transition is seamless.*/-export function TaskRunLog({ taskId }: { taskId: string }): JSX.Element | null {+export function TaskRunLog({+ taskId,+ optimisticStreamKey,+ optimisticRunId,+}: {+ taskId: string+ /** Client `streamKey` of an optimistic-create stream to adopt — set only during the create handoff. */+ optimisticStreamKey?: string+ /** Run id created by the optimistic flow, before the runs list has loaded it. */+ optimisticRunId?: string+}): JSX.Element | null {const logic = taskDetailSceneLogic({ taskId })const { runs, selectedRun, selectedRunId, runsError, selectedRunError, selectedRunNotFound, isRunPending } =useValues(logic)const { loadTaskRuns, loadSelectedTaskRun } = useActions(logic)+ // 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 run+ // up front, then `selectedRunId` once the runs list resolves it (same id), then any later new run.+ const effectiveRunId = selectedRunId ?? optimisticRunId+ if (optimisticStreamKey && effectiveRunId) {+ return (+ <div className="flex-1 min-h-0">+ <TaskRunChat taskId={taskId} runId={effectiveRunId} streamKey={optimisticStreamKey} />+ </div>+ )+ }+if (runsError) {return (<TaskErrorBannerdiff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsxnew file mode 100644index 000000000000..5429ee5ba6d7--- /dev/null+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx@@ -0,0 +1,175 @@+import { type ReactNode } from 'react'++import { IconArchive } from '@posthog/icons'+import { LemonDivider } from '@posthog/lemon-ui'++import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'+import { dayjs } from 'lib/dayjs'+import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import {+ SceneMenuBar,+ SceneMenuBarItem,+ SceneMenuBarMenu,+ SceneMenuBarSeparator,+} from '~/layout/scenes/components/SceneMenuBar'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import {+ ScenePanel,+ ScenePanelActionsSection,+ ScenePanelDivider,+ ScenePanelInfoSection,+} from '~/layout/scenes/SceneLayout'++import { Task, TaskRun } from '../../../types/taskTypes'+import { TaskPanelSkeleton, TaskRunMetadataSkeleton } from './taskDetailSkeletons'+import { TaskErrorBanner } from './TaskErrorBanner'+import { TaskRunMetadata } from './TaskRunMetadata'++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+ /** Drives the title/panel/metadata skeletons — the single unified loading affordance for the header. */+ isHeaderLoading: boolean+ /** Title-bar action buttons (or their skeleton). Supplied by the caller so the shell stays presentational. */+ titleActions: JSX.Element+ sceneMenuBarEnabled: boolean+ onArchive: () => void+ taskError: string | null+ onRetry: () => void+ /** Mobile shows the single-column layout, where the title needs a back button to return to the list. */+ isMobile: boolean+ /** The run-log slot (the streamed thread). */+ children: ReactNode+}++/**+ * 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.+ */+export function TaskRunSceneShell({+ task,+ selectedRun,+ isHeaderLoading,+ titleActions,+ sceneMenuBarEnabled,+ onArchive,+ taskError,+ onRetry,+ isMobile,+ children,+}: TaskRunSceneShellProps): JSX.Element {+ return (+ <SceneContent className="h-full min-h-0 gap-y-0">+ {sceneMenuBarEnabled && task && (+ <SceneMenuBar>+ <SceneMenuBarMenu label="File" dataAttr="task-menubar-file">+ <SceneMenuBarFileItems dataAttrKey="task" />+ <SceneMenuBarSeparator />+ <SceneMenuBarItem variant="destructive" onClick={onArchive} data-attr="task-menubar-archive">+ <IconArchive />+ Archive task+ </SceneMenuBarItem>+ </SceneMenuBarMenu>+ </SceneMenuBar>+ )}+ <ScenePanel>+ {isHeaderLoading || !task ? (+ <TaskPanelSkeleton />+ ) : (+ <>+ <ScenePanelInfoSection>+ <div className="flex flex-col gap-3">+ <div>+ <div className="text-xs text-muted mb-1">Task ID</div>+ <div className="font-mono text-sm">{task.slug}</div>+ </div>+ <div>+ <div className="text-xs text-muted mb-1">Repository</div>+ <div className="text-sm">{task.repository}</div>+ </div>+ <div>+ <div className="text-xs text-muted mb-1">Created by</div>+ <div className="text-sm">+ {task.created_by?.first_name || task.created_by?.email || 'Unknown'}+ </div>+ </div>+ <div>+ <div className="text-xs text-muted mb-1">Created</div>+ <div className="text-sm">{dayjs(task.created_at).format('MMM D, YYYY HH:mm')}</div>+ </div>+ </div>+ </ScenePanelInfoSection>++ <ScenePanelDivider />++ <ScenePanelActionsSection>+ <ButtonPrimitive menuItem variant="danger" onClick={onArchive}>+ <IconArchive />+ Archive task+ </ButtonPrimitive>+ </ScenePanelActionsSection>+ </>+ )}+ </ScenePanel>++ {taskError && !task ? (+ <TaskErrorBanner+ title="We couldn't load this task."+ message={taskError}+ onRetry={onRetry}+ dataAttr="task-load-error"+ className="max-w-200"+ />+ ) : (+ <>+ {taskError && (+ <TaskErrorBanner+ title="We couldn't load this task."+ message={taskError}+ onRetry={onRetry}+ dataAttr="task-load-error"+ className="max-w-200"+ />+ )}++ <header className="flex flex-col gap-y-2 mt-4">+ <SceneTitleSection+ name={task?.title || 'Task'}+ description={null}+ resourceType={{ type: 'task' }}+ isLoading={isHeaderLoading}+ canEdit={false}+ forceBackTo={+ isMobile+ ? {+ key: 'tasks',+ name: 'Tasks',+ path: urls.taskTracker(),+ }+ : undefined+ }+ actions={titleActions}+ />++ {isHeaderLoading ? (+ <TaskRunMetadataSkeleton />+ ) : (+ selectedRun && <TaskRunMetadata selectedRun={selectedRun} />+ )}++ <LemonDivider className="hidden lg:block mb-0 mt-2" />+ </header>++ {children}+ </>+ )}+ </SceneContent>+ )+}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.tsindex 9e64cb0b44c7..ed79dfc8aee8 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.test.ts@@ -85,9 +85,9 @@ describe('taskDetailSceneLogic', () => {// mounts the common logics, so clear before init or flags enabled in one test leak into// the next.window.localStorage.clear()- // preflightLogic prefers the app context over fetching, and the default test fixture has- // is_debug: true, which would force streamViaProxyEnabled on. Pin it to false so the- // feature flag alone drives the rollout-gated behavior in these tests.+ // streamViaProxyEnabled is now purely flag-driven, so preflight no longer affects it. The+ // default test fixture has is_debug: true; pin it to false to keep the app context minimal+ // and unsurprising for these tests.window.POSTHOG_APP_CONTEXT = { preflight: { is_debug: false } } as unknown as typeof window.POSTHOG_APP_CONTEXTinitKeaTests()global.fetch = createFetchMock()diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.tsindex 83f4ae240c2d..850fecc0e069 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts@@ -10,31 +10,30 @@ import { taskTrackerSceneLogic } from './taskTrackerSceneLogic'describe('taskTrackerSceneLogic', () => {let logic: ReturnType<typeof taskTrackerSceneLogic.build>let createBody: Record<string, any> | null- let runCalled: boolean+ let runBody: Record<string, any> | nullbeforeEach(() => {createBody = null- runCalled = false+ runBody = nulluseMocks({get: {'/api/projects/:team/tasks/': { results: [], count: 0 },'/api/projects/:team/tasks/repositories/': { repositories: [] },- '/api/projects/:team/integrations/': { results: [] },+ '/api/environments/:team/integrations/': { results: [] },},post: {'/api/projects/:team/tasks/': async ({ request }) => {createBody = (await request.json()) as Record<string, any>return [200, { id: 'new-task', ...createBody }]},- '/api/projects/:team/tasks/:id/run/': () => {- runCalled = true+ '/api/projects/:team/tasks/:id/run/': async ({ request }) => {+ runBody = (await request.json()) as Record<string, any>return [200, { id: 'new-task' }]},},})initKeaTests()logic = taskTrackerSceneLogic()- logic.mount()})afterEach(() => {@@ -44,6 +43,7 @@ describe('taskTrackerSceneLogic', () => {// 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 () => {+ logic.mount()logic.actions.setNewTaskData({ description: 'do the thing' })logic.actions.submitNewTask()@@ -55,7 +55,36 @@ describe('taskTrackerSceneLogic', () => {repository: null,github_integration: null,})- expect(runCalled).toBe(true)+ // Interactive so the sandbox event stream survives across turns (follow-ups stream), and the+ // typed message is seeded as turn 1 (interactive runs boot with the agent pulling it from run+ // state). Dropping either regresses follow-up streaming / loses the first prompt.+ expect(runBody).toMatchObject({+ mode: 'interactive',+ pending_user_message: 'do the thing',+ })expect(router.values.location.pathname).toContain('/tasks/new-task')})++ // The repo picker only renders once `repositoryConfig.integrationId` is set (auto-selected from the+ // connected GitHub org). Submitting resets the form, wiping that id; without re-deriving it the picker+ // stays blank for every subsequent new task. Guards that the auto-select is restored after a submit.+ it('restores the repository integration after a submit so the picker reappears', async () => {+ useMocks({+ get: {+ '/api/environments/:team/integrations/': {+ results: [{ id: 7, kind: 'github', display_name: 'acme/widgets', config: {} }],+ },+ },+ })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ // Auto-selected on mount once the integration list loads — the picker is showing.+ expect(logic.values.newTaskData.repositoryConfig.integrationId).toBe(7)++ logic.actions.setNewTaskData({ description: 'ship it' })+ logic.actions.submitNewTask()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.newTaskData.repositoryConfig.integrationId).toBe(7)+ })})diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex 20f9afaf06af..86054b19bcae 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -1,13 +1,19 @@import { actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'-import { router } from 'kea-router'+import { router, urlToAction } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { uuid } from 'lib/utils/dom'-import { ClaudeRuntimeAdapterEnumApi, ReasoningEffortEnumApi } from 'products/tasks/frontend/generated/api.schemas'+import {+ ClaudeRuntimeAdapterEnumApi,+ ReasoningEffortEnumApi,+ TaskExecutionModeEnumApi,+} from 'products/tasks/frontend/generated/api.schemas'+import { runStreamLogic } from '../../api/logics'import type { SuggestionGroup, SuggestionItem } from '../../api/primitives'import { DEFAULT_HEADLINES, pickHeadline } from '../../api/primitives'import { tasksLogic } from '../../logics/tasksLogic'@@ -27,6 +33,15 @@ export interface TaskCreateForm {// want the branch picker to re-derive the repo's actual default branch (from the GitHub API), not pin a stale one.export type PersistedRepositoryConfig = Pick<RepositoryConfig, 'integrationId' | 'repository'>+// The optimistic run opened on send, before the task/run exist. `streamKey` is the client key the pending+// `RunSurface` (and its seeded `runStreamLogic`) bind to; `taskId`/`runId` are filled once known (reserved+// for a future zero-flash in-place handoff — today the scene navigates to the detail page once the run exists).+export interface ActiveCreation {+ streamKey: string+ taskId?: string+ runId?: string+}+const LAST_REPOSITORY_CONFIG_STORAGE_KEY = 'posthog_ai.tasks.lastRepositoryConfig'const EMPTY_TASK_FORM: TaskCreateForm = {@@ -63,6 +78,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([applySuggestion: (item: SuggestionItem) => ({ item }),setHeadline: (headline: string) => ({ headline }),setPersistedRepositoryConfig: (config: PersistedRepositoryConfig) => ({ config }),+ setActiveCreation: (creation: ActiveCreation) => ({ creation }),+ clearActiveCreation: true,}),reducers({@@ -105,6 +122,15 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([setHeadline: (_, { headline }) => headline,},],+ // The in-flight optimistic create. While set (and no task is selected) the scene shows the pending+ // run thread instead of the composer.+ activeCreation: [+ null as ActiveCreation | null,+ {+ setActiveCreation: (_, { creation }) => creation,+ clearActiveCreation: () => null,+ },+ ],}),selectors({@@ -115,7 +141,19 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([],}),- listeners(({ actions, values }) => ({+ listeners(({ actions, values, cache }) => ({+ // Release the manually-mounted optimistic stream once the create resolves (navigated to the real run)+ // or fails (returned to the composer), so the throwaway draft instance never leaks.+ clearActiveCreation: () => {+ cache.activeCreationUnmount?.()+ cache.activeCreationUnmount = undefined+ },+ // Resetting the form (after a successful submit) wipes the repo selection; immediately re-derive it+ // (last persisted pick, else the first connected GitHub org) so the composer comes back with the+ // picker populated rather than blank.+ resetNewTaskData: () => {+ actions.maybeAutoSelectIntegration()+ },// Remember the repo/integration whenever the picker changes it to a real selection. Clearing the// repo ("No repo" option) is intentionally NOT persisted so the next visit restores the last good pick.setNewTaskData: ({ data }) => {@@ -168,6 +206,19 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([return}+ // Optimistically open the thread on send: a `runStreamLogic` keyed by a client `streamKey`, seeded+ // with the typed message + provisioning indicator, rendered by the pending `RunSurface` (the+ // composable optimistic-open primitive). Hold a manual mount so the seed is in place when the pending+ // pane renders, and survives across the React swap into the detail page (which adopts the same+ // instance by binding this `streamKey`). Released by `clearActiveCreation` (failure / leaving the run).+ cache.activeCreationUnmount?.()+ cache.activeCreationUnmount = undefined+ const streamKey = `draft-${uuid()}`+ const stream = runStreamLogic({ streamKey })+ cache.activeCreationUnmount = stream.mount()+ actions.setActiveCreation({ streamKey })+ stream.actions.startOptimisticRun(description)+try {const taskData: TaskUpsertProps = {title: '',@@ -179,17 +230,28 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([}const newTask = await api.tasks.create(taskData)- lemonToast.success('Task created successfully')// Auto-run the task after creation; the detail scene shows the latest run by default. The// run checks out the chosen branch (server falls back to the repo's default branch if unset)// and launches with the picked model / reasoning effort (clamped to one the model supports).- await api.tasks.run(newTask.id, {+ const runResponse = await api.tasks.run(newTask.id, {branch: repositoryConfig.branch ?? null,runtime_adapter: ClaudeRuntimeAdapterEnumApi.Claude,model,reasoning_effort: resolveEffortForModel(reasoningEffort, model),+ // Interactive keeps the sandbox agent-server's event stream open across turns, so+ // follow-up messages stream their reply over the same SSE (background runs seal the+ // stream after the first turn). Interactive runs boot with the agent-server pulling+ // pending_user_message from run state (the workflow doesn't forward it), so seed the+ // typed message as turn 1 — otherwise the first prompt is lost and the run idles.+ mode: TaskExecutionModeEnumApi.Interactive,+ pending_user_message: description,})++ // Attach the real ids to the optimistic creation so the detail page adopts this seeded stream+ // (same `streamKey` + real `runId`) instead of cold-bootstrapping a fresh, skeleton-flashing one.+ // Kept set across navigation; cleared by the `urlToAction` below once the user leaves this run.+ actions.setActiveCreation({ streamKey, taskId: newTask.id, runId: runResponse.latest_run?.id })router.actions.push(`/tasks/${newTask.id}`)actions.submitNewTaskSuccess()@@ -197,13 +259,15 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([actions.loadTasks(values.taskListParams)actions.loadRepositories()} catch (error) {+ // Show the existing failure and return to the composer with the typed text intact.+ actions.clearActiveCreation()lemonToast.error('Failed to create task')actions.submitNewTaskFailure(error instanceof Error ? error.message : 'Unknown error')}},})),- events(({ actions, values }) => ({+ events(({ actions, values, cache }) => ({afterMount: () => {actions.loadTasks(values.taskListParams)actions.loadRepositories()@@ -214,5 +278,29 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([// integrations already cached by an earlier mount.actions.maybeAutoSelectIntegration()},+ beforeUnmount: () => {+ // Release the manually-mounted optimistic stream if the whole scene unmounts mid-create — the+ // `clearActiveCreation` release only fires on navigation between runs, so leaving the tasks+ // scene entirely (before the creation resolves) would otherwise leak the mounted instance.+ cache.activeCreationUnmount?.()+ cache.activeCreationUnmount = undefined+ },})),++ urlToAction(({ actions, values }) => {+ // The optimistic creation is kept alive across the success navigation so the detail page can adopt+ // its seeded stream. Release it once the user lands anywhere other than the created task — another+ // task, the list, or back to `/tasks/new`. Guarded on `taskId` being set so the pre-id provisioning+ // phase (still at `/tasks/new`, no id yet) is never torn down mid-create.+ const clearIfLeftCreatedTask = (taskId?: string): void => {+ const activeCreation = values.activeCreation+ if (activeCreation?.taskId && activeCreation.taskId !== taskId) {+ actions.clearActiveCreation()+ }+ }+ return {+ '/tasks': () => clearIfLeftCreatedTask(),+ '/tasks/:taskId': ({ taskId }) => clearIfLeftCreatedTask(taskId),+ }+ }),])diff --git a/products/posthog_ai/frontend/types/streamTypes.ts b/products/posthog_ai/frontend/types/streamTypes.tsindex 3e87cb92671b..79284a336d67 100644--- a/products/posthog_ai/frontend/types/streamTypes.ts+++ b/products/posthog_ai/frontend/types/streamTypes.ts@@ -19,6 +19,28 @@ export interface ProgressStep {detail?: string}+/**+ * The kinds of alert the `RunAlertActivity` card renders. `reconnecting` is the live-connection retry+ * banner (attempt counter + backoff); `connection_failed` is its terminal state (retries exhausted or a+ * non-retryable open); `agent_error` / `agent_crash` are genuine agent-emitted failures rendered inline.+ */+export type RunAlertKind = 'reconnecting' | 'connection_failed' | 'agent_error' | 'agent_crash'++/**+ * View-model for the live connection banner, derived by `runStreamLogic.runConnectionState` and consumed+ * by `RunAlertActivity`. Kept a pure type here (Tier 3) so the headless selector never imports the+ * component. `null` from the selector means "connection healthy — render nothing".+ */+export interface RunConnectionState {+ kind: RunAlertKind+ /** `reconnecting`: current 1-based reconnect attempt. */+ attempt?: number+ /** `reconnecting`: max attempts before the connection is given up. */+ maxAttempts?: number+ /** The failed kinds: the error/crash detail to surface. */+ message?: string+}+/*** One merged tool call: a `tool_call` creation plus N × `tool_call_update`s folded into a* single raw stream record keyed on `toolCallId`. Renderer-specific parsing, such as resolving