Skip to content

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

fix(posthog-ai): preserve task messages during startup and refresh (#98672)

Georgiy Tarasov685817e67315
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.md
index 49a822e9ce2c..29681cd9bb22 100644
--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md
+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md
@@ -31,6 +31,9 @@ The system provisions the sandbox, clones a GitHub repo, starts an agent server,
The run thread shows startup state in a progress accordion, with completed steps available in its history.
Before progress arrives, it shows "Setting up sandbox", including when resuming a finished run.
+The full task composer remains available during startup.
+Follow-up messages collect in "Up next" and send after the first response finishes.
+Once the agent starts, Steer can send them before the current turn ends.
The thread hides empty and whitespace-only assistant messages during streaming and history replay.
```text
@@ -509,6 +512,29 @@ its session history from the API.
Publish the updated agent and rebuild sandbox images before deploying the stricter
backend capability gate, so the fallback supplies a compatible agent.
+## Recovering task messages after a refresh
+
+The task page and side panel save unsent queue text and composer drafts in browser
+local storage once a task has an ID. The cache is scoped to the signed-in user,
+project, and task, expires after seven days, and does not sync between browsers.
+The latest edit wins across tabs; another tab's edits do not replace an open composer.
+
+Opening the task again restores queued messages followed by the unfinished draft
+into one editable draft, separated by blank lines. The queue starts empty. The
+user must review and submit the restored draft; sandbox readiness, turn completion,
+and permission responses cannot send it or start a run. An active optimistic
+handoff keeps its live queue and does not perform draft recovery.
+
+Messages awaiting a send acknowledgement remain cached. If a page closes before
+confirmation, recovery asks the user to check the conversation before sending again.
+Successful sends clear the submitted text while preserving newer edits. Storage
+failures do not block composing or sending; those drafts cannot survive a refresh.
+
+While a sandbox starts, the conversation displays its first submitted message from
+the run's saved `pending_user_message` when logs do not yet contain it. This is a
+display fallback: it strips context wrappers, gives way to the selected run's log
+or stream echo, and never submits the message again.
+
## Local development
To set up sandboxed agents for local development:
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 90e865d0ec58..95c718f012de 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5688,10 +5688,18 @@ snapshots:
hash: v1.k794b7964.31c7fd62daefb54216da5c53779c56e4c440441f72447fdd80a8b99190d35713.WfQlAvkYZKbboDjk-PaqhmaBt67pg8VBxAb7_8EwKOQ
products-posthog-ai-runalertactivity--connection-lost--light:
hash: v1.k794b7964.0bac493951bd2047e08b842ba4476ca3853b5cf2bab2bc586375eca502b36fd8.OmwzOF2ZEibfR1C9Ta07PYWQYuLUu6Firyw6xmtwKYc
+ products-posthog-ai-startup-chat--queued-sidebar--dark:
+ hash: v1.k794b7964.b00472829dd4a536ce873322691bcbf252f3079eb37d0614c7fa9baf9e0b3272.DObEcDsp_ZwITHJgw5jyv6_t4h1oDp1U2jI0wTthlWU
+ products-posthog-ai-startup-chat--queued-sidebar--light:
+ hash: v1.k794b7964.ceb503685717e53ea184aa8db4d0ea628e0dfa54e8b1d40f60d0673237e70d88.gvHsmMSxj7yMkUJ5iNSBtcZu_dsjRF_i4KDcmt45iLg
+ products-posthog-ai-startup-chat--queued-wide--dark:
+ hash: v1.k794b7964.fba7548a6b2f99684156a97ebcb24427e2d09d340b8db7415d7a1adb08f23f08.PDnSLZW8eyRMhNNz8YZ4LuM0MlTtnL_FiZb4SDaTetM
+ products-posthog-ai-startup-chat--queued-wide--light:
+ hash: v1.k794b7964.d910e03de15c10ca08b56a953b274b2ac7ccd3f9ad9a6df8203abe522d2c2ebf.fVoRoJVneYM2oa3LCr5Q8Jn0-H2BkPh_GotYHvj-Q7U
products-posthog-ai-startup-chat--sidebar--dark:
- hash: v1.k794b7964.567861258fbfdb2691329675379e27af95694c69f734e63d12e88f74d36c2eee.pStxB048sPXcS-nkSrl05g9zJO3iZQmPEYE-VzPrCro
+ hash: v1.k794b7964.6d96696bb96a440ce1fa7b776edc81f103b6812009d0a850bcda00634acf485f.dm_X4B9rkIjkeWEqyEbies8fE9rJzn6jP1Rwjfl1Txs
products-posthog-ai-startup-chat--sidebar--light:
- hash: v1.k794b7964.e6ac4e16cfc30937fa95cf22ebb3adff8f4bc80c52737d919273a0ab4609c220.tbDbVYqrgoK6xmsgtuG1d3ymNaokp5MmQnpllFLfx78
+ hash: v1.k794b7964.21eaee49f9429125b726ca537df2609832e2d31297b0e98d8264964866f293cb.u5AJc9X9898pYhh_P0fqkrmxDZRscEkFWYiCq68frv4
products-posthog-ai-threadactivitygroup--long-history--dark:
hash: v1.k794b7964.2e3de4c9920447e12ddad04f5ebdbc7aa37d8724ea2c3089f752d5476abb4d3a.8adra9j6VC2g8199P2Y4HNamG7wds2LYoefV0R-MH_s
products-posthog-ai-threadactivitygroup--long-history--light:
diff --git a/products/posthog_ai/frontend/README.md b/products/posthog_ai/frontend/README.md
index 608aed246bee..6e9de4f32681 100644
--- a/products/posthog_ai/frontend/README.md
+++ b/products/posthog_ai/frontend/README.md
@@ -68,7 +68,7 @@ once when `'read-only'`. This is what all three inbox embeds drop in.
### Live embed with composer (tasks-style; caller owns the composer + draft/queue)
Compose the `RunSurface` compound (`api/runSurface`, eager) and pass your composer UI as the
-`RunSurface.Composer` children — the slot owns prompt-vs-composer precedence and the null-bootstrap gate; you
+`RunSurface.Composer` children — the slot owns prompt-vs-composer precedence and the bootstrap gate (optimistic startup keeps the composer visible); you
own the composer. See `scenes/TaskTracker/components/TaskRunChat.tsx` for the full wiring.
```tsx
@@ -141,6 +141,13 @@ stream.actions.startOptimisticRun(message) // empty → "spinning up" + the type
// …after api create/run resolve, set runId on the same surface to attach + stream it.
```
+For an interactive optimistic start, mount `runInteractionLogic` with empty `taskId`/`runId` and explicit
+`streamKey`/`interactionKey` values. Hold its mount through creation, then supply the real IDs with the same
+keys. The composer preserves its draft, settings, and editable "Up next" queue through attachment.
+Startup submissions stay local until the agent starts and its first turn completes; manual Steer is available
+once the agent has started. Configuration changes apply to the next message, not the initial prompt.
+Release the held mount when the creation is abandoned or fails. Later successor runs use their own interaction key.
+
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
diff --git a/products/posthog_ai/frontend/components/QueuedMessageList.tsx b/products/posthog_ai/frontend/components/QueuedMessageList.tsx
index 2b24ca97a1d9..f79b948192e0 100644
--- a/products/posthog_ai/frontend/components/QueuedMessageList.tsx
+++ b/products/posthog_ai/frontend/components/QueuedMessageList.tsx
@@ -13,6 +13,7 @@ export interface QueuedMessageListProps {
onRemove: (id: string) => void
onSteer?: () => void
steerPending?: boolean
+ steerDisabledReason?: string
}
interface QueuedMessageItemProps {
@@ -116,6 +117,7 @@ export function QueuedMessageList({
onRemove,
onSteer,
steerPending = false,
+ steerDisabledReason,
}: QueuedMessageListProps): JSX.Element | null {
const [editingId, setEditingId] = useState<string | null>(null)
@@ -134,7 +136,9 @@ export function QueuedMessageList({
data-attr="run-queue-steer"
onClick={onSteer}
loading={steerPending}
- disabledReason={editingId ? 'Save or cancel your edit first' : undefined}
+ disabledReason={
+ steerDisabledReason ?? (editingId ? 'Save or cancel your edit first' : undefined)
+ }
tooltip="Send queued messages before the turn ends"
sideIcon={<KeyboardShortcut escape />}
>
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
index 8b2f7b01e2fb..60baca2c6c16 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
@@ -38,6 +38,7 @@ function setValues(
pendingPermissionRequest: PermissionRequestRecord | null
respondingToPermission: boolean
bootstrapLoading: boolean
+ runOpening: boolean
threadItems: unknown[]
task: { origin_product: string; runtime?: TaskRuntimeEnumApi } | null
}>
@@ -167,9 +168,9 @@ describe('RunSurface', () => {
}
)
- it('hides the composer during the null bootstrap window', () => {
- renderLiveWithComposer(null)
- expect(screen.queryByTestId('composer')).not.toBeInTheDocument()
+ it.each([false, true])('shows the pending composer only for an optimistic start: %s', (runOpening) => {
+ renderLiveWithComposer({ currentRunStatus: null, runOpening })
+ expect(!!screen.queryByTestId('composer')).toBe(runOpening)
// The thread still renders while bootstrapping.
expect(screen.getByTestId('thread')).toBeInTheDocument()
})
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
index 4a618644df85..675a1dcc69b7 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
@@ -240,12 +240,11 @@ function RunSurfaceThread({
}
/**
- * Input-region slot: owns prompt-vs-composer precedence and the null-bootstrap gate. While a permission /
+ * Input-region slot: owns prompt-vs-composer precedence and the bootstrap gate. While a permission /
* question request is pending (and the run isn't terminal) it renders the approval prompt; otherwise it
* renders the consumer's composer `children`. Renders nothing outside live mode, during the `null` bootstrap
- * window, or when no composer children are supplied (e.g. `ReadonlyRunSurface`). The composer thus shows for
- * any settled run status (active runs take a follow-up, terminal runs start a fresh run from the typed
- * message), is hidden during bootstrap, and is replaced by the prompt while a request is pending.
+ * window without an optimistic start, or when no composer children are supplied (e.g. `ReadonlyRunSurface`).
+ * The composer also shows during optimistic startup so follow-ups can queue before the agent is ready.
*/
function RunSurfaceComposer({
children,
@@ -255,7 +254,7 @@ function RunSurfaceComposer({
isStopping?: boolean
}): JSX.Element | null {
const { interaction, streamKey } = useRunSurfaceContext()
- const { pendingPermissionRequest, respondingToPermission, currentRunStatus } = useValues(runStreamLogic)
+ const { pendingPermissionRequest, respondingToPermission, currentRunStatus, runOpening } = useValues(runStreamLogic)
if (interaction !== 'live') {
return null
}
@@ -276,7 +275,7 @@ function RunSurfaceComposer({
</div>
</div>
)}
- {children && currentRunStatus !== null && (
+ {children && (currentRunStatus !== null || runOpening) && (
<div
hidden={showApproval}
data-attr="composer"
diff --git a/products/posthog_ai/frontend/e2e/run-surface.spec.ts b/products/posthog_ai/frontend/e2e/run-surface.spec.ts
index f7d8ec690183..b6d0d351f29b 100644
--- a/products/posthog_ai/frontend/e2e/run-surface.spec.ts
+++ b/products/posthog_ai/frontend/e2e/run-surface.spec.ts
@@ -160,9 +160,14 @@ async function openRunDeepLink(page: Page, teamId: string): Promise<void> {
})
}
-async function acceptConsentInPage(page: Page): Promise<void> {
+async function prepareRunComposer(page: Page): Promise<void> {
await page.addInitScript(() => {
- let appContext: { current_user?: { organization?: { is_ai_data_processing_approved?: boolean } } }
+ let appContext: {
+ current_user?: {
+ organization?: { is_ai_data_processing_approved?: boolean }
+ has_seen_product_intro_for?: Record<string, boolean>
+ }
+ }
Object.defineProperty(window, 'POSTHOG_APP_CONTEXT', {
configurable: true,
get: () => appContext,
@@ -170,6 +175,12 @@ async function acceptConsentInPage(page: Page): Promise<void> {
if (value.current_user?.organization) {
value.current_user.organization.is_ai_data_processing_approved = true
}
+ if (value.current_user) {
+ value.current_user.has_seen_product_intro_for = {
+ ...value.current_user.has_seen_product_intro_for,
+ posthog_ai_onboarding: true,
+ }
+ }
appContext = value
},
})
@@ -208,12 +219,104 @@ test.describe('Task run surface', () => {
await expect(page.getByText('Agent error')).toBeVisible({ timeout: 20000 })
})
+ test('refresh restores the startup queue as a draft without sending it when the agent becomes ready', async ({
+ page,
+ }, testInfo) => {
+ const firstMessage = 'Compare weekly activity.'
+ const followUp = 'Include a monthly comparison.'
+ const draft = 'Keep this unfinished draft.'
+ const restoredDraft = `${followUp}\n\n${draft}`
+ const commands: { method: string; params: { content?: string } }[] = []
+ await prepareRunComposer(page)
+ await routeTasksApi(page, {
+ runStatus: 'queued',
+ logs: { status: 200, body: '' },
+ stream: { mode: 'hang' },
+ })
+ await page.route(
+ (url) => url.pathname.endsWith(`/tasks/${TASK_ID}/`),
+ fulfillJson({ ...makeTask('queued'), created_by: null })
+ )
+ await page.route(
+ (url) => url.pathname.endsWith(`/runs/${RUN_ID}/`),
+ fulfillJson({
+ ...makeRun('queued'),
+ state: { pending_user_message: firstMessage, pending_user_message_id: 'pending-first-message' },
+ })
+ )
+ await page.route(
+ (url) => url.pathname.endsWith(`/runs/${RUN_ID}/command/`),
+ async (route) => {
+ commands.push(route.request().postDataJSON())
+ await fulfillJson({ jsonrpc: '2.0', result: { queued: true } })(route)
+ }
+ )
+
+ await openRunDeepLink(page, workspace!.team_id)
+ await expect(page.getByText(firstMessage, { exact: true })).toBeVisible()
+ const composer = page.getByTestId('sandbox-composer-input')
+ await composer.fill(followUp)
+ await composer.press('Enter')
+ await expect(page.getByText('Up next', { exact: true })).toBeVisible()
+ await expect(page.getByText(followUp, { exact: true })).toBeVisible()
+
+ let startAgent!: () => void
+ const agentReady = new Promise<void>((resolve) => {
+ startAgent = resolve
+ })
+ await page.route(
+ (url) => new RegExp(`/runs/${RUN_ID}/stream/?$`).test(url.pathname),
+ async (route) => {
+ await agentReady
+ await route.fulfill({
+ contentType: 'text/event-stream',
+ body: toSse([
+ {
+ type: 'notification',
+ notification: { method: '_posthog/run_started', params: { runId: RUN_ID } },
+ },
+ {
+ type: 'notification',
+ notification: { method: '_posthog/user_message', params: { content: firstMessage } },
+ },
+ agentMessageFrame('first-answer', 'Start by grouping activity by week.'),
+ { type: 'notification', notification: { method: '_posthog/turn_complete', params: {} } },
+ ]),
+ })
+ }
+ )
+ await composer.fill(draft)
+ await page.reload()
+ await expect(composer).toHaveValue(restoredDraft, { timeout: 40000 })
+ await expect(page.getByTestId('task-draft-restored')).toHaveText('Draft restored. Review it before sending.')
+ await expect(page.getByText('Up next', { exact: true })).toHaveCount(0)
+ await expect(page.getByText(firstMessage, { exact: true })).toBeVisible()
+
+ startAgent()
+ await expect(page.getByText('Start by grouping activity by week.', { exact: true })).toBeVisible()
+ await expect(page.getByText(firstMessage, { exact: true })).toHaveCount(1)
+ await expect(composer).toHaveValue(restoredDraft)
+ expect(commands).toEqual([])
+ await page.screenshot({ path: testInfo.outputPath('restored-task-draft.png') })
+
+ await composer.press('Enter')
+ await expect(composer).toHaveValue('')
+ await expect(page.getByTestId('task-draft-restored')).toHaveCount(0)
+ await expect
+ .poll(() =>
+ commands.filter((command) => command.method === 'user_message').map((command) => command.params.content)
+ )
+ .toEqual([restoredDraft])
+ })
+
for (const [surface, path] of [
['task page', 'tasks/new'],
['side panel', 'settings/user#panel=max'],
]) {
test(`new tasks start optimistically and recover from failure in the ${surface}`, async ({ page }) => {
const message = 'Explain how to compare weekly activity.'
+ const followUp = 'Include a monthly comparison.'
+ const draft = 'Keep this unfinished draft.'
let finishCreation!: (succeeded: boolean) => void
let creationResponse = new Promise<boolean>((resolve) => {
finishCreation = resolve
@@ -226,7 +329,7 @@ test.describe('Task run surface', () => {
const agentReady = new Promise<void>((resolve) => {
startAgent = resolve
})
- await acceptConsentInPage(page)
+ await prepareRunComposer(page)
await mockFeatureFlags(page, {
[TASKS_FLAG]: true,
[TASKS_STREAM_VIA_PROXY_FLAG]: false,
@@ -254,6 +357,10 @@ test.describe('Task run surface', () => {
})
}
)
+ await page.route(
+ (url) => url.pathname.endsWith(`/runs/${RUN_ID}/command/`),
+ fulfillJson({ jsonrpc: '2.0', result: { queued: true } })
+ )
await page.route((url) => url.pathname.endsWith('/tasks/repositories/'), fulfillJson({ repositories: [] }))
await page.route(
(url) => url.pathname.endsWith('/tasks/warm/'),
@@ -273,18 +380,18 @@ test.describe('Task run surface', () => {
await agentReady
await route.fulfill({
contentType: 'text/event-stream',
- body:
- toSse([
- {
- type: 'notification',
- notification: { method: '_posthog/run_started', params: { runId: RUN_ID } },
- },
- {
- type: 'notification',
- notification: { method: '_posthog/user_message', params: { content: message } },
- },
- agentMessageFrame('first-answer', 'Start by grouping activity by week.'),
- ]) + 'data: {"type":"task_run_state","status":"completed"}\n\n',
+ body: toSse([
+ {
+ type: 'notification',
+ notification: { method: '_posthog/run_started', params: { runId: RUN_ID } },
+ },
+ {
+ type: 'notification',
+ notification: { method: '_posthog/user_message', params: { content: message } },
+ },
+ agentMessageFrame('first-answer', 'Start by grouping activity by week.'),
+ { type: 'notification', notification: { method: '_posthog/turn_complete', params: {} } },
+ ]),
})
}
)
@@ -298,25 +405,47 @@ test.describe('Task run surface', () => {
await expect(page.getByText('Setting up sandbox', { exact: false })).toBeVisible()
await expect(page.getByTestId('run-log-skeleton')).toHaveCount(0)
+ const followUpComposer = page.getByTestId('sandbox-composer-input')
+ await expect(followUpComposer).toBeVisible()
+ await expect(page.getByRole('combobox', { name: 'Mode', exact: true })).toBeVisible()
+ await followUpComposer.fill(followUp)
+ await followUpComposer.press('Enter')
+ await expect(page.getByText('Up next', { exact: true })).toBeVisible()
+ await expect(page.getByText(followUp, { exact: true })).toBeVisible()
+ await expect(page.getByTestId('run-queue-steer')).toBeDisabled()
+ await followUpComposer.fill(draft)
finishCreation(false)
- await expect(composer).toHaveValue(message)
+ await expect(composer).toHaveValue(`${message}\n\n${followUp}\n\n${draft}`)
+ await composer.fill(message)
await expect(page.getByText('Setting up sandbox', { exact: false })).toHaveCount(0)
creationResponse = new Promise<boolean>((resolve) => {
finishCreation = resolve
})
await composer.press('Enter')
await expect(page.getByText(message, { exact: true })).toBeVisible()
+ await expect(followUpComposer).toBeVisible()
+ await followUpComposer.fill(followUp)
+ await followUpComposer.press('Enter')
+ await expect(page.getByText('Up next', { exact: true })).toBeVisible()
+ await followUpComposer.fill(draft)
finishCreation(true)
await expect(page.getByTestId('sandbox-composer-input')).toBeVisible()
await expect(page.getByText(message, { exact: true })).toHaveCount(1)
await expect(page.getByText('Setting up sandbox', { exact: false })).toBeVisible()
await expect(page.getByTestId('run-log-skeleton')).toHaveCount(0)
+ await expect(followUpComposer).toHaveValue(draft)
+ await expect(followUpComposer).toBeFocused()
+ await expect(page.getByText('Up next', { exact: true })).toBeVisible()
+ await expect(page.getByTestId('run-queue-steer')).toBeDisabled()
await page.screenshot({ path: test.info().outputPath('new-task-starting.png') })
startAgent()
await expect(page.getByText('Start by grouping activity by week.', { exact: true })).toBeVisible()
await expect(page.getByText(message, { exact: true })).toHaveCount(1)
+ await expect(page.getByText('Up next', { exact: true })).toHaveCount(0)
+ await expect(page.getByText(followUp, { exact: true })).toHaveCount(1)
+ await expect(followUpComposer).toHaveValue(draft)
revealMetadata()
await expect(page.getByTestId('sandbox-composer-input')).toBeVisible()
await expect(page.getByTestId('run-log-skeleton')).toHaveCount(0)
@@ -371,7 +500,7 @@ test.describe('Task run surface', () => {
},
stream: { mode: 'hang' },
})
- await acceptConsentInPage(page)
+ await prepareRunComposer(page)
await page.route(
(url) => url.pathname.endsWith(`/tasks/${TASK_ID}/`),
fulfillJson({ ...makeTask('completed'), created_by: null })
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
index f0915ba248b6..caf4c9e86e63 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
@@ -21,6 +21,7 @@ import { attachedContextLogic } from './attachedContextLogic'
import { runCancellationLogic } from './runCancellationLogic'
import { runInteractionLogic } from './runInteractionLogic'
import { runStreamLogic } from './runStreamLogic'
+import { TaskDraftPersistence, taskDraftStorageKey } from './taskDraftPersistence'
import { toolStreamEventsLogic } from './toolStreamEventsLogic'
// Minimal kea stub for the shared sandbox stream logic — gives the test full control over the busy gate
@@ -45,6 +46,7 @@ jest.mock('./runStreamLogic', () => {
handleTerminalStatus: (status: { status: string }) => status,
setStubStatus: (status: string | null) => ({ status }),
setStubThinking: (thinking: boolean) => ({ thinking }),
+ setStubReady: (ready: boolean) => ({ ready }),
setStubClearSupported: (supported: boolean) => ({ supported }),
ingestPermissionRequest: (record: PermissionRequestRecord) => ({ record }),
markPermissionRequestResolved: (requestId: string) => ({ requestId }),
@@ -60,6 +62,8 @@ jest.mock('./runStreamLogic', () => {
bootstrapRun: true,
}),
reducers({
+ runOpening: [false, {}],
+ runStarted: [true, { setStubReady: (_: boolean, { ready }: { ready: boolean }) => ready }],
currentRunStatus: [
'in_progress',
{
@@ -192,6 +196,7 @@ describe('runInteractionLogic', () => {
beforeEach(() => {
jest.clearAllMocks()
+ localStorage.clear()
;(tasksRunsCommandCreate as jest.Mock).mockResolvedValue({ jsonrpc: '2.0', result: { queued: true } })
;(tasksRunCreate as jest.Mock).mockResolvedValue({ latest_run: { id: 'run-2' } })
;(tasksRunsClearConversationCreate as jest.Mock).mockResolvedValue({})
@@ -219,6 +224,162 @@ describe('runInteractionLogic', () => {
toolEvents?.unmount()
})
+ it('restores queued text and the latest page-exit draft without sending on readiness or turn completion', async () => {
+ logic.actions.enableTaskDraftPersistence('user-1', 997)
+ setThinking(true)
+ logic.actions.setComposerFormValues({ draft: 'queued first' })
+ logic.actions.submitComposerForm()
+ logic.actions.setComposerFormValues({ draft: 'queued second' })
+ logic.actions.submitComposerForm()
+ runInteractionLogic({
+ ...logic.props,
+ flushDraft: () => logic.actions.setComposerFormValues({ draft: 'last keystroke' }),
+ })
+ window.dispatchEvent(new Event('pagehide'))
+ logic.unmount()
+ logic = runInteractionLogic({ taskId: TASK_ID, runId: RUN_ID, onRunStarted })
+ logic.mount()
+ logic.actions.enableTaskDraftPersistence('user-1', 997)
+ expect(logic.values.composerForm.draft).toBe('queued first\n\nqueued second\n\nlast keystroke')
+ expect(logic.values.queuedMessages).toEqual([])
+ expect(logic.values.draftRecovery).toBe('restored')
+ setThinking(false)
+ await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ expect(tasksRunCreate).not.toHaveBeenCalled()
+ expect(tasksWarmResumeCreate).not.toHaveBeenCalled()
+ await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(
+ ...userMessageCommand('queued first\n\nqueued second\n\nlast keystroke')
+ )
+ expect(new TaskDraftPersistence(taskDraftStorageKey('user-1', 997, TASK_ID)).restore()).toBeNull()
+ })
+
+ it('does not prewarm a recovered terminal draft or copy it into another user or project', async () => {
+ const key = taskDraftStorageKey('user-1', 997, TASK_ID)
+ new TaskDraftPersistence(key).save({ runId: RUN_ID, draft: 'saved draft', queuedText: '', recovery: null })
+ setStatus('completed')
+ await expectLogic(logic, () => logic.actions.enableTaskDraftPersistence('user-1', 997)).toFinishAllListeners()
+ expect(logic.values.composerForm.draft).toBe('saved draft')
+ expect(tasksWarmResumeCreate).not.toHaveBeenCalled()
+ logic.actions.setComposerFormValues({ draft: 'edited after recovery' })
+ logic.actions.enableTaskDraftPersistence('user-1', 997)
+ expect(logic.values.composerForm.draft).toBe('edited after recovery')
+ logic.actions.enableTaskDraftPersistence('user-2', 997)
+ expect(logic.values.composerForm.draft).toBe('')
+ logic.actions.enableTaskDraftPersistence('user-1', 998)
+ expect(logic.values.composerForm.draft).toBe('')
+ expect(new TaskDraftPersistence(key).restore()?.draft).toBe('edited after recovery')
+ })
+
+ it('keeps startup input and settings through attachment and sends the queue after the first turn', async () => {
+ const pending = runInteractionLogic({ taskId: '', runId: '', streamKey: RUN_ID, interactionKey: 'creation' })
+ const unmount = pending.mount()
+ const other = runInteractionLogic({
+ taskId: '',
+ runId: '',
+ streamKey: 'other-draft',
+ interactionKey: 'other-draft',
+ })
+ const unmountOther = other.mount()
+ const setReady = (ready: boolean): void =>
+ (stream.actions as unknown as { setStubReady: (ready: boolean) => void }).setStubReady(ready)
+ try {
+ pending.actions.enableTaskDraftPersistence('user-1', 997)
+ other.actions.setComposerFormValues({ draft: 'another task follow-up' })
+ other.actions.submitComposerForm()
+ setStatus(null)
+ setReady(false)
+ pending.actions.setEffort('low')
+ pending.actions.setMode('plan')
+ pending.actions.setComposerFormValues({ draft: 'first follow-up' })
+ pending.actions.submitComposerForm()
+ pending.actions.setComposerFormValues({ draft: 'second follow-up' })
+ pending.actions.submitComposerForm()
+ pending.actions.setComposerFormValues({ draft: 'unfinished draft' })
+ pending.actions.handleEscape()
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ expect(tasksWarmResumeCreate).not.toHaveBeenCalled()
+ expect(pending.values.queuedMessages).toEqual([
+ { id: 'queued', content: 'first follow-up\n\nsecond follow-up' },
+ ])
+
+ pending.actions.hydrateTaskDraft(TASK_ID)
+ expect(new TaskDraftPersistence(taskDraftStorageKey('user-1', 997, TASK_ID)).restore()?.draft).toBe(
+ 'first follow-up\n\nsecond follow-up\n\nunfinished draft'
+ )
+
+ const attached = runInteractionLogic({ ...pending.props, taskId: TASK_ID, runId: RUN_ID })
+ expect(attached).toBe(pending)
+ expect(new TaskDraftPersistence(taskDraftStorageKey('user-1', 997, TASK_ID)).restore()?.draft).toBe(
+ 'first follow-up\n\nsecond follow-up\n\nunfinished draft'
+ )
+ expect(attached.values.draftRecovery).toBeNull()
+ setStatus('queued')
+ attached.actions.steerQueue()
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ setThinking(true)
+ setReady(true)
+ stream.actions.setCurrentMode('default')
+ expect(attached.values.composerForm.draft).toBe('unfinished draft')
+ expect(attached.values.effortOverride).toBe('low')
+ expect(attached.values.selectedMode).toBe('plan')
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+
+ setThinking(false)
+ await expectLogic(attached, () => stream.actions.markTurnComplete()).toFinishAllListeners()
+ expect(attached.values.queuedMessages).toEqual([])
+ expect(attached.values.composerForm.draft).toBe('unfinished draft')
+ const messages = (tasksRunsCommandCreate as jest.Mock).mock.calls.filter(
+ (call) => call[3].method === 'user_message'
+ )
+ expect(messages).toEqual([userMessageCommand('first follow-up\n\nsecond follow-up')])
+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, {
+ jsonrpc: '2.0',
+ method: 'set_config_option',
+ params: { configId: 'mode', value: 'plan' },
+ })
+ expect(attached.values.selectedMode).toBe('plan')
+ stream.actions.setCurrentMode('auto')
+ expect(attached.values.selectedMode).toBe('auto')
+ expect(other.values.queuedMessages).toEqual([{ id: 'queued', content: 'another task follow-up' }])
+ } finally {
+ unmountOther()
+ unmount()
+ }
+ })
+
+ it('holds the queue after Stop until the user explicitly steers it', async () => {
+ setThinking(true)
+ logic.actions.enqueueMessage('keep this follow-up')
+ logic.actions.requestCancellation()
+ setThinking(false)
+ runCancellationLogic({ streamKey: RUN_ID }).actions.clearCancellation()
+ await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ expect(logic.values.queuedMessages[0].content).toBe('keep this follow-up')
+ await expectLogic(logic, () => logic.actions.steerQueue()).toFinishAllListeners()
+ expect(logic.values.queuedMessages).toEqual([])
+ })
+
+ it('drains a follow-up queued after a Stop that had nothing staged', async () => {
+ setThinking(true)
+ logic.actions.requestCancellation()
+ runCancellationLogic({ streamKey: RUN_ID }).actions.clearCancellation()
+ setThinking(false)
+ await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()
+
+ setThinking(true)
+ logic.actions.setComposerFormValues({ draft: 'follow-up after the stop' })
+ logic.actions.submitComposerForm()
+ expect(logic.values.queuedMessages[0].content).toBe('follow-up after the stop')
+
+ setThinking(false)
+ await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()
+ expect(logic.values.queuedMessages).toEqual([])
+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('follow-up after the stop'))
+ })
+
it('adopts the startup draft once and clears it after sending', async () => {
const onDraftAdopted = jest.fn()
const attached = runInteractionLogic({
@@ -1133,6 +1294,8 @@ describe('runInteractionLogic', () => {
})
it('keeps text typed into the composer during an in-flight draft send instead of clobbering it on success', async () => {
+ logic.actions.enableTaskDraftPersistence('user-1', 997)
+ const key = taskDraftStorageKey('user-1', 997, TASK_ID)
let resolveSend: () => void = () => {}
;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(
new Promise((resolve) => {
@@ -1150,6 +1313,11 @@ describe('runInteractionLogic', () => {
// The user keeps typing while the send is in flight.
logic.actions.setComposerFormValues({ draft: 'next thought' })
+ expect(new TaskDraftPersistence(key).restore()).toEqual({
+ draft: 'ship it\n\nnext thought',
+ recovery: 'unconfirmed',
+ })
+
await expectLogic(logic, () => {
resolveSend()
}).toFinishAllListeners()
@@ -1157,6 +1325,7 @@ describe('runInteractionLogic', () => {
// Success leaves the composer alone — the newly typed text survives rather than being wiped.
expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('ship it'))
expect(logic.values.composerForm.draft).toBe('next thought')
+ expect(new TaskDraftPersistence(key).restore()).toEqual({ draft: 'next thought', recovery: 'restored' })
})
it('restores a failed draft send ahead of text typed during the send, preserving order', async () => {
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
index 3848130fda2c..2a8f2a01671d 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
@@ -1,4 +1,17 @@
-import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import {
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ propsChanged,
+ reducers,
+ selectors,
+} from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
@@ -10,6 +23,7 @@ import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'
import {
buildRunCreateRequest,
DEFAULT_COMPOSER_MODEL,
+ getRuntimeAdapterForModel,
resolveEffortForModel,
} from 'products/posthog_ai/frontend/utils/composerModels'
import {
@@ -40,16 +54,21 @@ import { modelCatalogueLogic } from './modelCatalogueLogic'
import { type CancellationState, runCancellationLogic } from './runCancellationLogic'
import { isTerminalRunStatus, runStreamLogic } from './runStreamLogic'
import type { RunStatus } from './runStreamLogic'
+import { taskDraftListeners } from './taskDraftListeners'
+import type { DraftRecovery } from './taskDraftPersistence'
import { taskRunDefaultsLogic } from './taskRunDefaultsLogic'
import { taskWarmLogic } from './taskWarmLogic'
import { toolStreamEventsLogic } from './toolStreamEventsLogic'
export interface RunInteractionLogicProps {
+ /** Empty until creation attaches a real task and run. */
taskId: string
runId: string
+ /** Keeps the composer state alive across an optimistic creation's ID handoff. */
+ interactionKey?: 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
+ * Optional override for the bound `runStreamLogic` key. The logic keys its own state by
+ * `interactionKey ?? runId`, 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`.
*/
@@ -115,11 +134,14 @@ export interface runInteractionLogicValues {
pendingPermissionRequest: PermissionRequestRecord | null // runStreamLogic
permissionResponseRequestIds: Set<string> // runStreamLogic
respondingToPermission: boolean // runStreamLogic
+ runOpening: boolean // runStreamLogic
+ runStarted: boolean // runStreamLogic
defaultEffort: string | null // taskRunDefaultsLogic
defaultModel: string | null // taskRunDefaultsLogic
canSend: boolean
clearing: boolean
composerActive: boolean
+ composerFocused: boolean
composerForm: {
draft: string
}
@@ -144,6 +166,7 @@ export interface runInteractionLogicValues {
consentBlocked: boolean
consentBlockedSource: 'draft' | 'queue' | 'steer'
deferredSteerRequestId: string | null
+ draftRecovery: DraftRecovery
effortOverride: string | null
hasUnresolvedApproval: boolean
isBusy: boolean
@@ -166,6 +189,7 @@ export interface runInteractionLogicValues {
showComposerFormErrors: boolean
startingRun: boolean
steerPending: boolean
+ unsentStartupMode: PermissionMode | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -265,25 +289,15 @@ export interface runInteractionLogicActions {
startOptimisticResume: (message: string) => {
message: string
} // runStreamLogic
- consumeWarm: () => {
- value: true
- } // taskWarmLogic
- noteDraft: (
- hasText: boolean,
- request: import('./taskWarmLogic').TaskWarmRequest
- ) => {
- hasText: boolean
- request: import('./taskWarmLogic').TaskWarmRequest
- } // taskWarmLogic
- releaseWarm: () => {
- value: true
- } // taskWarmLogic
claimApplyBackTargets: (streamKey: string) => {
streamKey: string
} // toolStreamEventsLogic
releaseApplyBackTargets: (streamKey: string) => {
streamKey: string
} // toolStreamEventsLogic
+ beginTaskDraftDelivery: (content: string) => {
+ content: string
+ }
blockOnConsent: (source?: 'draft' | 'queue' | 'steer') => {
source: 'draft' | 'queue' | 'steer'
}
@@ -296,8 +310,19 @@ export interface runInteractionLogicActions {
clearQueue: () => {
value: true
}
+ enableTaskDraftPersistence: (
+ userId: string,
+ projectId: number
+ ) => {
+ projectId: number
+ userId: string
+ }
enqueueMessage: (content: string) => {
content: string
+ wasEmpty: boolean
+ }
+ finishTaskDraftDelivery: () => {
+ value: true
}
flushQueue: (steer?: boolean) => {
steer: boolean
@@ -305,6 +330,12 @@ export interface runInteractionLogicActions {
handleEscape: () => {
value: true
}
+ hydrateTaskDraft: (taskId?: string) => {
+ taskId: string | undefined
+ }
+ persistTaskDraft: () => {
+ value: true
+ }
prependQueuedMessage: (content: string) => {
content: string
}
@@ -331,6 +362,9 @@ export interface runInteractionLogicActions {
setClearing: (clearing: boolean) => {
clearing: boolean
}
+ setComposerFocused: (focused: boolean) => {
+ focused: boolean
+ }
setComposerFormManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
@@ -353,10 +387,14 @@ export interface runInteractionLogicActions {
setDeferredSteer: (requestId: string | null) => {
requestId: string | null
}
+ setDraftRecovery: (recovery: DraftRecovery) => {
+ recovery: DraftRecovery
+ }
setEffort: (effort: string) => {
effort: string
}
setMode: (mode: PermissionMode) => {
+ beforeStart: boolean
mode: PermissionMode
}
setModel: (model: string) => {
@@ -369,6 +407,7 @@ export interface runInteractionLogicActions {
effort: string
}
setSentMode: (mode: PermissionMode) => {
+ hasStartupOverride: boolean
mode: PermissionMode
}
setSentModel: (model: string) => {
@@ -433,7 +472,14 @@ export interface runInteractionLogicMeta {
isTerminal: boolean
) => boolean
isTerminal: (currentRunStatus: RunStatus | null) => boolean
- selectedModel: (modelOverride: string | null, arg: any, defaultModel: string | null) => string
+ selectedModel: (
+ modelOverride: string | null,
+ arg: any,
+ defaultModel: string | null,
+ catalogue: ModelChoiceApi[],
+ arg2: any,
+ isTerminal: boolean
+ ) => string
selectedEffort: (
effortOverride: string | null,
arg: any,
@@ -442,12 +488,19 @@ export interface runInteractionLogicMeta {
catalogue: ModelChoiceApi[]
) => ReasoningEffortEnumApi
selectedMode: (
+ unsentStartupMode: PermissionMode | null,
modeOverride: PermissionMode | null,
currentMode: string | null,
arg: any,
arg2: any
) => PermissionMode
- isBusy: (isThinking: boolean) => boolean
+ isBusy: (
+ isThinking: boolean,
+ runOpening: boolean,
+ runStarted: boolean,
+ isTerminal: boolean,
+ runId: string
+ ) => boolean
canSend: (
sending: boolean,
cancellationState: CancellationState,
@@ -457,7 +510,8 @@ export interface runInteractionLogicMeta {
bootstrappedRunId: string | null,
bootstrappedTaskId: string | null,
runId: string,
- taskId: string
+ taskId: string,
+ runStarted: boolean
) => boolean
isSubmitting: (sending: boolean, startingRun: boolean, clearing: boolean) => boolean
pendingContextItems: (
@@ -492,7 +546,12 @@ export type runInteractionLogicType = MakeLogicType<
export const runInteractionLogic = kea<runInteractionLogicType>([
path(['products', 'posthog_ai', 'frontend', 'logics', 'runInteractionLogic']),
props({} as RunInteractionLogicProps),
- key((props) => props.runId),
+ key((props) => {
+ if (!props.runId && (!props.interactionKey || !props.streamKey)) {
+ throw new Error('A pending composer requires interactionKey and streamKey')
+ }
+ return props.interactionKey ?? props.runId
+ }),
connect((props: RunInteractionLogicProps) => ({
values: [
@@ -504,6 +563,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
'pendingPermissionRequest',
'respondingToPermission',
'isThinking',
+ 'runOpening',
+ 'runStarted',
'currentMode',
'conversationClearSupported',
'permissionResponseRequestIds',
@@ -546,14 +607,19 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
['markContextSent'],
toolStreamEventsLogic,
['claimApplyBackTargets', 'releaseApplyBackTargets'],
- taskWarmLogic({ taskId: props.taskId, resumeFromRunId: props.runId }),
- ['noteDraft', 'consumeWarm', 'releaseWarm'],
runCancellationLogic({ streamKey: props.streamKey ?? props.runId }),
['requestCancellation'],
],
})),
- actions({
+ actions(({ values }) => ({
+ enableTaskDraftPersistence: (userId: string, projectId: number) => ({ userId, projectId }),
+ hydrateTaskDraft: (taskId?: string) => ({ taskId }),
+ persistTaskDraft: true,
+ beginTaskDraftDelivery: (content: string) => ({ content }),
+ finishTaskDraftDelivery: true,
+ setDraftRecovery: (recovery: DraftRecovery) => ({ recovery }),
+ setComposerFocused: (focused: boolean) => ({ focused }),
setSending: (sending: boolean) => ({ sending }),
blockOnConsent: (source: 'draft' | 'queue' | 'steer' = 'draft') => ({ source }),
clearConsentBlock: true,
@@ -568,7 +634,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// the staged buffer combined into this send).
sendNow: (content: string, source: 'draft' | 'queue', steer: boolean = false) => ({ content, source, steer }),
// Stage a follow-up, concatenating onto any message already queued so the buffer stays a single message.
- enqueueMessage: (content: string) => ({ content }),
+ enqueueMessage: (content: string) => ({ content, wasEmpty: values.queuedMessages.length === 0 }),
// Re-stage unsent content ahead of anything queued since — used to restore a failed queue flush.
prependQueuedMessage: (content: string) => ({ content }),
updateQueuedMessage: (id: string, content: string) => ({ id, content }),
@@ -587,16 +653,29 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
setEffort: (effort: string) => ({ effort }),
// Pick the permission mode for the run. Like model/effort, selection is held client-side and synced to
// the running agent (via `set_config_option { configId: 'mode' }`) at send time, or seeds the next run.
- setMode: (mode: PermissionMode) => ({ mode }),
+ setMode: (mode: PermissionMode) => ({ mode, beforeStart: !values.runStarted }),
// Internal: record the model / effort / mode last synced to the agent session, so a send only fires a
// `set_config_option` when the pick actually differs from what the session is already running.
setSentModel: (model: string) => ({ model }),
setSentEffort: (effort: string) => ({ effort }),
- setSentMode: (mode: PermissionMode) => ({ mode }),
- }),
+ setSentMode: (mode: PermissionMode) => ({ mode, hasStartupOverride: values.unsentStartupMode !== null }),
+ })),
reducers({
- queueNeedsRetry: [false, { queueDeliveryFailed: () => true, clearQueue: () => false }],
+ composerFocused: [false, { setComposerFocused: (_, { focused }) => focused }],
+ queueNeedsRetry: [
+ false,
+ {
+ queueDeliveryFailed: () => true,
+ requestCancellation: () => true,
+ handleTerminalStatus: (state, { status }) => isTerminalRunStatus(status) || state,
+ // A Stop or a terminal run with nothing staged latches the hold against a message that does
+ // not exist. Whatever is staged next into an empty buffer is a fresh follow-up, not the held
+ // one, so it drains on turn end instead of waiting for a Steer click.
+ enqueueMessage: (state, { wasEmpty }) => (wasEmpty ? false : state),
+ clearQueue: () => false,
+ },
+ ],
consentBlockedSource: ['draft' as 'draft' | 'queue' | 'steer', { blockOnConsent: (_, { source }) => source }],
deferredSteerRequestId: [
null as string | null,
@@ -638,6 +717,14 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
setClearing: (_, { clearing }) => clearing,
},
],
+ draftRecovery: [
+ null as DraftRecovery,
+ {
+ setDraftRecovery: (_, { recovery }) => recovery,
+ submitComposerForm: () => null,
+ resetComposerForm: () => null,
+ },
+ ],
queuedMessages: [
[] as QueuedMessage[],
{
@@ -678,12 +765,21 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
null as PermissionMode | null,
{
setMode: (_, { mode }) => mode,
+ setSentMode: (state, { mode, hasStartupOverride }) => (hasStartupOverride ? mode : state),
// Unlike model/effort, the mode genuinely changes server-side (e.g. a plan approval moves the
// session out of Plan mode) — the agent's confirmed mode is authoritative, so a stale manual
// pick must not keep shadowing the stream's `current_mode_update`.
setCurrentMode: () => null,
},
],
+ // The initial session mode describes the first prompt, not the queued follow-up's selection.
+ unsentStartupMode: [
+ null as PermissionMode | null,
+ {
+ setMode: (_, { mode, beforeStart }) => (beforeStart ? mode : null),
+ setSentMode: () => null,
+ },
+ ],
// The model/effort last synced to the agent session via `set_config_option`. null means "not synced
// yet this session" — the active config is then the run's stored value (or the default).
sentModel: [
@@ -787,9 +883,31 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// override, else the run's stored value, else the server-resolved default (user preference over
// project default), else the built-in default. Effort is clamped to one the model supports.
selectedModel: [
- (s) => [s.modelOverride, (_, p) => p.currentModel, s.defaultModel],
- (override: string | null, current, serverDefault: string | null): string =>
- override ?? current ?? serverDefault ?? DEFAULT_COMPOSER_MODEL,
+ (s) => [
+ s.modelOverride,
+ (_, p) => p.currentModel,
+ s.defaultModel,
+ s.catalogue,
+ (_, p) => p.currentRuntimeAdapter,
+ s.isTerminal,
+ ],
+ (
+ override: string | null,
+ current: string | null | undefined,
+ serverDefault: string | null,
+ catalogue: ModelChoiceApi[],
+ runtimeAdapter: string | null | undefined,
+ terminal: boolean
+ ): string => {
+ const compatibleOverride =
+ override &&
+ !terminal &&
+ runtimeAdapter &&
+ getRuntimeAdapterForModel(catalogue, override) !== runtimeAdapter
+ ? null
+ : override
+ return compatibleOverride ?? current ?? serverDefault ?? DEFAULT_COMPOSER_MODEL
+ },
],
selectedEffort: [
(s) => [s.effortOverride, (_, p) => p.currentEffort, s.defaultEffort, s.selectedModel, s.catalogue],
@@ -807,8 +925,15 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// mode, another runtime's vocabulary) degrades to the next fallback instead of leaking out as a
// fake `PermissionMode`.
selectedMode: [
- (s) => [s.modeOverride, s.currentMode, (_, p) => p.currentMode, (_, p) => p.currentRuntimeAdapter],
+ (s) => [
+ s.unsentStartupMode,
+ s.modeOverride,
+ s.currentMode,
+ (_, p) => p.currentMode,
+ (_, p) => p.currentRuntimeAdapter,
+ ],
(
+ startupOverride: PermissionMode | null,
override: PermissionMode | null,
current: string | null,
initial: string | null | undefined,
@@ -818,12 +943,17 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// (a run started from desktop or Slack), and showing `full access` on a Claude run — or
// sending it — is a mode that runtime rejects.
const adapter = runtimeAdapter ?? RuntimeAdapterEnumApi.Claude
- const picked = override ?? getModeOption(current)?.value ?? getModeOption(initial)?.value
+ const picked =
+ startupOverride ?? override ?? getModeOption(current)?.value ?? getModeOption(initial)?.value
return picked ? resolveModeForRuntimeAdapter(adapter, picked) : getDefaultModeForRuntimeAdapter(adapter)
},
],
// The agent is actively working a turn — a follow-up typed now should stage rather than send.
- isBusy: [(s) => [s.isThinking], (isThinking: boolean): boolean => isThinking],
+ isBusy: [
+ (s, p) => [s.isThinking, s.runOpening, s.runStarted, s.isTerminal, p.runId],
+ (thinking: boolean, opening: boolean, started: boolean, terminal: boolean, runId: string): boolean =>
+ thinking || opening || (!terminal && (!runId || !started)),
+ ],
canSend: [
(s, p) => [
s.sending,
@@ -835,6 +965,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
s.bootstrappedTaskId,
p.runId,
p.taskId,
+ s.runStarted,
],
(
sending: boolean,
@@ -845,13 +976,17 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
activeRunId: string | null,
activeTaskId: string | null,
runId: string,
- taskId: string
+ taskId: string,
+ runStarted: boolean
): boolean =>
!sending &&
!cancellationState &&
!isTerminal &&
currentProjectId != null &&
status !== null &&
+ !!taskId &&
+ !!runId &&
+ runStarted &&
(!activeRunId || activeRunId === runId) &&
(!activeTaskId || activeTaskId === taskId),
],
@@ -892,6 +1027,18 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
}),
listeners(({ actions, values, props, cache }) => {
+ const getWarmLogic = (): ReturnType<typeof taskWarmLogic> | undefined => {
+ if (!props.taskId || !props.runId) {
+ return
+ }
+ const warm = taskWarmLogic({ taskId: props.taskId, resumeFromRunId: props.runId })
+ if (cache.warmLogicKey !== warm.key || cache.warmDisposables !== cache.disposables) {
+ cache.disposables.add(() => warm.mount(), 'composer-warm', { pauseOnPageHidden: false })
+ cache.warmLogicKey = warm.key
+ cache.warmDisposables = cache.disposables
+ }
+ return warm
+ }
const invalidateSend = (): void => {
cache.sendGeneration = (cache.sendGeneration ?? 0) + 1
actions.setSending(false)
@@ -901,7 +1048,14 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// Consent gates warming as it gates sending: a warm boots a cloud sandbox and restores
// the task's repository snapshot, so typing must not start one before the organization
// accepts AI data processing.
- if (!values.isTerminal || !values.dataProcessingAccepted) {
+ if (
+ !props.taskId ||
+ !props.runId ||
+ !values.isTerminal ||
+ !values.dataProcessingAccepted ||
+ values.draftRecovery ||
+ cache.restoringTaskDraft
+ ) {
return
}
const createRequest = buildRunCreateRequest(
@@ -911,7 +1065,10 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
values.selectedMode,
{ resume_from_run_id: props.runId }
)
- actions.noteDraft(Boolean(values.composerForm.draft.trim()), createRequest as WarmTaskResumeRequestApi)
+ getWarmLogic()?.actions.noteDraft(
+ Boolean(values.composerForm.draft.trim()),
+ createRequest as WarmTaskResumeRequestApi
+ )
}
// Record the non-text refs just wrapped into a send under the task, so no later send anywhere in
@@ -1029,6 +1186,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
props.runId === runId &&
props.taskId === taskId
actions.setSending(true)
+ actions.beginTaskDraftDelivery(content)
const streamKey = props.streamKey ?? props.runId
// `/clear` goes unwrapped: a context block would hide the command behind it (the
// agent reads the command off the front) and mark refs sent that nothing ever read.
@@ -1040,6 +1198,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
if (source === 'draft') {
actions.resetComposerForm()
}
+ actions.persistTaskDraft()
try {
// Sync the picked model/effort to the agent session first, but only what the user actually
// changed since the last sync — mid-run config lives as session state, so it must go via a
@@ -1092,8 +1251,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
if (!isCurrent()) {
return
}
- actions.setSentMode(values.selectedMode)
}
+ actions.setSentMode(values.selectedMode)
// Wrap the outgoing content with the on-screen context block (invisible to the user —
// `runStreamLogic.unwrapUserMessageContent` strips it on replay, and the echo below is raw).
if (!isCurrent() || values.hasUnresolvedApproval) {
@@ -1124,6 +1283,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// The SSE echo (`pushHumanMessage`) reopens the turn — always the raw text the user typed.
actions.pushHumanMessage(content)
markPendingContextSent(pendingContext)
+ actions.finishTaskDraftDelivery()
} catch {
if (!isCurrent()) {
return
@@ -1142,6 +1302,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
actions.queueDeliveryFailed()
actions.prependQueuedMessage(content)
}
+ actions.finishTaskDraftDelivery()
lemonToast.error('Failed to send message. Please try again.')
} finally {
if (isCurrent()) {
@@ -1181,7 +1342,13 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
cancelPermissionDelivery: invalidateSend,
startNewRun: async ({ content }) => {
- if (values.startingRun || !content.trim() || values.currentProjectId == null) {
+ if (
+ !props.taskId ||
+ !props.runId ||
+ values.startingRun ||
+ !content.trim() ||
+ values.currentProjectId == null
+ ) {
return
}
actions.setStartingRun(true)
@@ -1224,7 +1391,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
pending_user_message: wrapWithPosthogContext(content, pendingContext),
}
)
- actions.consumeWarm()
+ getWarmLogic()?.actions.consumeWarm()
+ actions.beginTaskDraftDelivery(content)
actions.resetComposerForm()
actions.startOptimisticResume(content)
optimisticStarted = true
@@ -1240,6 +1408,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
throw new Error('The run response did not include a run')
}
accepted = true
+ actions.finishTaskDraftDelivery()
markPendingContextSent(pendingContext)
props.flushDraft?.()
const handoff = { run, streamKey, draft: values.composerForm.draft }
@@ -1263,6 +1432,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
})
optimisticStarted = false
}
+ actions.finishTaskDraftDelivery()
lemonToast.error(
error instanceof ApiError && error.code === 'warm_run_activation_unavailable'
? "Couldn't start this run yet. Please try again."
@@ -1277,7 +1447,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
},
clearConversation: async () => {
- if (values.clearing || values.currentProjectId == null) {
+ if (!props.taskId || !props.runId || values.clearing || values.currentProjectId == null) {
return
}
actions.setClearing(true)
@@ -1286,7 +1456,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// Any successor held right now was warmed before this boundary was written, so its
// restored session still carries the conversation the clear just removed. Hand it
// back; the next keystroke warms a fresh one on the cleared state.
- actions.releaseWarm()
+ getWarmLogic()?.actions.releaseWarm()
actions.resetComposerForm()
// A finished run has no live stream to echo these back, so paint them from here.
// They match what the backend persisted, so a later replay folds the same thread.
@@ -1300,10 +1470,36 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
},
}
}),
- afterMount(({ actions, props }) => {
+ listeners(taskDraftListeners),
+ propsChanged(({ actions }) => {
+ actions.hydrateTaskDraft()
+ }),
+ afterMount((logic) => {
+ const { actions, props, cache } = logic
if (props.initialDraft) {
actions.setComposerFormValues({ draft: props.initialDraft })
props.onDraftAdopted?.()
}
+ cache.disposables.add(
+ () => {
+ const flush = (): void => {
+ logic.props.flushDraft?.()
+ actions.persistTaskDraft()
+ }
+ const onVisibilityChange = (): void => {
+ if (document.visibilityState === 'hidden') {
+ flush()
+ }
+ }
+ window.addEventListener('pagehide', flush)
+ document.addEventListener('visibilitychange', onVisibilityChange)
+ return () => {
+ window.removeEventListener('pagehide', flush)
+ document.removeEventListener('visibilitychange', onVisibilityChange)
+ }
+ },
+ 'task-draft-page-exit',
+ { pauseOnPageHidden: false }
+ )
}),
])
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index 79828576c409..3d5685dc6137 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -1276,6 +1276,72 @@ describe('runStreamLogic', () => {
expect(logic.values.threadItems.filter((item) => item.type === 'human_message')).toHaveLength(1)
})
+ it.each([false, true])(
+ 'displays a pending first message before logs arrive (readOnly=%s)',
+ async (readOnly) => {
+ const content = 'Compare weekly activity.'
+ runStreamLogic({ ...logic.props, replayOnly: readOnly })
+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])
+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({
+ id: 'run-1',
+ task: 'task-1',
+ stage: null,
+ branch: null,
+ status: TaskRunStatus.QUEUED,
+ environment: TaskRunEnvironment.CLOUD,
+ error_message: null,
+ output: null,
+ artifacts: [],
+ state: {
+ pending_user_message: wrapWithPosthogContext(content, [
+ { type: 'text', value: 'Hidden context' },
+ ]),
+ pending_user_message_id: 'pending-1',
+ },
+ })
+ await expectLogic(logic, () =>
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
+ ).toFinishAllListeners()
+ expect(logic.values.threadItems.filter((item) => item.type === 'human_message')).toEqual([
+ { id: 'pending-run-1-pending-1', type: 'human_message', text: content, complete: true },
+ ])
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ await expectLogic(logic, () =>
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: content },
+ }),
+ readOnly ? 'replay' : 'live'
+ )
+ ).toFinishAllListeners()
+ expect(logic.values.threadItems.filter((item) => item.type === 'human_message')).toEqual([
+ { id: 'human-0', type: 'human_message', text: content, complete: true },
+ ])
+ }
+ )
+
+ it('keeps the selected run pending message even if its ancestor contains identical text', () => {
+ const text = 'Continue with the comparison.'
+ const ancestor = { ...notification('_posthog/user_message', { content: text }), source_run_id: 'ancestor' }
+ const selected = { ...notification('_posthog/user_message', { content: text }), source_run_id: 'run-1' }
+ const options = { isResumeRun: true, pendingMessage: { runId: 'run-1', id: 'pending-1', text } }
+ expect(
+ foldLogToThread([{ entry: ancestor, source: 'replay' }], options).threadItems.filter(
+ (item) => item.type === 'human_message'
+ )
+ ).toHaveLength(2)
+ const items = foldLogToThread(
+ [
+ { entry: ancestor, source: 'replay' },
+ { entry: selected, source: 'replay' },
+ ],
+ options
+ ).threadItems.filter((item) => item.type === 'human_message')
+ expect(items).toHaveLength(2)
+ expect(items.every((item) => item.id.startsWith('human-'))).toBe(true)
+ })
+
// The backend persists the human turn as a session/update `user_message_chunk`, not a
// `_posthog/user_message` ext-notification — this is the frame a thread actually loads from logs.
it('renders a persisted user_message_chunk session update on bootstrap replay', async () => {
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index af70260bd6d1..f6855f42cdd4 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -1044,6 +1044,26 @@ export interface FoldedThread {
toolInvocations: Map<string, ToolInvocation>
}
+export interface PendingRunMessage {
+ runId: string
+ id: string
+ text: string
+}
+
+function readPendingRunMessage(state: unknown, runId: string): PendingRunMessage | null {
+ if (!isRecord(state) || typeof state.pending_user_message !== 'string') {
+ return null
+ }
+ const text = unwrapUserMessageContent(state.pending_user_message)
+ return text
+ ? {
+ runId,
+ id: typeof state.pending_user_message_id === 'string' ? state.pending_user_message_id : runId,
+ text,
+ }
+ : null
+}
+
/**
* Pure projection: fold the ordered log into the rendered thread (and the tool-invocation map the
* renderer looks up). The fold rules (chunk buffering with the tail rule, tool-update merge,
@@ -1051,7 +1071,10 @@ export interface FoldedThread {
* across re-folds. `isResumeRun` drives the §6 resume-context filter; per-entry `source` decides
* whether a wire user turn renders (replay) or is left to the live echo (live).
*/
-export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun: boolean }): FoldedThread {
+export function foldLogToThread(
+ entries: StoredEntry[],
+ options: { isResumeRun: boolean; pendingMessage?: PendingRunMessage | null }
+): FoldedThread {
let items: ThreadItem[] = []
const invocations = new Map<string, ToolInvocation>()
// Texts already rendered by a `_posthog/user_message`, so a later identical `user_message_chunk`
@@ -1069,8 +1092,14 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
let contextSeq = 0
let timestamp: number | undefined
let importedRun = false
+ let entryRunId: string | undefined
+ let pendingMessageSeen = false
+ let pendingInsertionIndex: number | undefined
const pushHuman = (text: string): void => {
+ if (options.pendingMessage?.text === text && entryRunId === options.pendingMessage.runId) {
+ pendingMessageSeen = true
+ }
items = insertHumanMessageAtTurnStart(items, {
id: `human-${humanCount++}`,
type: 'human_message',
@@ -1225,6 +1254,14 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
}
for (const { entry, source } of entries) {
+ entryRunId = entry.source_run_id ?? options.pendingMessage?.runId
+ if (
+ options.pendingMessage &&
+ entryRunId === options.pendingMessage.runId &&
+ pendingInsertionIndex === undefined
+ ) {
+ pendingInsertionIndex = items.length
+ }
const notification = entry.notification
const method = notification.method
const params = (notification.params ?? {}) as Record<string, unknown>
@@ -1436,6 +1473,15 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
}
}
+ if (options.pendingMessage && !pendingMessageSeen) {
+ // This is a display fallback, not an optimistic send; bootstrap must still read the full log.
+ items.splice(pendingInsertionIndex ?? items.length, 0, {
+ id: `pending-${options.pendingMessage.runId}-${options.pendingMessage.id}`,
+ type: 'human_message',
+ text: options.pendingMessage.text,
+ complete: true,
+ })
+ }
return { threadItems: items, toolInvocations: invocations }
}
@@ -1488,6 +1534,7 @@ export interface runStreamLogicValues {
log: RunLog
logBootstrapLoading: boolean
pendingPermissionRequest: PermissionRequestRecord | null
+ pendingRunMessage: PendingRunMessage | null
permissionResponseRequestIds: Set<string>
reconnectAttempt: number
resolvedPermissionRequestIds: Set<string>
@@ -1710,6 +1757,9 @@ export interface runStreamLogicActions {
setCurrentStage: (stage: string | null) => {
stage: string | null
}
+ setPendingRunMessage: (message: PendingRunMessage | null) => {
+ message: PendingRunMessage | null
+ }
setRunOpening: (opening: boolean) => {
opening: boolean
}
@@ -1747,7 +1797,11 @@ export interface runStreamLogicMeta {
permissionResponseRequestIds: Set<string>,
pendingPermissionRequest: PermissionRequestRecord | null
) => boolean
- foldedThread: (log: RunLog, isBootstrapResumeRun: boolean) => FoldedThread
+ foldedThread: (
+ log: RunLog,
+ isBootstrapResumeRun: boolean,
+ pendingRunMessage: PendingRunMessage | null
+ ) => FoldedThread
latestTurnTraceId: (threadItems: ThreadItem[]) => string | null
threadItems: (foldedThread: FoldedThread, showDebugLogs: boolean) => ThreadItem[]
hasThreadItems: (threadItems: ThreadItem[]) => boolean
@@ -1986,6 +2040,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
* `pushHumanMessage`.
*/
startOptimisticRun: (message?: string) => ({ message }),
+ setPendingRunMessage: (message: PendingRunMessage | null) => ({ message }),
startOptimisticResume: (message: string) => ({ message }),
appendResumeBoundary: true,
rollbackOptimisticResume: true,
@@ -2055,6 +2110,14 @@ export const runStreamLogic = kea<runStreamLogicType>([
reset: () => 0,
},
],
+ pendingRunMessage: [
+ null as PendingRunMessage | null,
+ {
+ setPendingRunMessage: (_, { message }) => message,
+ reset: () => null,
+ startOptimisticResume: () => null,
+ },
+ ],
currentRunStatus: [
null as RunStatus | null,
{
@@ -2341,8 +2404,9 @@ export const runStreamLogic = kea<runStreamLogicType>([
* Memoized on `log` identity, so it recomputes only when a frame is actually appended.
*/
foldedThread: [
- (s) => [s.log, s.isBootstrapResumeRun],
- (log: RunLog, isResumeRun: boolean): FoldedThread => foldLogToThread(log.entries, { isResumeRun }),
+ (s) => [s.log, s.isBootstrapResumeRun, s.pendingRunMessage],
+ (log: RunLog, isResumeRun: boolean, pendingMessage: PendingRunMessage | null): FoldedThread =>
+ foldLogToThread(log.entries, { isResumeRun, pendingMessage }),
],
latestTurnTraceId: [
(s) => [s.threadItems],
@@ -2569,6 +2633,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
breakpoint()
actions.markBootstrapResumeRun(isResumeRun(replayRun))
actions.mergeRunArtifacts(extractRunArtifacts(replayRun))
+ actions.setPendingRunMessage(readPendingRunMessage(replayRun.state, runId))
const replayResult = await fetchLogEntriesWithRetry(taskId, runId, breakpoint)
if (!Array.isArray(replayResult)) {
@@ -2626,6 +2691,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
// Flag the run's resume-ness so the projection can drop the synthetic resume-context
// prompt (§6) before any history frame folds.
actions.markBootstrapResumeRun(isResumeRun(run))
+ actions.setPendingRunMessage(readPendingRunMessage(run.state, runId))
// Surface any git artifacts the run already carries (working/base branch, an opened PR)
// so the pre-turn header and post-turn PR card render immediately on reopen.
actions.mergeRunArtifacts(extractRunArtifacts(run))
diff --git a/products/posthog_ai/frontend/logics/runnerPanelLogic.ts b/products/posthog_ai/frontend/logics/runnerPanelLogic.ts
index 0c45899adb51..94f9e2865f71 100644
--- a/products/posthog_ai/frontend/logics/runnerPanelLogic.ts
+++ b/products/posthog_ai/frontend/logics/runnerPanelLogic.ts
@@ -5,6 +5,8 @@ import { MakeLogicType, actions, kea, key, listeners, path, props, reducers, sel
// 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
+ interactionKey?: string
+ composerWasFocused?: boolean
taskId?: string
runId?: string
draft?: string
diff --git a/products/posthog_ai/frontend/logics/taskDraftListeners.ts b/products/posthog_ai/frontend/logics/taskDraftListeners.ts
new file mode 100644
index 000000000000..1649974774e1
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/taskDraftListeners.ts
@@ -0,0 +1,83 @@
+import type { ListenerDefinitions } from 'kea'
+
+import type { runInteractionLogicType } from './runInteractionLogic'
+import { TaskDraftPersistence, type TaskDraftState, taskDraftStorageKey } from './taskDraftPersistence'
+
+export function taskDraftState(logic: runInteractionLogicType): TaskDraftState {
+ return {
+ runId: logic.props.runId,
+ draft: logic.values.composerForm.draft,
+ queuedText: logic.values.queuedMessages.map((message) => message.content).join('\n\n'),
+ recovery: logic.values.draftRecovery,
+ }
+}
+
+export function taskDraftListeners(logic: runInteractionLogicType): ListenerDefinitions<runInteractionLogicType> {
+ const { actions, cache } = logic
+ const save = (): void => {
+ if (!cache.restoringTaskDraft) {
+ const persistence: TaskDraftPersistence | undefined = cache.taskDraftPersistence
+ persistence?.save(taskDraftState(logic))
+ }
+ }
+
+ return {
+ enableTaskDraftPersistence: ({ userId, projectId }: { userId: string; projectId: number }): void => {
+ const previous: { userId: string; projectId: number } | undefined = cache.taskDraftIdentity
+ if (previous && (previous.userId !== userId || previous.projectId !== projectId)) {
+ cache.restoringTaskDraft = true
+ cache.taskDraftPersistence = undefined
+ actions.clearQueue()
+ actions.resetComposerForm()
+ cache.restoringTaskDraft = false
+ }
+ cache.taskDraftIdentity = { userId, projectId }
+ actions.hydrateTaskDraft()
+ },
+ hydrateTaskDraft: ({ taskId }: { taskId?: string }): void => {
+ if (taskId) {
+ cache.taskDraftTaskId = taskId
+ }
+ const identity: { userId: string; projectId: number } | undefined = cache.taskDraftIdentity
+ const savedTaskId = logic.props.taskId || cache.taskDraftTaskId
+ if (!identity || !savedTaskId) {
+ return
+ }
+ const key = taskDraftStorageKey(identity.userId, identity.projectId, savedTaskId)
+ if (cache.taskDraftPersistence?.key === key) {
+ return
+ }
+ const persistence = new TaskDraftPersistence(key)
+ cache.taskDraftPersistence = persistence
+ const state = taskDraftState(logic)
+ // An optimistic handoff already owns its queue; only a fresh composer recovers as a draft.
+ if (!state.draft && !state.queuedText) {
+ const restored = persistence.restore()
+ if (restored?.draft) {
+ cache.restoringTaskDraft = true
+ actions.setDraftRecovery(restored.recovery)
+ actions.setComposerFormValues({ draft: restored.draft })
+ cache.restoringTaskDraft = false
+ }
+ }
+ save()
+ },
+ persistTaskDraft: save,
+ beginTaskDraftDelivery: ({ content }: { content: string }): void => {
+ const persistence: TaskDraftPersistence | undefined = cache.taskDraftPersistence
+ persistence?.startDelivery(content)
+ },
+ finishTaskDraftDelivery: (): void => {
+ const persistence: TaskDraftPersistence | undefined = cache.taskDraftPersistence
+ persistence?.finishDelivery(taskDraftState(logic))
+ },
+ setComposerFormValue: save,
+ setComposerFormValues: save,
+ resetComposerForm: save,
+ enqueueMessage: save,
+ prependQueuedMessage: save,
+ updateQueuedMessage: save,
+ removeQueuedMessage: save,
+ clearQueue: save,
+ }
+}
diff --git a/products/posthog_ai/frontend/logics/taskDraftPersistence.test.ts b/products/posthog_ai/frontend/logics/taskDraftPersistence.test.ts
new file mode 100644
index 000000000000..ffb5bddb02b9
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/taskDraftPersistence.test.ts
@@ -0,0 +1,79 @@
+import { TaskDraftPersistence, TaskDraftState, taskDraftStorageKey } from './taskDraftPersistence'
+
+const key = taskDraftStorageKey('user-1', 997, 'task-1')
+const empty: TaskDraftState = { runId: 'run-1', draft: '', queuedText: '', recovery: null }
+
+describe('task draft persistence', () => {
+ beforeEach(() => localStorage.clear())
+
+ it('recovers an unconfirmed send before the queue and draft, then retains only newer text after acknowledgement', () => {
+ const tab = new TaskDraftPersistence(key)
+ tab.startDelivery('sent first')
+ tab.save({ ...empty, queuedText: 'queued second', draft: 'unfinished third' })
+ expect(new TaskDraftPersistence(key).restore()).toEqual({
+ draft: 'sent first\n\nqueued second\n\nunfinished third',
+ recovery: 'unconfirmed',
+ })
+ tab.finishDelivery({ ...empty, draft: 'unfinished third' })
+ expect(new TaskDraftPersistence(key).restore()).toEqual({ draft: 'unfinished third', recovery: 'restored' })
+ tab.save(empty)
+ expect(new TaskDraftPersistence(key).restore()).toBeNull()
+ })
+
+ it('keeps the latest tab edit when an older send finishes or its unchanged page exits', () => {
+ const olderTab = new TaskDraftPersistence(key)
+ olderTab.startDelivery('sending')
+ olderTab.save(empty)
+ new TaskDraftPersistence(key).save({ ...empty, draft: 'newer tab edit' })
+ olderTab.finishDelivery(empty)
+ olderTab.save(empty)
+ expect(new TaskDraftPersistence(key).restore()?.draft).toBe('newer tab edit')
+ olderTab.save({ ...empty, draft: 'latest edit from the older tab' })
+ expect(new TaskDraftPersistence(key).restore()?.draft).toBe('latest edit from the older tab')
+ })
+
+ it.each([
+ ['user-2', 997, 'task-1'],
+ ['user-1', 998, 'task-1'],
+ ['user-1', 997, 'task-2'],
+ ] as const)('does not restore another identity: %s/%s/%s', (userId, projectId, taskId) => {
+ new TaskDraftPersistence(key).save({ ...empty, draft: 'private draft' })
+ expect(new TaskDraftPersistence(taskDraftStorageKey(userId, projectId, taskId)).restore()).toBeNull()
+ })
+
+ it.each([
+ 'invalid json',
+ JSON.stringify({ version: 0, draft: 'old format' }),
+ JSON.stringify({ version: 1, draft: 123 }),
+ ])('ignores malformed storage: %s', (value) => {
+ localStorage.setItem(key, value)
+ expect(new TaskDraftPersistence(key).restore()).toBeNull()
+ })
+
+ it('expires a draft after seven days', () => {
+ new TaskDraftPersistence(key).save({ ...empty, draft: 'stale draft' })
+ const now = jest.spyOn(Date, 'now').mockReturnValue(Date.now() + 7 * 24 * 60 * 60 * 1000)
+ try {
+ expect(new TaskDraftPersistence(key).restore()).toBeNull()
+ expect(localStorage.getItem(key)).toBeNull()
+ } finally {
+ now.mockRestore()
+ }
+ })
+
+ it('tolerates disabled storage without preventing a send from finishing', () => {
+ const storage = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new DOMException('Storage unavailable', 'QuotaExceededError')
+ })
+ try {
+ const tab = new TaskDraftPersistence(key)
+ expect(() => {
+ tab.startDelivery('sending')
+ tab.save(empty)
+ tab.finishDelivery(empty)
+ }).not.toThrow()
+ } finally {
+ storage.mockRestore()
+ }
+ })
+})
diff --git a/products/posthog_ai/frontend/logics/taskDraftPersistence.ts b/products/posthog_ai/frontend/logics/taskDraftPersistence.ts
new file mode 100644
index 000000000000..48d5d07da269
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/taskDraftPersistence.ts
@@ -0,0 +1,127 @@
+import { v4 as uuid } from 'uuid'
+
+export type DraftRecovery = 'restored' | 'unconfirmed' | null
+
+export interface TaskDraftState {
+ runId: string
+ draft: string
+ queuedText: string
+ recovery: DraftRecovery
+}
+
+interface SavedTaskDraft {
+ version: 1
+ revision: string
+ updatedAt: number
+ runId: string
+ draft: string
+ queuedText: string
+ pendingContent: string
+ deliveryUnconfirmed: boolean
+}
+
+const DRAFT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
+
+export function taskDraftStorageKey(userId: string, projectId: number, taskId: string): string {
+ return `posthog-ai:task-draft:${userId}:${projectId}:${taskId}`
+}
+
+function readDraft(key: string): SavedTaskDraft | null {
+ try {
+ const raw = localStorage.getItem(key)
+ if (!raw) {
+ return null
+ }
+ const value: unknown = JSON.parse(raw)
+ if (
+ typeof value === 'object' &&
+ value !== null &&
+ 'version' in value &&
+ value.version === 1 &&
+ 'revision' in value &&
+ typeof value.revision === 'string' &&
+ 'updatedAt' in value &&
+ typeof value.updatedAt === 'number' &&
+ Number.isFinite(value.updatedAt) &&
+ value.updatedAt <= Date.now() &&
+ Date.now() - value.updatedAt < DRAFT_MAX_AGE_MS &&
+ 'runId' in value &&
+ typeof value.runId === 'string' &&
+ 'draft' in value &&
+ typeof value.draft === 'string' &&
+ 'queuedText' in value &&
+ typeof value.queuedText === 'string' &&
+ 'pendingContent' in value &&
+ typeof value.pendingContent === 'string' &&
+ 'deliveryUnconfirmed' in value &&
+ typeof value.deliveryUnconfirmed === 'boolean'
+ ) {
+ return value as SavedTaskDraft
+ }
+ localStorage.removeItem(key)
+ } catch {
+ // Storage can be unavailable or contain a draft written by an incompatible client.
+ }
+ return null
+}
+
+export class TaskDraftPersistence {
+ private pendingContent = ''
+ private lastSnapshot = ''
+ private revision: string | null = null
+
+ constructor(readonly key: string) {}
+
+ restore(): { draft: string; recovery: DraftRecovery } | null {
+ const saved = readDraft(this.key)
+ if (!saved) {
+ return null
+ }
+ this.revision = saved.revision
+ return {
+ draft: [saved.pendingContent, saved.queuedText, saved.draft].filter(Boolean).join('\n\n'),
+ recovery: saved.deliveryUnconfirmed ? 'unconfirmed' : 'restored',
+ }
+ }
+
+ startDelivery(content: string): void {
+ this.pendingContent = content
+ }
+
+ finishDelivery(state: TaskDraftState): void {
+ this.pendingContent = ''
+ this.save(state, true)
+ }
+
+ save(state: TaskDraftState, onlyIfCurrent = false): void {
+ const snapshot = {
+ runId: state.runId,
+ draft: state.draft,
+ queuedText: state.queuedText,
+ pendingContent: this.pendingContent,
+ deliveryUnconfirmed: !!this.pendingContent || state.recovery === 'unconfirmed',
+ }
+ const serialized = JSON.stringify(snapshot)
+ if (serialized === this.lastSnapshot) {
+ return
+ }
+ this.lastSnapshot = serialized
+ try {
+ // A response from an older tab must not erase a newer tab's edits.
+ if (onlyIfCurrent && readDraft(this.key)?.revision !== this.revision) {
+ return
+ }
+ if (!snapshot.draft && !snapshot.queuedText && !snapshot.pendingContent) {
+ localStorage.removeItem(this.key)
+ this.revision = null
+ return
+ }
+ const revision = uuid()
+ const saved: SavedTaskDraft = { ...snapshot, version: 1, revision, updatedAt: Date.now() }
+ localStorage.setItem(this.key, JSON.stringify(saved))
+ this.revision = revision
+ } catch {
+ // Recovery is best-effort; storage failures must not prevent editing or sending.
+ }
+ }
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx
index 10de090bff30..51a21d2bc2cc 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx
@@ -91,6 +91,7 @@ function SidePanelRunnerContent(): JSX.Element {
taskId={activeCreation.taskId}
runId={activeCreation.runId}
streamKey={activeCreation.streamKey}
+ interactionKey={activeCreation.interactionKey}
onRunStarted={updateActiveCreationRun}
escapeScope="composer"
initialDraft={activeCreation.draft}
@@ -99,7 +100,9 @@ function SidePanelRunnerContent(): JSX.Element {
/>
</div>
) : (
- <StartupRunChat streamKey={activeCreation.streamKey} focusedRef={startupFocusedRef} />
+ <div className="flex-1 min-h-0 px-4">
+ <StartupRunChat streamKey={activeCreation.streamKey} focusedRef={startupFocusedRef} />
+ </div>
)}
</div>
)
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.stories.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.stories.tsx
index 4a9fbbe33816..bf21d5207587 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.stories.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.stories.tsx
@@ -5,18 +5,31 @@ import { useEffect } from 'react'
import { mswDecorator } from '~/mocks/browser'
import { SidePanelRunner } from '../../../components/SidePanelRunner'
+import { runInteractionLogic } from '../../../logics/runInteractionLogic'
import { runStreamLogic } from '../../../logics/runStreamLogic'
import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
-function StartupSidebar(): JSX.Element {
+function StartupSidebar({ narrow = true, queued = false }: { narrow?: boolean; queued?: boolean }): JSX.Element {
const { setActiveCreation } = useActions(taskTrackerSceneLogic({ panelId: 'startup-story' }))
const { startOptimisticRun } = useActions(runStreamLogic({ streamKey: 'startup-story' }))
+ const { enqueueMessage } = useActions(
+ runInteractionLogic({
+ taskId: '',
+ runId: '',
+ streamKey: 'startup-story',
+ interactionKey: 'startup-story',
+ currentRuntimeAdapter: 'claude',
+ })
+ )
useEffect(() => {
- setActiveCreation({ streamKey: 'startup-story' })
+ setActiveCreation({ streamKey: 'startup-story', interactionKey: 'startup-story' })
startOptimisticRun('Explain how to measure weekly active users.')
- }, [setActiveCreation, startOptimisticRun])
+ if (queued) {
+ enqueueMessage('Include a monthly comparison and explain how to interpret the result.')
+ }
+ }, [setActiveCreation, startOptimisticRun, enqueueMessage, queued])
return (
- <div className="flex h-160 w-100 flex-col border rounded bg-surface-primary">
+ <div className={`flex h-160 flex-col border rounded bg-surface-primary ${narrow ? 'w-100' : 'w-180'}`}>
<div className="px-4 py-3 font-semibold">PostHog AI</div>
<div className="flex-1 min-h-0">
<SidePanelRunner panelId="startup-story" />
@@ -44,3 +57,5 @@ const meta: Meta = {
export default meta
export const Sidebar: StoryObj = {}
+export const QueuedSidebar: StoryObj = { render: () => <StartupSidebar queued /> }
+export const QueuedWide: StoryObj = { render: () => <StartupSidebar queued narrow={false} /> }
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsx
index 2add57410039..53a8fcb3259e 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsx
@@ -1,65 +1,70 @@
-import { useActions, useValues } from 'kea'
+import { BindLogic, useActions, useValues } from 'kea'
import { type MutableRefObject, useRef } from 'react'
-import { Composer } from 'products/posthog_ai/frontend/api/primitives'
import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'
-import { RunEscapeBoundary } from '../../../components/RunEscapeBoundary'
-import { runCancellationLogic } from '../../../logics/runCancellationLogic'
+import { RunEscapeBoundary, type RunEscapeBoundaryProps } from '../../../components/RunEscapeBoundary'
+import { runInteractionLogic, type RunInteractionLogicProps } from '../../../logics/runInteractionLogic'
import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
+import { TaskRunComposer } from './TaskRunComposer'
export function StartupRunChat({
streamKey,
focusedRef,
+ escapeScope = 'composer',
}: {
streamKey: string
- focusedRef: MutableRefObject<boolean>
+ focusedRef?: MutableRefObject<boolean>
+ escapeScope?: RunEscapeBoundaryProps['scope']
}): JSX.Element {
const textAreaRef = useRef<HTMLTextAreaElement>(null)
+ const flushDraftRef = useRef<() => void>(() => {})
const { activeCreation } = useValues(taskTrackerSceneLogic)
- const { setStartupDraft } = useActions(taskTrackerSceneLogic)
- const { requestCancellation } = useActions(runCancellationLogic({ streamKey }))
- const { cancellationState } = useValues(runCancellationLogic({ streamKey }))
+ const logicProps: RunInteractionLogicProps = {
+ taskId: activeCreation?.taskId ?? '',
+ runId: activeCreation?.runId ?? '',
+ streamKey,
+ interactionKey: streamKey,
+ flushDraft: () => flushDraftRef.current(),
+ }
+ const interaction = runInteractionLogic(logicProps)
+ const { handleEscape } = useActions(interaction)
+ const { cancellationState } = useValues(interaction)
return (
- <RunEscapeBoundary
- scope="composer"
- focusKey={streamKey}
- textAreaRef={textAreaRef}
- onEscape={requestCancellation}
- className="@container/thread flex flex-col flex-1 min-h-0"
- >
+ <BindLogic logic={runInteractionLogic} props={logicProps}>
<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
- className="px-4 pb-4"
- onFocusCapture={() => {
- focusedRef.current = true
- }}
- onBlurCapture={() => {
- focusedRef.current = false
- }}
- >
- <Composer.Root
+ <RunEscapeBoundary
+ scope={escapeScope}
+ focusKey={streamKey}
textAreaRef={textAreaRef}
- value={activeCreation?.draft ?? ''}
- onChange={setStartupDraft}
- onSubmit={() => {}}
- disabledReason="Wait for the run to start"
- stopLoading={!!cancellationState}
- isTurnActive
- onStop={requestCancellation}
+ onEscape={handleEscape}
+ className="@container/thread flex flex-col flex-1 h-full min-h-0 -mx-4"
>
- <Composer.Frame>
- <Composer.Field>
- <Composer.Placeholder>Send a follow-up message…</Composer.Placeholder>
- <Composer.Textarea data-attr="sandbox-composer-input" autoFocus />
- </Composer.Field>
- </Composer.Frame>
- <Composer.Submit data-attr="sandbox-composer-send" />
- </Composer.Root>
- </div>
- </RunEscapeBoundary>
+ <RunSurface.Thread className="flex-1 min-h-0" listClassName="py-4" rowClassName="px-4" />
+ <RunSurface.Composer isStopping={!!cancellationState}>
+ <div
+ onFocusCapture={() => {
+ if (focusedRef) {
+ focusedRef.current = true
+ }
+ }}
+ onBlurCapture={() => {
+ if (focusedRef) {
+ focusedRef.current = false
+ }
+ }}
+ >
+ <TaskRunComposer
+ logicProps={interaction.props}
+ textAreaRef={textAreaRef}
+ flushDraftRef={flushDraftRef}
+ autoFocus
+ />
+ </div>
+ </RunSurface.Composer>
+ </RunEscapeBoundary>
+ </RunSurface.Root>
+ </BindLogic>
)
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx
index 5a6f55dcb884..6e07f9e2102a 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx
@@ -1,12 +1,4 @@
-import { useActions, useValues } from 'kea'
-
-import { IconStopFilled } from '@posthog/icons'
-import { LemonButton } from '@posthog/lemon-ui'
-
-import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'
-
-import { RunEscapeBoundary } from '../../../components/RunEscapeBoundary'
-import { runCancellationLogic } from '../../../logics/runCancellationLogic'
+import { StartupRunChat } from './StartupRunChat'
import { TaskRunSceneShell } from './TaskRunSceneShell'
export interface TaskCreateThreadProps {
@@ -26,8 +18,6 @@ export interface TaskCreateThreadProps {
* detail page, which adopts the same seeded stream so only the continuous thread underneath persists.
*/
export function TaskCreateThread({ streamKey, isMobile }: TaskCreateThreadProps): JSX.Element {
- const { requestCancellation } = useActions(runCancellationLogic({ streamKey }))
- const { cancellationState } = useValues(runCancellationLogic({ streamKey }))
return (
<TaskRunSceneShell
task={null}
@@ -38,27 +28,7 @@ export function TaskCreateThread({ streamKey, isMobile }: TaskCreateThreadProps)
onRetry={() => {}}
isMobile={isMobile}
>
- <RunEscapeBoundary
- scope="chat"
- focusKey={streamKey}
- onEscape={requestCancellation}
- 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 className="flex justify-end px-4 pb-4">
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconStopFilled />}
- onClick={requestCancellation}
- loading={!!cancellationState}
- tooltip={cancellationState ? 'Stopping…' : 'Stop'}
- data-attr="run-startup-stop"
- />
- </div>
- </RunEscapeBoundary>
+ <StartupRunChat streamKey={streamKey} escapeScope="chat" />
</TaskRunSceneShell>
)
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
index f2cb1197e1fd..05e342417014 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
@@ -106,7 +106,13 @@ export function TaskDetailPage({ taskId, isMobile }: TaskDetailPageProps): JSX.E
onRetry={loadTask}
isMobile={isMobile}
>
- <TaskRunLog taskId={taskId} optimisticStreamKey={optimisticStreamKey} optimisticRunId={optimisticRunId} />
+ <TaskRunLog
+ taskId={taskId}
+ optimisticStreamKey={optimisticStreamKey}
+ optimisticRunId={optimisticRunId}
+ interactionKey={isActiveCreation ? activeCreation?.interactionKey : undefined}
+ autoFocus={isActiveCreation && activeCreation?.composerWasFocused}
+ />
</TaskRunSceneShell>
)
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
index 6a38df7501ae..2e0aef5816b0 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
@@ -1,32 +1,20 @@
import { BindLogic, useActions, useValues } from 'kea'
-import { router } from 'kea-router'
-import { type MutableRefObject, type RefObject, useEffect, useRef } from 'react'
+import { type MutableRefObject, useEffect, useRef } from 'react'
-import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
-import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { runInteractionLogic, type RunInteractionLogicProps } from 'products/posthog_ai/frontend/api/logics'
-import { Composer, QueuedMessageList } from 'products/posthog_ai/frontend/api/primitives'
// Eager, NOT the lazy `api/readableRun` facade: the runner scene is already a route-split chunk and the run
// surface is its primary content, so a second `lazy()` would only add a redundant chunk fetch + Suspense
// flash. The inbox embeds keep the lazy `ReadonlyRunSurface`.
import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'
-import { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCatalogueLogic'
-import { taskRunDefaultsLogic } from 'products/posthog_ai/frontend/logics/taskRunDefaultsLogic'
-import { getRuntimeAdapterForModel } from 'products/posthog_ai/frontend/utils/composerModels'
-import { cycleMode, getModesForRuntimeAdapter } from 'products/posthog_ai/frontend/utils/composerModes'
-import { AttachedContextBar } from '../../../components/composer/AttachedContextBar'
-import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'
-import { ComposerModePicker } from '../../../components/composer/ComposerModePicker'
-import { ComposerModeShortcut } from '../../../components/composer/ComposerModeShortcut'
-import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'
import { RunEscapeBoundary, type RunEscapeBoundaryProps } from '../../../components/RunEscapeBoundary'
import { useForegroundStream } from '../../../hooks/useForegroundStream'
import { runCancellationLogic } from '../../../logics/runCancellationLogic'
import type { RunContinuationHandoff } from '../../../logics/runInteractionLogic'
import { taskDetailSceneLogic } from '../taskDetailSceneLogic'
+import { TaskRunComposer } from './TaskRunComposer'
export interface TaskRunChatProps {
taskId: string
@@ -37,6 +25,7 @@ export interface TaskRunChatProps {
* fresh one. Passed to both `RunSurface.Root` and `runInteractionLogic` so they never diverge.
*/
streamKey?: string
+ interactionKey?: string
/** Called after a fresh run starts, in addition to the `taskDetailSceneLogic` re-pointing below. */
onRunStarted?: (runId: string, handoff?: RunContinuationHandoff) => void
escapeScope?: RunEscapeBoundaryProps['scope']
@@ -57,6 +46,7 @@ export function TaskRunChat({
taskId,
runId,
streamKey,
+ interactionKey,
onRunStarted,
escapeScope = 'chat',
initialDraft,
@@ -74,23 +64,30 @@ export function TaskRunChat({
// — the side panel opens `task.latest_run` while the page follows a `?runId=` link or a newer run. Read
// the run's setup only when the two agree; a mismatch would launch the successor on another run's config.
const runConfig = selectedRun?.id === runId ? selectedRun : undefined
+ const pendingInteraction = interactionKey ? runInteractionLogic.findMounted(interactionKey) : undefined
const logicProps: RunInteractionLogicProps = {
taskId,
runId,
streamKey,
+ interactionKey,
initialDraft,
onDraftAdopted,
flushDraft: () => flushDraftRef.current(),
currentModel:
- runConfig?.model ?? (typeof runConfig?.state?.model === 'string' ? runConfig.state.model : undefined),
+ runConfig?.model ??
+ (typeof runConfig?.state?.model === 'string'
+ ? runConfig.state.model
+ : pendingInteraction?.props.currentModel),
currentEffort:
runConfig?.reasoning_effort ??
- (typeof runConfig?.state?.reasoning_effort === 'string' ? runConfig.state.reasoning_effort : undefined),
+ (typeof runConfig?.state?.reasoning_effort === 'string'
+ ? runConfig.state.reasoning_effort
+ : pendingInteraction?.props.currentEffort),
currentMode:
typeof runConfig?.state?.initial_permission_mode === 'string'
? runConfig.state.initial_permission_mode
- : undefined,
- currentRuntimeAdapter: runConfig?.runtime_adapter,
+ : pendingInteraction?.props.currentMode,
+ currentRuntimeAdapter: runConfig?.runtime_adapter ?? pendingInteraction?.props.currentRuntimeAdapter,
onRunStarted: (newRunId, handoff) => {
if (handoff) {
continueWithRun(handoff)
@@ -165,7 +162,7 @@ function TaskRunChatContent({
<RunSurface.Composer isStopping={!!cancellationState}>
{/* The composer owns the per-keystroke draft in an isolated child so typing never re-renders
the thread/virtualizer rendered as its sibling above — that cascade is what made the input lag. */}
- <LiveComposer
+ <TaskRunComposer
logicProps={logicProps}
textAreaRef={textAreaRef}
autoFocus={autoFocus}
@@ -177,137 +174,3 @@ function TaskRunChatContent({
</RunSurface.Root>
)
}
-
-function LiveComposer({
- logicProps,
- textAreaRef,
- autoFocus,
- flushDraftRef,
-}: {
- logicProps: RunInteractionLogicProps
- textAreaRef: RefObject<HTMLTextAreaElement>
- autoFocus?: boolean
- flushDraftRef: MutableRefObject<() => void>
-}): JSX.Element {
- const {
- composerForm,
- isSubmitting,
- isBusy,
- queuedMessages,
- isTerminal,
- selectedModel,
- defaultModel,
- selectedEffort,
- consentBlocked,
- selectedMode,
- composerActive,
- steerPending,
- cancellationState,
- } = useValues(runInteractionLogic(logicProps))
- const { catalogue } = useValues(modelCatalogueLogic)
- const { myConfigLoading } = useValues(taskRunDefaultsLogic)
- // A live run's harness is whatever it booted on; once terminal the next run follows the picked model.
- const composerAdapter = logicProps.currentRuntimeAdapter ?? getRuntimeAdapterForModel(catalogue, selectedModel)
- const {
- setComposerFormValues,
- submitComposerForm,
- requestCancellation,
- updateQueuedMessage,
- removeQueuedMessage,
- setModel,
- setEffort,
- clearConsentBlock,
- setMode,
- steerQueue,
- submitAfterConsent,
- } = useActions(runInteractionLogic(logicProps))
-
- const draft = useDebouncedDraft(composerForm.draft, (value) => setComposerFormValues({ draft: value }))
- useEffect(() => {
- flushDraftRef.current = draft.flush
- }, [flushDraftRef, draft.flush])
-
- return (
- <>
- <ComposerModeShortcut
- disabled={!composerActive}
- onCycle={() => setMode(cycleMode(composerAdapter, selectedMode))}
- />
- <Composer.Root
- textAreaRef={textAreaRef}
- value={draft.value}
- onChange={draft.onChange}
- onSubmit={() =>
- draft.submit(() => {
- submitComposerForm()
- return runInteractionLogic(logicProps).values.composerForm.draft
- })
- }
- loading={isSubmitting}
- stopLoading={!!cancellationState}
- isTurnActive={isBusy}
- onStop={requestCancellation}
- >
- {queuedMessages.length > 0 && (
- <Composer.Banner>
- <QueuedMessageList
- messages={queuedMessages}
- onUpdate={updateQueuedMessage}
- onRemove={removeQueuedMessage}
- onSteer={steerQueue}
- steerPending={steerPending || !!cancellationState}
- />
- </Composer.Banner>
- )}
- <Composer.Frame>
- <Composer.Header>
- <AttachedContextBar />
- </Composer.Header>
- <Composer.Field>
- <Composer.Placeholder>
- {isTerminal ? 'Send a message to start a new run…' : 'Send a follow-up message…'}
- </Composer.Placeholder>
- <Composer.Textarea data-attr="sandbox-composer-input" autoFocus={autoFocus} />
- </Composer.Field>
- <Composer.Footer className="flex flex-wrap items-center gap-1 pl-2">
- {/* Mode + model/effort pickers: selection lives in the bound runInteractionLogic and is
- applied when the message is sent — synced to the running agent on a follow-up,
- or used to seed the next run once terminal. */}
- <ComposerModePicker
- selectedMode={selectedMode}
- onModeChange={setMode}
- modes={getModesForRuntimeAdapter(composerAdapter)}
- />
- <ComposerModelEffortPickers
- models={catalogue}
- selectedModel={selectedModel}
- defaultModel={defaultModel}
- isDefaultModelLoading={myConfigLoading}
- selectedEffort={selectedEffort}
- onModelChange={setModel}
- onEffortChange={setEffort}
- // While the run is live its harness is fixed to whatever the sandbox booted; once
- // terminal the next send starts a fresh run, which may pick any harness.
- lockedRuntimeAdapter={isTerminal ? null : logicProps.currentRuntimeAdapter}
- onOpenDefaultSettings={() =>
- router.actions.push(
- urls.settings('environment-task-agents', 'task-agent-my-preference')
- )
- }
- />
- </Composer.Footer>
- </Composer.Frame>
- <AIConsentPopoverWrapper
- placement="top-end"
- showArrow
- ignoreDismissal
- hidden={!consentBlocked}
- onApprove={submitAfterConsent}
- onDismiss={() => clearConsentBlock()}
- >
- <Composer.Submit data-attr="sandbox-composer-send" />
- </AIConsentPopoverWrapper>
- </Composer.Root>
- </>
- )
-}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
new file mode 100644
index 000000000000..58d24ef6a221
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
@@ -0,0 +1,183 @@
+import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
+import { type MutableRefObject, type RefObject, useEffect } from 'react'
+
+import { projectLogic } from 'scenes/projectLogic'
+import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
+import { urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
+
+import { runInteractionLogic, type RunInteractionLogicProps } from 'products/posthog_ai/frontend/api/logics'
+import { Composer, QueuedMessageList } from 'products/posthog_ai/frontend/api/primitives'
+import { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCatalogueLogic'
+import { taskRunDefaultsLogic } from 'products/posthog_ai/frontend/logics/taskRunDefaultsLogic'
+import { getRuntimeAdapterForModel } from 'products/posthog_ai/frontend/utils/composerModels'
+import { cycleMode, getModesForRuntimeAdapter } from 'products/posthog_ai/frontend/utils/composerModes'
+
+import { AttachedContextBar } from '../../../components/composer/AttachedContextBar'
+import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'
+import { ComposerModePicker } from '../../../components/composer/ComposerModePicker'
+import { ComposerModeShortcut } from '../../../components/composer/ComposerModeShortcut'
+import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'
+
+export function TaskRunComposer({
+ logicProps,
+ textAreaRef,
+ autoFocus,
+ flushDraftRef,
+}: {
+ logicProps: RunInteractionLogicProps
+ textAreaRef: RefObject<HTMLTextAreaElement>
+ autoFocus?: boolean
+ flushDraftRef: MutableRefObject<() => void>
+}): JSX.Element {
+ const {
+ composerForm,
+ draftRecovery,
+ canSend,
+ isSubmitting,
+ isBusy,
+ queuedMessages,
+ isTerminal,
+ selectedModel,
+ defaultModel,
+ selectedEffort,
+ consentBlocked,
+ selectedMode,
+ composerActive,
+ steerPending,
+ cancellationState,
+ } = useValues(runInteractionLogic(logicProps))
+ const { catalogue } = useValues(modelCatalogueLogic)
+ const { user } = useValues(userLogic)
+ const { currentProjectId } = useValues(projectLogic)
+ const { myConfigLoading } = useValues(taskRunDefaultsLogic)
+ // A live run's harness is whatever it booted on; once terminal the next run follows the picked model.
+ const composerAdapter = logicProps.currentRuntimeAdapter ?? getRuntimeAdapterForModel(catalogue, selectedModel)
+ const controlsReady = isTerminal || !!logicProps.currentRuntimeAdapter
+ const {
+ setComposerFormValues,
+ enableTaskDraftPersistence,
+ setComposerFocused,
+ submitComposerForm,
+ requestCancellation,
+ updateQueuedMessage,
+ removeQueuedMessage,
+ setModel,
+ setEffort,
+ clearConsentBlock,
+ setMode,
+ steerQueue,
+ submitAfterConsent,
+ } = useActions(runInteractionLogic(logicProps))
+
+ useEffect(() => {
+ if (user?.uuid && currentProjectId !== null) {
+ enableTaskDraftPersistence(user.uuid, currentProjectId)
+ }
+ }, [user?.uuid, currentProjectId, enableTaskDraftPersistence])
+
+ const draft = useDebouncedDraft(composerForm.draft, (value) => setComposerFormValues({ draft: value }))
+ useEffect(() => {
+ flushDraftRef.current = draft.flush
+ }, [flushDraftRef, draft.flush])
+
+ return (
+ <div onFocusCapture={() => setComposerFocused(true)} onBlurCapture={() => setComposerFocused(false)}>
+ <ComposerModeShortcut
+ disabled={!composerActive || !controlsReady}
+ onCycle={() => setMode(cycleMode(composerAdapter, selectedMode))}
+ />
+ <Composer.Root
+ textAreaRef={textAreaRef}
+ value={draft.value}
+ onChange={draft.onChange}
+ onSubmit={() =>
+ draft.submit(() => {
+ submitComposerForm()
+ return runInteractionLogic(logicProps).values.composerForm.draft
+ })
+ }
+ loading={isSubmitting}
+ stopLoading={!!cancellationState}
+ isTurnActive={isBusy}
+ onStop={requestCancellation}
+ >
+ {draftRecovery && composerForm.draft && (
+ <Composer.Banner>
+ <p className="text-xs text-muted px-2 mb-2" data-attr="task-draft-restored">
+ {draftRecovery === 'unconfirmed'
+ ? "Delivery wasn't confirmed. Check the conversation before sending again."
+ : 'Draft restored. Review it before sending.'}
+ </p>
+ </Composer.Banner>
+ )}
+ {queuedMessages.length > 0 && (
+ <Composer.Banner>
+ <QueuedMessageList
+ messages={queuedMessages}
+ onUpdate={updateQueuedMessage}
+ onRemove={removeQueuedMessage}
+ onSteer={steerQueue}
+ steerDisabledReason={!canSend && !isSubmitting ? 'Wait for the agent to start' : undefined}
+ steerPending={steerPending || isSubmitting || !!cancellationState}
+ />
+ </Composer.Banner>
+ )}
+ <Composer.Frame>
+ <Composer.Header>
+ <AttachedContextBar />
+ </Composer.Header>
+ <Composer.Field>
+ <Composer.Placeholder>
+ {isTerminal ? 'Send a message to start a new run…' : 'Send a follow-up message…'}
+ </Composer.Placeholder>
+ <Composer.Textarea data-attr="sandbox-composer-input" autoFocus={autoFocus} />
+ </Composer.Field>
+ <Composer.Footer className="flex flex-wrap items-center gap-1 pl-2">
+ <fieldset
+ disabled={!controlsReady}
+ className="flex flex-wrap items-center gap-1 border-0 p-0 m-0 min-w-0"
+ >
+ {/* Mode + model/effort pickers: selection lives in the bound runInteractionLogic and is
+ applied when the message is sent — synced to the running agent on a follow-up,
+ or used to seed the next run once terminal. */}
+ <ComposerModePicker
+ selectedMode={selectedMode}
+ onModeChange={setMode}
+ modes={getModesForRuntimeAdapter(composerAdapter)}
+ />
+ <ComposerModelEffortPickers
+ models={catalogue}
+ selectedModel={selectedModel}
+ defaultModel={defaultModel}
+ isDefaultModelLoading={myConfigLoading}
+ selectedEffort={selectedEffort}
+ onModelChange={setModel}
+ onEffortChange={setEffort}
+ // While the run is live its harness is fixed to whatever the sandbox booted; once
+ // terminal the next send starts a fresh run, which may pick any harness.
+ lockedRuntimeAdapter={isTerminal ? null : logicProps.currentRuntimeAdapter}
+ onOpenDefaultSettings={() =>
+ router.actions.push(
+ urls.settings('environment-task-agents', 'task-agent-my-preference')
+ )
+ }
+ />
+ </fieldset>
+ </Composer.Footer>
+ </Composer.Frame>
+ <AIConsentPopoverWrapper
+ placement="top-end"
+ showArrow
+ ignoreDismissal
+ hidden={!consentBlocked}
+ onApprove={submitAfterConsent}
+ onDismiss={() => clearConsentBlock()}
+ >
+ <Composer.Submit data-attr="sandbox-composer-send" />
+ </AIConsentPopoverWrapper>
+ </Composer.Root>
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsx
index e7b353b2d535..9185139c6982 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsx
@@ -18,12 +18,16 @@ export function TaskRunLog({
taskId,
optimisticStreamKey,
optimisticRunId,
+ interactionKey,
+ autoFocus,
}: {
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
+ interactionKey?: string
+ autoFocus?: boolean
}): JSX.Element | null {
const logic = taskDetailSceneLogic({ taskId })
const {
@@ -59,7 +63,13 @@ export function TaskRunLog({
if (optimisticStreamKey && effectiveRunId) {
return (
<div className="flex-1 min-h-0">
- <TaskRunChat taskId={taskId} runId={effectiveRunId} streamKey={optimisticStreamKey} />
+ <TaskRunChat
+ taskId={taskId}
+ runId={effectiveRunId}
+ streamKey={optimisticStreamKey}
+ interactionKey={effectiveRunId === optimisticRunId ? interactionKey : undefined}
+ autoFocus={effectiveRunId === optimisticRunId && autoFocus}
+ />
</div>
)
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
index 23d26bd35add..88fd1b63e5df 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
@@ -13,6 +13,8 @@ import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schema
import { attachedContextLogic, runStreamLogic } from '../../api/logics'
import { composerSeedLogic } from '../../logics/composerSeedLogic'
import { runCancellationLogic } from '../../logics/runCancellationLogic'
+import { runInteractionLogic } from '../../logics/runInteractionLogic'
+import { TaskDraftPersistence, taskDraftStorageKey } from '../../logics/taskDraftPersistence'
import { toolStreamEventsLogic } from '../../logics/toolStreamEventsLogic'
import { OriginProduct, Task, TaskRunEnvironment, TaskRunStatus } from '../../types/taskTypes'
import { taskTrackerSceneLogic } from './taskTrackerSceneLogic'
@@ -54,6 +56,7 @@ describe('taskTrackerSceneLogic', () => {
})
beforeEach(() => {
+ localStorage.clear()
createBody = null
runBody = null
useMocks({
@@ -145,6 +148,8 @@ describe('taskTrackerSceneLogic', () => {
} else {
expect(logic.values.activeCreation).toEqual({
streamKey,
+ interactionKey: streamKey,
+ composerWasFocused: false,
taskId: 'new-task',
runId: 'run-1',
draft: 'A follow-up draft',
@@ -199,13 +204,26 @@ describe('taskTrackerSceneLogic', () => {
logic.actions.submitNewTask()
const streamKey = logic.values.activeCreation!.streamKey
expect(runStreamLogic({ streamKey }).values.streamPhase).toBe('provisioning')
- logic.actions.setStartupDraft('Include a weekly comparison')
+ const interaction = runInteractionLogic.findMounted(streamKey)!
+ interaction.actions.enableTaskDraftPersistence('user-1', 997)
+ interaction.actions.setComposerFormValues({ draft: 'Include a weekly comparison' })
+ interaction.actions.submitComposerForm()
+ interaction.actions.setComposerFormValues({ draft: 'Also include a chart' })
+
+ if (failure !== 'task') {
+ await waitFor(() =>
+ expect(new TaskDraftPersistence(taskDraftStorageKey('user-1', 997, 'new-task')).restore()).toEqual({
+ draft: 'Explain the example chart\n\nInclude a weekly comparison\n\nAlso include a chart',
+ recovery: 'unconfirmed',
+ })
+ )
+ }
await expectLogic(logic, finishRequest).toFinishAllListeners()
expect(logic.values.activeCreation).toBeNull()
expect(logic.values.newTaskData.description).toBe(
- 'Explain the example chart\n\nInclude a weekly comparison'
+ 'Explain the example chart\n\nInclude a weekly comparison\n\nAlso include a chart'
)
expect(logic.values.isSubmittingTask).toBe(false)
expect(router.values.location.pathname).toContain('/tasks/new')
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index ff656549aaea..cb141181893a 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -32,7 +32,7 @@ import { composerSeedLogic } from '../../logics/composerSeedLogic'
import type { ComposerSeed } from '../../logics/composerSeedLogic'
import { modelCatalogueLogic } from '../../logics/modelCatalogueLogic'
import { runCancellationLogic } from '../../logics/runCancellationLogic'
-import type { RunContinuationHandoff } from '../../logics/runInteractionLogic'
+import { runInteractionLogic, type RunContinuationHandoff } from '../../logics/runInteractionLogic'
import { runnerPanelLogic } from '../../logics/runnerPanelLogic'
import type { ActiveCreation } from '../../logics/runnerPanelLogic'
import { taskRunDefaultsLogic } from '../../logics/taskRunDefaultsLogic'
@@ -629,19 +629,32 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
const seededContext = values.contextItems
actions.claimApplyBackTargets(streamKey)
const stream = runStreamLogic({ streamKey })
+ const interaction = runInteractionLogic({
+ taskId: '',
+ runId: '',
+ streamKey,
+ interactionKey: streamKey,
+ currentModel: values.displayModel,
+ currentEffort: values.displayEffort,
+ currentMode: permissionMode,
+ currentRuntimeAdapter:
+ values.isDefaultSelection && !values.defaultRuntimeAdapter ? null : values.composerAdapter,
+ })
cache.disposables.add(
() => {
const cancellation = runCancellationLogic({ streamKey })
const unmount = cancellation.mount()
+ const unmountInteraction = interaction.mount()
return () => {
cancellation.actions.clearCancellation()
+ unmountInteraction()
unmount()
}
},
'active-creation',
{ pauseOnPageHidden: false }
)
- actions.setActiveCreation({ streamKey })
+ actions.setActiveCreation({ streamKey, interactionKey: streamKey })
stream.actions.startOptimisticRun(description)
try {
@@ -704,6 +717,13 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// since the Run it points at is the one the create just activated.
actions.consumeWarm()
+ if (!disposables.isDisposed && values.activeCreation?.streamKey === streamKey) {
+ interaction.props.flushDraft?.()
+ interaction.actions.hydrateTaskDraft(newTask.id)
+ interaction.actions.beginTaskDraftDelivery(description)
+ interaction.actions.persistTaskDraft()
+ }
+
// `latest_run` set means the create matched an idling warm Run and activated it in place,
// with `pending_user_message` as turn 1. Creating a second Run here would strand that warm
// sandbox and cold-boot another one.
@@ -711,13 +731,15 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// Otherwise auto-run the task; 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).
- let runId = newTask.latest_run?.id
+ let createdRun = newTask.latest_run
+ let runId = createdRun?.id
if (!runId) {
const runResponse = await submitWithWarmRunRetry(
(options) => tasksRunCreate(projectId, newTask.id, runRequest, options),
disposables
)
- runId = runResponse.latest_run?.id
+ createdRun = runResponse.latest_run
+ runId = createdRun?.id
}
if (disposables.isDisposed) {
@@ -736,10 +758,29 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
const creationIsActive = values.activeCreation?.streamKey === streamKey
if (creationIsActive) {
+ interaction.props.flushDraft?.()
+ interaction.actions.finishTaskDraftDelivery()
+ runInteractionLogic({
+ ...interaction.props,
+ taskId: newTask.id,
+ runId,
+ currentModel: createdRun?.model ?? interaction.props.currentModel,
+ currentEffort: createdRun?.reasoning_effort ?? interaction.props.currentEffort,
+ currentMode:
+ typeof createdRun?.state?.initial_permission_mode === 'string'
+ ? createdRun.state.initial_permission_mode
+ : interaction.props.currentMode,
+ currentRuntimeAdapter: createdRun?.runtime_adapter ?? interaction.props.currentRuntimeAdapter,
+ })
// 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 })
+ actions.setActiveCreation({
+ streamKey,
+ taskId: newTask.id,
+ runId,
+ composerWasFocused: interaction.values.composerFocused,
+ })
// An embedded instance (`panelId` set) keeps the run in place because the host renders
// `activeCreation` instead of navigating the main app to the `/tasks/:id` detail page.
if (!props.panelId) {
@@ -764,9 +805,16 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
}
actions.releaseApplyBackTargets(streamKey)
if (values.activeCreation?.streamKey === streamKey) {
- const draft = values.activeCreation.draft
- if (draft) {
- actions.setNewTaskData({ description: [values.newTaskData.description, draft].join('\n\n') })
+ interaction.props.flushDraft?.()
+ const unsent = [
+ ...interaction.values.queuedMessages.map((message) => message.content),
+ interaction.values.composerForm.draft,
+ values.activeCreation.draft,
+ ].filter(Boolean)
+ if (unsent.length > 0) {
+ actions.setNewTaskData({
+ description: [values.newTaskData.description, ...unsent].join('\n\n'),
+ })
}
actions.clearActiveCreation()
}
@@ -799,6 +847,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
}
actions.setActiveCreation({
streamKey: handoff?.streamKey ?? values.activeCreation.streamKey,
+ interactionKey: undefined,
taskId: values.activeCreation.taskId,
runId,
draft: handoff?.draft ?? values.activeCreation.draft,