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): stop the composer queue swallowing follow-ups (#105740)

Vojta Bartoš84ebde9e18fb
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 14708937421d..462d3af7e88b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6533,9 +6533,9 @@ snapshots:
products-posthog-ai-composer--with-slash-commands--light:
hash: v1.k794b7964.6b8e440643d6eb0eb60c9a885df9f83ac28d3b3453a5c2f6de6482a0f338aa11.3Q0FXWPH9ccU3rvUz5NsKDwW1TYNyc0Id46_MQU30lg
products-posthog-ai-composer--with-up-next-queue--dark:
- hash: v1.k794b7964.e893edaa31202a96439233ff254af446b1ae72107ca4d187a0ab27abc87db8ac.ClRtYW3AIl8tt8UNlaLx_52ymgYxs4FUUHPusEIzAs8
+ hash: v1.k794b7964.563c987f4fed1042fce5351ec93e9e1d2912fc4ae6113b4e6094ea169f44a3a8.II9-hW26nHjWbT0tJS8mDPeb-cr2tmhwxpwkePElrzs
products-posthog-ai-composer--with-up-next-queue--light:
- hash: v1.k794b7964.c6aa2aa587283120fba069845efe3f499ad93f57f01a44fe60714bf6de06aa77.sXADx8Z_E97Ez10RF94ejn6saVtul9mmzMW6g6F-M8U
+ hash: v1.k794b7964.0e83b3f4cf50e720a0a875329373ae3ed4d107ca2347ad1117ed5797ad9343ae.Kz7lcZjYOHsWZJaf464mkjYQC94dec-e3ISY-RNzBuw
products-posthog-ai-debuglogsmenu--non-staff--dark:
hash: v1.k794b7964.8fbc222393e4a977c643005d53ec8b83d55ee078f87f00dc53e4a2422df58f16.HSRv6p696X41lVON7tvCZSWNH-xgjRDLiMUZjwHmuFk
products-posthog-ai-debuglogsmenu--non-staff--light:
@@ -6604,18 +6604,22 @@ snapshots:
hash: v1.k794b7964.4313fbb59e762d6fc4a87fed828bb6c814697c489997e23111f95df3d84be347.VRvN01m1Gf36IcNO8lzu8q3mqxKWwSRROgPqtbxMiSU
products-posthog-ai-queuedmessagelist--empty--light:
hash: v1.k794b7964.8ff99b0d11642dd53f5f0f70fc69106ee0e0158728fd6a73cf8699c4d68f8186.BQuDnKXQn4DwravdDwbmq3GC_BR06D3nntvW0bDvyzE
+ products-posthog-ai-queuedmessagelist--held--dark:
+ hash: v1.k794b7964.2d66446284f130978b3290d7b3562839ead19cf4533ec7f9fc49e154261a7e44.zUN-L242xFuvmgjcGFJF4wzS_hS1KQhFfVLFBkxhXHc
+ products-posthog-ai-queuedmessagelist--held--light:
+ hash: v1.k794b7964.22ceb3b4dc894ff82f41e975b5fc7d4629659961900e3701eebc5c3502273233.iL8GeYKEdNPHfvd0d6k_QpLobW9yCS4iXEjLGOJBP2o
products-posthog-ai-queuedmessagelist--multiple--dark:
- hash: v1.k794b7964.3eda7962450082ad7e2ccb00419d73cde05964c67ce755414b11e1e4aea1aa8d.sccBMURl0uxdRk2-I_rbzScJQpUb8YMXKogdqgDEen0
+ hash: v1.k794b7964.944199db52c0297f3eb56cd1df476f976e11d8e224afbd556ec4864c7cffb324.hDBgtSt7QWpeqbEcIvPWWLh_a8mBMXy12Ia6tP6XWUM
products-posthog-ai-queuedmessagelist--multiple--light:
- hash: v1.k794b7964.b8f2bbbd52d9d6d9cf037064a8006404e4baa16713f6cfd83dada357d174228c.R1y2GmsWYktkzIyDfTGX3pFYKv-wSUj7SrIVfUA93NU
+ hash: v1.k794b7964.c3da4a630f7959b3ce1e239f475abd30d970902171d646be3544cf2afab518eb.ae3hUPyrrOihGnKMB_jQLgg8jwdauUyCbvwpnz58wCc
products-posthog-ai-queuedmessagelist--single--dark:
- hash: v1.k794b7964.dc7887592adb4bd52e26bc40b2b7d91b4f0bb30b734313a8ca4dbf51a90eba20.jQksRkqZoUKTRLj-qr3x369OJW5x1-VvIqARTVLdRrU
+ hash: v1.k794b7964.80368927dbcd1b2bacf91e958cf35342ab901ddc90a40c65bfe39572c9391b36.ikAvYkXKx3xPyGuPTiebY04fDhhDRE6x70NkYvZApzw
products-posthog-ai-queuedmessagelist--single--light:
- hash: v1.k794b7964.574947658755ff52ea706341b7733033c27284dcded89cec117e770420947f6b.wYrWBIoHgR8k8p_nv1OqlGzkyyqedwJiMzRaaamjJKA
+ hash: v1.k794b7964.339a3ea55edf48a5cb8b447526b71c2c1ae455dec74346108992c3d3a56b9774.8ECQa3OJ6Wf3sgSnicfH26-VNQBCb5Ny2_YKN_QCgj0
products-posthog-ai-queuedmessagelist--waiting-for-approval--dark:
- hash: v1.k794b7964.c53aea6618dc88c754e0e9f074f439dbc8e11634184680e91b00170e4f681ff5.xLAZFI1s99bnlOuZw2PXahGWRxKTy5vxGa4-n7s_RQs
+ hash: v1.k794b7964.2dfea9c3f0550076760e28ddef424eb6586b3ca184433e40043c2dcb34b54073.WOfpDXq_bwCMkUI0uLMbG8PX9DXLgUFMtT4HQNJdQi8
products-posthog-ai-queuedmessagelist--waiting-for-approval--light:
- hash: v1.k794b7964.84558994ccccfbf6b0479c05e70fa04048ecdb813a76ac4a3e689b3f3d4a3cfd.WdgXqb0eDP9c6glP6UuTXb--spzTGFym3foe4wFyEIg
+ hash: v1.k794b7964.298184ec5314c4a602a008f7f5cf69a9915c5615494ef3b97f921c91b1377678.ydPjkGpjRqR4dR0dp4bEQME2Dv9jkx7KYlKrDe9R75w
products-posthog-ai-runalertactivity--agent-crash--dark:
hash: v1.k794b7964.564c24429f7c7f159a30ac1141bab57edf1a5c2b4664beed27914b0bb045e9b9.ekKvBBwcTcgUDFNqNoufRAs6MjAO_moIm_G0cFYgRek
products-posthog-ai-runalertactivity--agent-crash--light:
@@ -6633,13 +6637,13 @@ snapshots:
products-posthog-ai-runalertactivity--connection-lost-narrow--light:
hash: v1.k794b7964.8555bf34acfd36c149b40599f32ca9aba1e2e746b94e43abea582710b3c2dd3f.a8iigoMwFpLemT0mLL8QoBjdFHkg_IZ1uvvSireyP9U
products-posthog-ai-startup-chat--queued-sidebar--dark:
- hash: v1.k794b7964.64511ab3090bb1c47555f2f66169395314cb6dedfee2bb2cf127bf4022405470.opaLkUHD-RjeY3_kb_5H4veCE0s8Dt-aRo1H5WZPNeU
+ hash: v1.k794b7964.09044ddb515744099eabe2881689812c0586ce88b5165a3849464ddad9b3ae3f.VlpRnuqPgJZC6rVD37-9cjVUD9O6ZZk4kzAfPvIFOqU
products-posthog-ai-startup-chat--queued-sidebar--light:
- hash: v1.k794b7964.e91fc770dfa66746faefb69b53ec2fb74580d620a246c3dcee4fd2d253d9aa89.irPFIkEUZ4AoypYJvAZ59uZvjIXUOFn4C9HyXHQ0GyA
+ hash: v1.k794b7964.81581b9f5819cb15acf16ae5aad14b9473a4aee528125a4ad1e46cf4ad93a82d.XCVMzmQ6kHE_Lw06Q0ZdgJ0zBcxESrvQQ2O5I2HcsnU
products-posthog-ai-startup-chat--queued-wide--dark:
- hash: v1.k794b7964.fba7548a6b2f99684156a97ebcb24427e2d09d340b8db7415d7a1adb08f23f08.PDnSLZW8eyRMhNNz8YZ4LuM0MlTtnL_FiZb4SDaTetM
+ hash: v1.k794b7964.5db40206f864b58e4a84d954fa58639fdec43bc178e008191d410cbeb6053608.cFgGJK6e7olWV45z3ekjUoGPbAMP2EablOmWNqLsACI
products-posthog-ai-startup-chat--queued-wide--light:
- hash: v1.k794b7964.d910e03de15c10ca08b56a953b274b2ac7ccd3f9ad9a6df8203abe522d2c2ebf.fVoRoJVneYM2oa3LCr5Q8Jn0-H2BkPh_GotYHvj-Q7U
+ hash: v1.k794b7964.3c58e032bb08060136074b2e28a01545852b1bccd78271c853ab93e144779a20.15rV0dd31YqWPTEJA0RLfsmsM85DJF3Y5pL5qlaGams
products-posthog-ai-startup-chat--sidebar--dark:
hash: v1.k794b7964.9df1a431eabd0d314ea291036288e31d351d785e5f511f64fcd255ba86c04c16.YtLvYRZ_hIFGA6PPEN-wZgi5tq85gR0OluUYChuz2KU
products-posthog-ai-startup-chat--sidebar--light:
diff --git a/products/posthog_ai/frontend/components/QueuedMessageList.stories.tsx b/products/posthog_ai/frontend/components/QueuedMessageList.stories.tsx
index dc5648590901..b6b242551509 100644
--- a/products/posthog_ai/frontend/components/QueuedMessageList.stories.tsx
+++ b/products/posthog_ai/frontend/components/QueuedMessageList.stories.tsx
@@ -10,7 +10,7 @@ const meta: Meta<typeof QueuedMessageList> = {
title: 'Products/PostHog AI/QueuedMessageList',
component: QueuedMessageList,
tags: ['autodocs'],
- render: ({ messages, steerPending }) => {
+ render: ({ messages, steerPending, held }) => {
const [queue, setQueue] = useState<QueuedMessage[]>(messages)
return (
<div className="max-w-180 mx-auto p-4">
@@ -20,6 +20,7 @@ const meta: Meta<typeof QueuedMessageList> = {
onRemove={(id) => setQueue((q) => q.filter((m) => m.id !== id))}
onSteer={() => setQueue([])}
steerPending={steerPending}
+ held={held}
/>
</div>
)
@@ -38,6 +39,11 @@ export const WaitingForApproval: Story = {
parameters: { testOptions: { waitForLoadersToDisappear: false } },
}
+/** A Stop or a failed send leaves the message staged. Nothing sends it until the user steers it. */
+export const Held: Story = {
+ args: { messages: [{ id: '1', content: 'Also break it down by browser' }], held: true },
+}
+
export const Multiple: Story = {
args: {
messages: [
diff --git a/products/posthog_ai/frontend/components/QueuedMessageList.tsx b/products/posthog_ai/frontend/components/QueuedMessageList.tsx
index f79b948192e0..f1f183681640 100644
--- a/products/posthog_ai/frontend/components/QueuedMessageList.tsx
+++ b/products/posthog_ai/frontend/components/QueuedMessageList.tsx
@@ -1,9 +1,10 @@
import { useEffect, useRef, useState } from 'react'
-import { IconCheck, IconPencil, IconTrash, IconX } from '@posthog/icons'
+import { IconArrowRight, IconCheck, IconChevronDown, IconPencil, IconStack, IconTrash, IconX } from '@posthog/icons'
import { LemonButton, LemonTextArea } from '@posthog/lemon-ui'
import { KeyboardShortcut } from 'lib/components/KeyboardShortcut/KeyboardShortcut'
+import { cn } from 'lib/utils/css-classes'
import type { QueuedMessage } from '../logics/runInteractionLogic'
@@ -14,6 +15,10 @@ export interface QueuedMessageListProps {
onSteer?: () => void
steerPending?: boolean
steerDisabledReason?: string
+ /** The staged messages wait on the user, not on the agent — say so instead of looking like a queue. */
+ held?: boolean
+ /** Reports an open row editor, so the consumer can hold a send that would ship the pre-edit text. */
+ onEditingChange?: (editing: boolean) => void
}
interface QueuedMessageItemProps {
@@ -25,7 +30,7 @@ interface QueuedMessageItemProps {
onRemove: (id: string) => void
}
-/** One staged "Up next" message — read row with edit/remove, or an inline editor. Logic-free (controlled). */
+/** One staged message — read row with edit/remove, or an inline editor. Logic-free (controlled). */
function QueuedMessageItem({
message,
isEditing,
@@ -84,9 +89,9 @@ function QueuedMessageItem({
}
return (
- <div className="group flex items-center gap-2 py-1 px-2 rounded-md hover:bg-bg-light">
- <p className="flex-1 text-sm text-secondary truncate mb-0">{message.content}</p>
- <div className="flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
+ <div className="flex items-center gap-2 py-1 px-2 rounded-md border border-primary bg-surface-primary">
+ <p className="flex-1 text-sm truncate mb-0">{message.content}</p>
+ <div className="flex gap-0.5">
<LemonButton
size="xsmall"
type="tertiary"
@@ -107,8 +112,8 @@ function QueuedMessageItem({
}
/**
- * The editable "Up next" buffer rendered above the composer while the agent is busy. Purely presentational
- * (no kea): the consumer owns the queue state and passes `onUpdate` / `onRemove`. Modeled on PostHog AI's
+ * The editable queue rendered above the composer while the agent is busy. Purely presentational (no kea):
+ * the consumer owns the queue state and passes `onUpdate` / `onRemove`. Modeled on PostHog AI's
* `QueuedMessageItem`, minus the conversation/Max coupling.
*/
export function QueuedMessageList({
@@ -118,48 +123,88 @@ export function QueuedMessageList({
onSteer,
steerPending = false,
steerDisabledReason,
+ held = false,
+ onEditingChange,
}: QueuedMessageListProps): JSX.Element | null {
const [editingId, setEditingId] = useState<string | null>(null)
+ const [collapsed, setCollapsed] = useState(false)
+ // A row can leave while its editor is open — a flush clears the queue, and the consumer may drop a row
+ // of its own. Holding a stale id would keep the send button disabled against an editor nobody can see.
+ const editing = editingId !== null && messages.some((message) => message.id === editingId)
+
+ useEffect(() => {
+ onEditingChange?.(editing)
+ }, [editing, onEditingChange])
if (messages.length === 0) {
return null
}
return (
- <div className="flex flex-col gap-0.5 pb-2">
- <div className="flex flex-wrap items-center justify-between gap-1 px-2">
- <p className="text-xs font-medium text-muted mb-0">Up next</p>
+ <div className="flex flex-col gap-1 pb-2">
+ <div className="flex flex-wrap items-center justify-between gap-1">
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ data-attr="run-queue-toggle"
+ // Collapsing hides the editor, so close it first rather than leaving it open off screen.
+ onClick={() => {
+ setCollapsed(!collapsed)
+ setEditingId(null)
+ }}
+ icon={
+ <IconChevronDown
+ className={cn(
+ 'transition-transform duration-150 ease-out motion-reduce:transition-none',
+ collapsed && '-rotate-90'
+ )}
+ />
+ }
+ tooltip={collapsed ? 'Show queued messages' : 'Hide queued messages'}
+ >
+ <span className="flex items-center gap-1.5 text-xs font-medium text-muted">
+ <IconStack />
+ <span data-attr="run-queue-label">
+ {messages.length} queued{held && ', not sent yet'}
+ </span>
+ </span>
+ </LemonButton>
{onSteer && (
<LemonButton
size="xsmall"
- type="tertiary"
+ // The only way forward once the queue is held, so it carries the weight there.
+ type={held ? 'secondary' : 'tertiary'}
+ icon={<IconArrowRight />}
data-attr="run-queue-steer"
onClick={onSteer}
loading={steerPending}
- disabledReason={
- steerDisabledReason ?? (editingId ? 'Save or cancel your edit first' : undefined)
- }
- tooltip="Send queued messages before the turn ends"
+ disabledReason={steerDisabledReason ?? (editing ? 'Save or cancel your edit first' : undefined)}
+ tooltip="Sends without waiting for the agent to finish this turn."
sideIcon={<KeyboardShortcut escape />}
>
- Steer
+ Send now
</LemonButton>
)}
</div>
- {messages.map((message) => (
- <QueuedMessageItem
- key={message.id}
- message={message}
- isEditing={editingId === message.id}
- onEdit={() => setEditingId(message.id)}
- onCancel={() => setEditingId(null)}
- onSave={(id, content) => {
- onUpdate(id, content)
- setEditingId(null)
- }}
- onRemove={onRemove}
- />
- ))}
+ {/* Capped so a fast typist can't grow the banner until it pushes the composer off screen. */}
+ {!collapsed && (
+ <div className="flex flex-col gap-1 max-h-48 overflow-y-auto">
+ {messages.map((message) => (
+ <QueuedMessageItem
+ key={message.id}
+ message={message}
+ isEditing={editingId === message.id}
+ onEdit={() => setEditingId(message.id)}
+ onCancel={() => setEditingId(null)}
+ onSave={(id, content) => {
+ onUpdate(id, content)
+ setEditingId(null)
+ }}
+ onRemove={onRemove}
+ />
+ ))}
+ </div>
+ )}
</div>
)
}
diff --git a/products/posthog_ai/frontend/e2e/run-surface.spec.ts b/products/posthog_ai/frontend/e2e/run-surface.spec.ts
index 10fceb4b81f7..99fcbd3cf3b9 100644
--- a/products/posthog_ai/frontend/e2e/run-surface.spec.ts
+++ b/products/posthog_ai/frontend/e2e/run-surface.spec.ts
@@ -275,7 +275,7 @@ test.describe('Task run surface', () => {
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.getByTestId('run-queue-label')).toBeVisible()
await expect(page.getByText(followUp, { exact: true })).toBeVisible()
let startAgent!: () => void
@@ -326,7 +326,7 @@ test.describe('Task run surface', () => {
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.getByTestId('run-queue-label')).toHaveCount(0)
await expect(page.getByText(firstMessage, { exact: true })).toBeVisible()
startAgent()
@@ -447,7 +447,7 @@ test.describe('Task run surface', () => {
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.getByTestId('run-queue-label')).toBeVisible()
await expect(page.getByText(followUp, { exact: true })).toBeVisible()
await expect(page.getByTestId('run-queue-steer')).toBeDisabled()
await followUpComposer.fill(draft)
@@ -463,7 +463,7 @@ test.describe('Task run surface', () => {
await expect(followUpComposer).toBeVisible()
await followUpComposer.fill(followUp)
await followUpComposer.press('Enter')
- await expect(page.getByText('Up next', { exact: true })).toBeVisible()
+ await expect(page.getByTestId('run-queue-label')).toBeVisible()
await followUpComposer.fill(draft)
finishCreation(true)
@@ -473,14 +473,14 @@ test.describe('Task run surface', () => {
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-label')).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.getByTestId('run-queue-label')).toHaveCount(0)
await expect(page.getByText(followUp, { exact: true })).toHaveCount(1)
await expect(followUpComposer).toHaveValue(draft)
revealMetadata()
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
index 42e8ecc829c2..952703ce3aa9 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
@@ -301,7 +301,8 @@ describe('runInteractionLogic', () => {
expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
expect(tasksWarmResumeCreate).not.toHaveBeenCalled()
expect(pending.values.queuedMessages).toEqual([
- { id: 'queued', content: 'first follow-up\n\nsecond follow-up' },
+ { id: expect.any(String), content: 'first follow-up' },
+ { id: expect.any(String), content: 'second follow-up' },
])
pending.actions.hydrateTaskDraft(TASK_ID)
@@ -342,7 +343,7 @@ describe('runInteractionLogic', () => {
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' }])
+ expect(other.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'another task follow-up' }])
} finally {
unmountOther()
unmount()
@@ -440,7 +441,7 @@ describe('runInteractionLogic', () => {
}).toFinishAllListeners()
expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
expect(logic.values.composerForm.draft).toBe('unsent draft')
- expect(logic.values.queuedMessages).toEqual([{ id: 'queued', content: 'saved message' }])
+ expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'saved message' }])
})
it('sends immediately and echoes the message when the agent is idle', async () => {
@@ -590,14 +591,17 @@ describe('runInteractionLogic', () => {
expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'follow up' }])
})
- it('concatenates follow-ups into a single staged message and flushes it when the turn completes', async () => {
+ it('stages each follow-up on its own row and flushes them as one message when the turn completes', async () => {
setThinking(true)
logic.actions.setComposerFormValues({ draft: 'first' })
logic.actions.submitComposerForm()
logic.actions.setComposerFormValues({ draft: 'second' })
logic.actions.submitComposerForm()
- // A second follow-up concatenates onto the first rather than fanning out into a separate message.
- expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'first\n\nsecond' }])
+ // Each follow-up keeps its own row, so the user can edit or drop one without rewriting the other.
+ expect(logic.values.queuedMessages).toEqual([
+ { id: expect.any(String), content: 'first' },
+ { id: expect.any(String), content: 'second' },
+ ])
// Turn completes → drain. The flush itself sends while idle.
setThinking(false)
@@ -748,7 +752,7 @@ describe('runInteractionLogic', () => {
logic.actions.steerQueue()
await expectLogic(logic, () => complete(response)).toFinishAllListeners()
expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
- expect(logic.values.queuedMessages[0].content).toBe('first\n\nsecond')
+ expect(logic.values.queuedMessages.map((message) => message.content)).toEqual(['first', 'second'])
expect(logic.values.composerForm.draft).toBe('unsent draft')
expect(logic.values.steerPending).toBe(false)
expect(lemonToast.error).toHaveBeenCalled()
@@ -832,6 +836,106 @@ describe('runInteractionLogic', () => {
expect(logic.values.queuedMessages).toEqual([])
})
+ it('sends a message held by a stop together with the next one the user submits', async () => {
+ setThinking(true)
+ logic.actions.enqueueMessage('first follow-up')
+ logic.actions.requestCancellation()
+ expect(logic.values.queueHeld).toBe(true)
+
+ // The stop lands and the turn ends, so the run is idle again when the user types.
+ setThinking(false)
+ runCancellationLogic({ streamKey: RUN_ID }).actions.clearCancellation()
+ logic.actions.setComposerFormValues({ draft: 'are you there?' })
+ await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
+
+ expect(tasksRunsCommandCreate).toHaveBeenLastCalledWith(
+ ...userMessageCommand('first follow-up\n\nare you there?')
+ )
+ expect(logic.values.queuedMessages).toEqual([])
+ expect(logic.values.queueHeld).toBe(false)
+ })
+
+ it('holds an unconfirmed send as its own rows until the user asks for it again', async () => {
+ ;(tasksRunsCommandCreate as jest.Mock).mockRejectedValueOnce(new Error('Connection lost'))
+ setThinking(true)
+ logic.actions.enqueueMessage('first')
+ logic.actions.enqueueMessage('second')
+ await expectLogic(logic, () => logic.actions.steerQueue()).toFinishAllListeners()
+
+ // The send may have reached the agent, so the rows come back as they were rather than as one blob.
+ expect(logic.values.queuedMessages.map((message) => message.content)).toEqual(['first', 'second'])
+ expect(logic.values.queueHeld).toBe(true)
+ ;(tasksRunsCommandCreate as jest.Mock).mockClear()
+
+ // Typing more must not re-deliver them: only an explicit send may repeat an unconfirmed message.
+ setThinking(false)
+ logic.actions.setComposerFormValues({ draft: 'third' })
+ await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
+ await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+
+ await expectLogic(logic, () => logic.actions.steerQueue()).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
+ expect(logic.values.queuedMessages).toEqual([])
+ })
+
+ it('carries staged rows into the run a terminal send starts', async () => {
+ setThinking(true)
+ logic.actions.enqueueMessage('staged while running')
+ setStatus('completed')
+ stream.actions.handleTerminalStatus({ status: 'completed' })
+
+ logic.actions.setComposerFormValues({ draft: 'and now this' })
+ await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
+
+ expect(tasksRunCreate).toHaveBeenCalledWith(
+ '997',
+ TASK_ID,
+ expect.objectContaining({ pending_user_message: 'staged while running\n\nand now this' }),
+ expect.anything()
+ )
+ expect(logic.values.queuedMessages).toEqual([])
+ })
+
+ it('waits for an open row editor before a terminal send carries the rows', async () => {
+ setThinking(true)
+ logic.actions.enqueueMessage('half-written')
+ setStatus('completed')
+ stream.actions.handleTerminalStatus({ status: 'completed' })
+ logic.actions.setQueueEditing(true)
+
+ logic.actions.setComposerFormValues({ draft: 'and now this' })
+ await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
+
+ // Sending would have carried the row as it stood before the edit the user is still typing.
+ expect(tasksRunCreate).not.toHaveBeenCalled()
+ expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'half-written' }])
+
+ logic.actions.setQueueEditing(false)
+ await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
+ expect(tasksRunCreate).toHaveBeenCalledWith(
+ '997',
+ TASK_ID,
+ expect.objectContaining({ pending_user_message: 'half-written\n\nand now this' }),
+ expect.anything()
+ )
+ })
+
+ it('waits for an open row editor before draining on turn completion', async () => {
+ setThinking(true)
+ logic.actions.enqueueMessage('half-written')
+ logic.actions.setQueueEditing(true)
+
+ setThinking(false)
+ await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+
+ // Closing the editor drains on its own: no turn completion is coming, so nothing else would.
+ await expectLogic(logic, () => logic.actions.setQueueEditing(false)).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('half-written'))
+ expect(logic.values.queuedMessages).toEqual([])
+ })
+
it('edits and removes staged messages', async () => {
setThinking(true)
logic.actions.setComposerFormValues({ draft: 'typo' })
@@ -1521,7 +1625,10 @@ describe('runInteractionLogic', () => {
// The failed send re-stages 'first' in front of 'second', preserving order, and toasts.
expect(lemonToast.error).toHaveBeenCalled()
- expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'first\n\nsecond' }])
+ expect(logic.values.queuedMessages).toEqual([
+ { id: expect.any(String), content: 'first' },
+ { id: expect.any(String), content: 'second' },
+ ])
})
// The tasks run backend has no server-side consent check, so a follow-up (or a fresh-run send on a
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
index 1cc53724173d..40a19831431f 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
@@ -96,14 +96,23 @@ export interface RunContinuationHandoff {
draft: string
}
-/** The follow-up staged in the "Up next" buffer while the agent is mid-turn. */
+/**
+ * Why a staged message is waiting on the user instead of draining on its own. `cancelled` covers a Stop or
+ * a run that ended, where nothing reached the agent, so the next thing the user submits can carry it. After
+ * `unconfirmed` the message may already be with the agent — only an explicit send may repeat it.
+ */
+export type QueueHold = 'cancelled' | 'unconfirmed' | null
+
+/** One follow-up staged in the queue while the agent is mid-turn. */
export interface QueuedMessage {
id: string
content: string
}
-/** Stable id for the single staged "Up next" message — the queue never holds more than one. */
-const QUEUED_MESSAGE_ID = 'queued'
+// Identifies a staged message for the duration of its stay in the buffer, so editing or removing one row
+// leaves the others alone. Module-scoped because the ids only have to be unique within a single buffer.
+let queuedMessageSequence = 0
+const nextQueuedMessageId = (): string => `queued-${++queuedMessageSequence}`
// Agent-server (ACP) session config option ids — see the `/code` agent's buildConfigOptions. The model
// option's id is `model`; the effort option's id is `effort` (its category is `thought_level`).
@@ -179,7 +188,9 @@ export interface runInteractionLogicValues {
modeOverride: PermissionMode | null
modelOverride: string | null
pendingContextItems: AttachedContextItem[]
- queueNeedsRetry: boolean
+ queueEditing: boolean
+ queueHeld: boolean
+ queueHold: QueueHold
queuedMessages: QueuedMessage[]
selectedEffort: ReasoningEffortEnumApi
selectedMode: PermissionMode
@@ -321,7 +332,7 @@ export interface runInteractionLogicActions {
}
enqueueMessage: (content: string) => {
content: string
- wasEmpty: boolean
+ id: string
}
finishTaskDraftDelivery: () => {
value: true
@@ -338,8 +349,8 @@ export interface runInteractionLogicActions {
persistTaskDraft: () => {
value: true
}
- prependQueuedMessage: (content: string) => {
- content: string
+ prependQueuedMessages: (rows: QueuedMessage[]) => {
+ rows: QueuedMessage[]
}
queueDeliveryFailed: () => {
value: true
@@ -355,9 +366,11 @@ export interface runInteractionLogicActions {
sendNow: (
content: string,
source: 'draft' | 'queue',
- steer?: boolean
+ steer?: boolean,
+ rows?: QueuedMessage[]
) => {
content: string
+ rows: QueuedMessage[]
source: 'draft' | 'queue'
steer: boolean
}
@@ -402,6 +415,9 @@ export interface runInteractionLogicActions {
setModel: (model: string) => {
model: string
}
+ setQueueEditing: (editing: boolean) => {
+ editing: boolean
+ }
setSending: (sending: boolean) => {
sending: boolean
}
@@ -515,6 +531,7 @@ export interface runInteractionLogicMeta {
taskId: string,
runStarted: boolean
) => boolean
+ queueHeld: (queuedMessages: QueuedMessage[], queueHold: QueueHold) => boolean
isSubmitting: (sending: boolean, startingRun: boolean, clearing: boolean) => boolean
pendingContextItems: (
arg: AttachedContextItem[],
@@ -539,11 +556,10 @@ export type runInteractionLogicType = MakeLogicType<
* transport: the SSE stream, thread projection, run status, and permission routing all live in
* `runStreamLogic`, which this connects to by `streamKey` (the `runId`).
*
- * Queueing is client-side and holds at most a single message: a follow-up typed while the agent is working
- * a turn is staged here (editable, removable), and a second follow-up typed before the turn ends is
- * concatenated onto it rather than fanning out into separate messages. The single staged message is flushed
- * as one `user_message` when the turn completes. This mirrors the PostHog AI sandbox flush path without any
- * conversation/Max coupling.
+ * Queueing is client-side: a follow-up typed while the agent is working a turn is staged here, and each one
+ * keeps its own row so the user can edit or drop it on its own. The staged rows are flushed as a single
+ * `user_message` when the turn completes, so follow-ups never fan out into separate turns. This mirrors the
+ * PostHog AI sandbox flush path without any conversation/Max coupling.
*/
export const runInteractionLogic = kea<runInteractionLogicType>([
path(['products', 'posthog_ai', 'frontend', 'logics', 'runInteractionLogic']),
@@ -634,11 +650,17 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// Internal: POST one `user_message` now. `source` says where the content lives so a successful send
// clears the right place and a failed send preserves it for retry ('draft' → composer, 'queue' →
// 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, 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 }),
+ sendNow: (content: string, source: 'draft' | 'queue', steer: boolean = false, rows: QueuedMessage[] = []) => ({
+ content,
+ source,
+ steer,
+ rows,
+ }),
+ // Stage a follow-up as its own row under the ones already queued.
+ enqueueMessage: (content: string) => ({ id: nextQueuedMessageId(), content }),
+ // Re-stage unsent rows ahead of anything queued since — used to restore a failed queue flush with
+ // the rows it took, so one failure doesn't fuse them into a single uneditable row.
+ prependQueuedMessages: (rows: QueuedMessage[]) => ({ rows }),
updateQueuedMessage: (id: string, content: string) => ({ id, content }),
removeQueuedMessage: (id: string) => ({ id }),
clearQueue: true,
@@ -648,6 +670,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
handleEscape: true,
setDeferredSteer: (requestId: string | null) => ({ requestId }),
queueDeliveryFailed: true,
+ // Mirrors the queue editor's open/closed state into the logic, so an automatic drain waits for it.
+ setQueueEditing: (editing: boolean) => ({ editing }),
// Pick the model / reasoning effort for the next message. Selection is held client-side only and
// synced to the running agent (via `set_config_option`) at send time — not on each pick. The backend
// doesn't persist live changes back to the run state, so the override is the source of truth.
@@ -665,16 +689,27 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
reducers({
composerFocused: [false, { setComposerFocused: (_, { focused }) => focused }],
- queueNeedsRetry: [
+ queueHold: [
+ null as QueueHold,
+ {
+ queueDeliveryFailed: () => 'unconfirmed',
+ requestCancellation: () => 'cancelled',
+ handleTerminalStatus: (state, { status }) => (isTerminalRunStatus(status) ? 'cancelled' : state),
+ // A Stop or a terminal run holds the message it caught, not what the user types afterwards.
+ // Submitting text is an explicit "send this", so it lifts that hold and the buffer drains on
+ // turn end. Without it, every later submit joined a buffer nothing would ever deliver.
+ // An `unconfirmed` hold survives: the send that failed may have reached the agent anyway, so
+ // repeating it needs the user to look at the thread and ask for it.
+ enqueueMessage: (state) => (state === 'cancelled' ? null : state),
+ clearQueue: () => null,
+ },
+ ],
+ // Set while a staged row is open in its editor, so an automatic drain can't send the text the user
+ // is halfway through replacing. The editor itself lives in component state.
+ queueEditing: [
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),
+ setQueueEditing: (_, { editing }) => editing,
clearQueue: () => false,
},
],
@@ -730,17 +765,11 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
queuedMessages: [
[] as QueuedMessage[],
{
- // The buffer holds a single message under a stable id — a second follow-up concatenates onto
- // the staged content rather than appending a new entry.
- enqueueMessage: (state, { content }) =>
- state.length > 0
- ? [{ id: QUEUED_MESSAGE_ID, content: `${state[0].content}\n\n${content}` }]
- : [{ id: QUEUED_MESSAGE_ID, content }],
- // Restore the unsent content in front of anything staged since, preserving send order.
- prependQueuedMessage: (state, { content }) =>
- state.length > 0
- ? [{ id: QUEUED_MESSAGE_ID, content: `${content}\n\n${state[0].content}` }]
- : [{ id: QUEUED_MESSAGE_ID, content }],
+ // Each follow-up keeps its own row, in the order it was typed, so the user can edit or drop
+ // one of them without rewriting the rest. They go out together as one message.
+ enqueueMessage: (state, { id, content }) => [...state, { id, content }],
+ // Restore the unsent rows in front of anything staged since, preserving send order.
+ prependQueuedMessages: (state, { rows }) => [...rows, ...state],
updateQueuedMessage: (state, { id, content }) =>
state.flatMap((message) =>
message.id === id ? (content.trim() ? [{ ...message, content }] : []) : [message]
@@ -840,7 +869,20 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
actions.clearConversation()
return
}
- actions.startNewRun(content)
+ // A row editor keeps its text in the component until the user saves, so sending now
+ // would carry the row as it stood before the edit. Wait, as the drain does.
+ if (values.queueEditing) {
+ lemonToast.info('Save or cancel your edit first')
+ return
+ }
+ // A finished run can't drain the queue — `canSend` is false for the rest of its life —
+ // so the staged rows ride along into the run this send starts. Leaving them behind
+ // stranded them on screen, promising a delivery nothing would ever make.
+ const staged = values.queuedMessages.map((message) => message.content)
+ if (staged.length > 0) {
+ actions.clearQueue()
+ }
+ actions.startNewRun([...staged, content].join('\n\n'))
return
}
// While the agent is working, a send is in flight, or a message is already staged — concatenate
@@ -992,6 +1034,12 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
(!activeRunId || activeRunId === runId) &&
(!activeTaskId || activeTaskId === taskId),
],
+ // Whether the staged message is waiting on the user rather than on the agent. The queue looks the
+ // same in both cases, so the banner says which it is.
+ queueHeld: [
+ (s) => [s.queuedMessages, s.queueHold],
+ (queued: QueuedMessage[], hold: QueueHold): boolean => queued.length > 0 && hold !== null,
+ ],
// In-flight indicator for the composer's send button — a live send, a new-run start, or a clear.
isSubmitting: [
(s) => [s.sending, s.startingRun, s.clearing],
@@ -1074,6 +1122,13 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
)
}
+ // A queue send that never landed goes back as the rows it took, so one failure doesn't fuse them
+ // into a single uneditable row. A send with no rows attached still has its text, so it returns as
+ // one row rather than vanishing.
+ const restoreQueuedRows = (rows: QueuedMessage[], content: string): void => {
+ actions.prependQueuedMessages(rows.length > 0 ? rows : [{ id: nextQueuedMessageId(), content }])
+ }
+
// Record the non-text refs just wrapped into a send under the task, so no later send anywhere in
// the task's resume chain (including the next run after a terminal-run send) re-inflates them.
const markPendingContextSent = (pendingContext: AttachedContextItem[]): void => {
@@ -1104,13 +1159,17 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
actions.submitComposerForm()
}
},
- // Clear before awaiting delivery so new follow-ups survive completion. Failed sends prepend
- // their text to those newer follow-ups, and require an explicit retry to avoid duplicate delivery.
+ // Clear before awaiting delivery so new follow-ups survive completion. A failed send restores the
+ // rows it took, and holds them until the user asks again, so nothing is delivered twice.
flushQueue: ({ steer }) => {
- const [queued] = values.queuedMessages
+ const rows = values.queuedMessages
+ // The staged rows go out as one `user_message`, so follow-ups never fan out into separate
+ // turns — the second would otherwise wait for the turn the first one starts.
+ const queued = rows.map((message) => message.content).join('\n\n')
if (
!queued ||
- (!steer && (values.isBusy || values.queueNeedsRetry)) ||
+ (!steer && (values.isBusy || values.queueHold !== null)) ||
+ values.queueEditing ||
values.hasUnresolvedApproval ||
!values.canSend
) {
@@ -1121,7 +1180,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
return
}
actions.clearQueue()
- actions.sendNow(queued.content, 'queue', steer)
+ actions.sendNow(queued, 'queue', steer, rows)
},
steerQueue: () => {
@@ -1161,8 +1220,15 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
actions.clearQueue()
}
},
+ // A turn that ended while a row was open skipped the drain, and an idle agent sends no further
+ // turn completion — so retry the drain once the editor closes.
+ setQueueEditing: ({ editing }) => {
+ if (!editing) {
+ actions.flushQueue()
+ }
+ },
- sendNow: async ({ content, source, steer }) => {
+ sendNow: async ({ content, source, steer, rows }) => {
if (
!values.canSend ||
!content.trim() ||
@@ -1172,7 +1238,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// Nothing was sent. The queue buffer was already cleared in `flushQueue`, so re-stage for
// retry; the draft path leaves its content untouched in the composer.
if (source === 'queue') {
- actions.prependQueuedMessage(content)
+ restoreQueuedRows(rows, content)
}
return
}
@@ -1303,7 +1369,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
})
} else {
actions.queueDeliveryFailed()
- actions.prependQueuedMessage(content)
+ restoreQueuedRows(rows, content)
}
actions.finishTaskDraftDelivery()
lemonToast.error('Failed to send message. Please try again.')
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
index 94013c0b2d61..f4c1658398f5 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
@@ -42,6 +42,7 @@ export function TaskRunComposer({
isSubmitting,
isBusy,
queuedMessages,
+ queueHeld,
isTerminal,
selectedModel,
defaultModel,
@@ -76,6 +77,7 @@ export function TaskRunComposer({
setMode,
steerQueue,
submitAfterConsent,
+ setQueueEditing,
} = useActions(runInteractionLogic(logicProps))
useEffect(() => {
@@ -135,8 +137,16 @@ export function TaskRunComposer({
onUpdate={updateQueuedMessage}
onRemove={removeQueuedMessage}
onSteer={steerQueue}
- steerDisabledReason={!canSend && !isSubmitting ? 'Wait for the agent to start' : undefined}
+ steerDisabledReason={
+ isTerminal
+ ? 'This run has finished. Your next message starts a new run and takes these with it.'
+ : !canSend && !isSubmitting
+ ? 'Wait for the agent to start'
+ : undefined
+ }
steerPending={steerPending || isSubmitting || !!cancellationState}
+ held={queueHeld}
+ onEditingChange={setQueueEditing}
/>
</Composer.Banner>
)}