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.

feat(tasks): add optimistic approvals and queue steering (#96084)

Georgiy Tarasov45927f9f2f2c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4238c4a154b3..e9a5abb3ac04 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5553,13 +5553,17 @@ snapshots:
products-posthog-ai-queuedmessagelist--empty--light:
hash: v1.k794b7964.8ff99b0d11642dd53f5f0f70fc69106ee0e0158728fd6a73cf8699c4d68f8186.BQuDnKXQn4DwravdDwbmq3GC_BR06D3nntvW0bDvyzE
products-posthog-ai-queuedmessagelist--multiple--dark:
- hash: v1.k794b7964.df1eade6e183882ac4d220db72d54facaef1b22f1101d78683d6f2586af645f4.VcQ01DmlP4tHpLwgl8bn3UzQSJDkSIlpim747hocONc
+ hash: v1.k794b7964.3eda7962450082ad7e2ccb00419d73cde05964c67ce755414b11e1e4aea1aa8d.sccBMURl0uxdRk2-I_rbzScJQpUb8YMXKogdqgDEen0
products-posthog-ai-queuedmessagelist--multiple--light:
- hash: v1.k794b7964.b9579f5c5a4eae44c5143e87c238482f1340cb42617133b88ba5d726fd6d29d6.Jfm-YMQbfiruoX3Q5A_8dWxK3oxl5ezc5esv4_M9zfU
+ hash: v1.k794b7964.b8f2bbbd52d9d6d9cf037064a8006404e4baa16713f6cfd83dada357d174228c.R1y2GmsWYktkzIyDfTGX3pFYKv-wSUj7SrIVfUA93NU
products-posthog-ai-queuedmessagelist--single--dark:
- hash: v1.k794b7964.0c2d1ef2f419ad132533feeab88c70b8ff71b141e579d71be1a2399a1fcd730b.Up3p6SW6AQ0hKPpnuGgk6vGU0JIwNRcDlyvbWQ3wHm8
+ hash: v1.k794b7964.dc7887592adb4bd52e26bc40b2b7d91b4f0bb30b734313a8ca4dbf51a90eba20.jQksRkqZoUKTRLj-qr3x369OJW5x1-VvIqARTVLdRrU
products-posthog-ai-queuedmessagelist--single--light:
- hash: v1.k794b7964.9a96b57f229ede4a08ede4e081cad6fc788244f553de1a8d945cdfe3ccb3fe1c.LdYCyr75SdQkMa9RdjmEqLD-vS6zsJxXQr33aFn4NiU
+ hash: v1.k794b7964.574947658755ff52ea706341b7733033c27284dcded89cec117e770420947f6b.wYrWBIoHgR8k8p_nv1OqlGzkyyqedwJiMzRaaamjJKA
+ products-posthog-ai-queuedmessagelist--waiting-for-approval--dark:
+ hash: v1.k794b7964.c53aea6618dc88c754e0e9f074f439dbc8e11634184680e91b00170e4f681ff5.xLAZFI1s99bnlOuZw2PXahGWRxKTy5vxGa4-n7s_RQs
+ products-posthog-ai-queuedmessagelist--waiting-for-approval--light:
+ hash: v1.k794b7964.84558994ccccfbf6b0479c05e70fa04048ecdb813a76ac4a3e689b3f3d4a3cfd.WdgXqb0eDP9c6glP6UuTXb--spzTGFym3foe4wFyEIg
products-posthog-ai-runalertactivity--agent-crash--dark:
hash: v1.k794b7964.eccf2dc544a4a6695a42fb347e5c87b78fe735e8ac46647d17e53bf94d25884e.-9d5PYEyERQrPQag4CvnJteuh6fkhr0vYWyTDOt0Z8E
products-posthog-ai-runalertactivity--agent-crash--light:
diff --git a/products/posthog_ai/frontend/components/Approval.test.tsx b/products/posthog_ai/frontend/components/Approval.test.tsx
index 1e8bac108e3d..e427598f3844 100644
--- a/products/posthog_ai/frontend/components/Approval.test.tsx
+++ b/products/posthog_ai/frontend/components/Approval.test.tsx
@@ -137,15 +137,13 @@ describe('Sandbox approval input area', () => {
})
it('guards against double-submit while the reply POST is in flight', () => {
- // The logic's respondingToPermission flag drives the loading state — it flips
- // synchronously on dispatch and resets on success and on failure alike.
;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: true })
render(<PermissionInput streamKey="conv-1" request={makeRequest()} />)
- // Loading message replaces the option list, so nothing can be clicked.
- expect(screen.getByText('Sending response…')).toBeInTheDocument()
- expect(screen.queryByText('Approve')).not.toBeInTheDocument()
- expect(screen.queryByText('Decline')).not.toBeInTheDocument()
+ fireEvent.click(screen.getByText('Approve'))
+ fireEvent.click(screen.getByText('Decline'))
+ fireEvent.keyDown(window, { key: '1' })
+ fireEvent.keyDown(window, { key: 'Enter' })
expect(respondToPermission).not.toHaveBeenCalled()
})
diff --git a/products/posthog_ai/frontend/components/PermissionInput.test.tsx b/products/posthog_ai/frontend/components/PermissionInput.test.tsx
new file mode 100644
index 000000000000..3773b93c27ef
--- /dev/null
+++ b/products/posthog_ai/frontend/components/PermissionInput.test.tsx
@@ -0,0 +1,71 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { useActions, useValues } from 'kea'
+
+import type { PermissionRequestRecord } from '../types/streamTypes'
+import { PermissionInput } from './PermissionInput'
+
+jest.mock('kea', () => ({ ...jest.requireActual('kea'), useActions: jest.fn(), useValues: jest.fn() }))
+jest.mock('../logics/runStreamLogic', () => ({ runStreamLogic: jest.fn(() => ({})) }))
+jest.mock('./tool/toolRegistry', () => ({ lookupToolRenderer: () => ({}) }))
+
+describe('PermissionInput', () => {
+ const respondToPermission = jest.fn()
+ const cancelRun = jest.fn()
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ localStorage.clear()
+ ;(useActions as jest.Mock).mockReturnValue({ respondToPermission, cancelRun })
+ ;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: false })
+ })
+
+ afterEach(cleanup)
+
+ it.each(['Bash', 'ExitPlanMode'])(
+ 'preserves %s feedback through hidden delivery and disables its shortcuts',
+ (toolName) => {
+ const request: PermissionRequestRecord = {
+ requestId: 'approval-1',
+ sourceRunId: 'run-1',
+ toolCallId: 'tool-1',
+ toolName,
+ options: [
+ { optionId: 'auto', name: 'Allow', kind: 'allow_once' },
+ { optionId: 'reject', name: 'Do it differently', kind: 'reject_with_feedback' },
+ ],
+ rawToolCall: {
+ toolCallId: 'tool-1',
+ rawServerName: 'claude',
+ rawToolName: toolName,
+ input: {},
+ status: 'pending',
+ contentBlocks: [],
+ },
+ }
+ const { rerender } = render(<PermissionInput streamKey="run-1" request={request} />)
+ fireEvent.keyDown(document.body, { key: '2' })
+ const input = screen.getByPlaceholderText(/tell the agent what to do differently/i)
+ fireEvent.change(input, { target: { value: 'Use the example environment' } })
+ fireEvent.keyDown(input, { key: 'Enter' })
+ expect(respondToPermission).toHaveBeenCalledTimes(1)
+
+ ;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: true })
+ rerender(<PermissionInput streamKey="run-1" request={request} />)
+ for (const key of ['Escape', 'Tab', 'ArrowUp', '1', 'Enter']) {
+ fireEvent.keyDown(document.body, { key })
+ }
+ expect(respondToPermission).toHaveBeenCalledTimes(1)
+ expect(cancelRun).not.toHaveBeenCalled()
+
+ ;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: false })
+ rerender(<PermissionInput streamKey="run-1" request={request} />)
+ expect(screen.getByPlaceholderText(/tell the agent what to do differently/i)).toBe(input)
+ expect(input).toHaveValue('Use the example environment')
+ fireEvent.keyDown(input, { key: 'Enter' })
+ expect(respondToPermission).toHaveBeenCalledTimes(2)
+ expect(respondToPermission.mock.calls[1]).toEqual(respondToPermission.mock.calls[0])
+ }
+ )
+})
diff --git a/products/posthog_ai/frontend/components/PermissionInput.tsx b/products/posthog_ai/frontend/components/PermissionInput.tsx
index 5c51c88b1118..24526d8f8c1d 100644
--- a/products/posthog_ai/frontend/components/PermissionInput.tsx
+++ b/products/posthog_ai/frontend/components/PermissionInput.tsx
@@ -4,7 +4,7 @@ import type { ReactNode } from 'react'
import { useEffect, useRef, useState } from 'react'
import { IconWarning } from '@posthog/icons'
-import { Button, Spinner } from '@posthog/quill-primitives'
+import { Button } from '@posthog/quill-primitives'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { cn } from 'lib/utils/css-classes'
@@ -393,20 +393,13 @@ export function PermissionInput({ streamKey, request }: PermissionInputProps): J
payload={display.payload}
/>
)}
- {respondingToPermission ? (
- <div className="flex items-center gap-2 text-muted pt-1">
- <Spinner className="size-4" />
- <span>Sending response…</span>
- </div>
- ) : (
- <PermissionOptionRows
- options={mappedOptions}
- responding={respondingToPermission}
- onRespond={(optionId, customInput) =>
- respondToPermission({ requestId: request.requestId, optionId, customInput })
- }
- />
- )}
+ <PermissionOptionRows
+ options={mappedOptions}
+ responding={respondingToPermission}
+ onRespond={(optionId, customInput) =>
+ respondToPermission({ requestId: request.requestId, optionId, customInput })
+ }
+ />
</div>
)
}
diff --git a/products/posthog_ai/frontend/components/PlanApprovalActions.tsx b/products/posthog_ai/frontend/components/PlanApprovalActions.tsx
index 70411ae1577f..affe4e182a2b 100644
--- a/products/posthog_ai/frontend/components/PlanApprovalActions.tsx
+++ b/products/posthog_ai/frontend/components/PlanApprovalActions.tsx
@@ -251,7 +251,7 @@ export function PlanApprovalSelector({
// any element outside the card keeps native Tab/Enter behavior.
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent): void => {
- if (rejectSelected || e.defaultPrevented) {
+ if (responding || rejectSelected || e.defaultPrevented) {
return
}
const target = e.target
diff --git a/products/posthog_ai/frontend/components/QuestionField.tsx b/products/posthog_ai/frontend/components/QuestionField.tsx
index 83483d649ff7..c4bf37345ef3 100644
--- a/products/posthog_ai/frontend/components/QuestionField.tsx
+++ b/products/posthog_ai/frontend/components/QuestionField.tsx
@@ -19,6 +19,7 @@ interface QuestionFieldProps {
onSubmit: () => void
onSkip?: () => void
submitLabel?: string
+ disabled?: boolean
}
export function QuestionField({
@@ -29,6 +30,7 @@ export function QuestionField({
onSubmit,
onSkip,
submitLabel = 'Next',
+ disabled = false,
}: QuestionFieldProps): JSX.Element {
const fieldType = question.type ?? 'select'
@@ -48,6 +50,7 @@ export function QuestionField({
default:
return (
<SelectField
+ disabled={disabled}
question={question}
value={value as string | undefined}
onAnswer={onAnswer}
@@ -59,12 +62,14 @@ export function QuestionField({
}
function SelectField({
+ disabled,
question,
value,
onAnswer,
onSkip,
submitLabel,
}: {
+ disabled: boolean
question: MultiQuestionFormQuestion
value: string | undefined
onAnswer: (value: string | null) => void
@@ -81,6 +86,7 @@ function SelectField({
return (
<OptionSelector
+ disabled={disabled}
options={options}
onSelect={onAnswer}
allowCustom={allowCustomAnswer}
diff --git a/products/posthog_ai/frontend/components/QuestionInput.test.tsx b/products/posthog_ai/frontend/components/QuestionInput.test.tsx
index e21cd984b8d1..54d741f583af 100644
--- a/products/posthog_ai/frontend/components/QuestionInput.test.tsx
+++ b/products/posthog_ai/frontend/components/QuestionInput.test.tsx
@@ -164,12 +164,22 @@ describe('QuestionInput', () => {
})
})
- it('shows a sending state and blocks interaction while a reply is in flight', () => {
+ it('preserves custom answers and disables hidden shortcuts during delivery', () => {
+ const request = makeRequest([goalQuestion])
+ const { rerender } = render(<QuestionInput streamKey="conv-1" request={request} />)
+ fireEvent.click(screen.getByText("Explain what you'd like instead."))
+ fireEvent.change(screen.getByPlaceholderText('Type your answer...'), { target: { value: 'Cut churn' } })
+ fireEvent.click(screen.getByText('Submit'))
;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: true })
- render(<QuestionInput streamKey="conv-1" request={makeRequest([goalQuestion])} />)
-
- expect(screen.getByText('Sending response…')).toBeInTheDocument()
- expect(screen.queryByText('Revenue')).not.toBeInTheDocument()
- expect(respondToPermission).not.toHaveBeenCalled()
+ rerender(<QuestionInput streamKey="conv-1" request={request} />)
+ fireEvent.keyDown(document.body, { key: 'Escape' })
+ fireEvent.keyDown(document.body, { key: '1' })
+ expect(respondToPermission).toHaveBeenCalledTimes(1)
+ ;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: false })
+ rerender(<QuestionInput streamKey="conv-1" request={request} />)
+ expect(screen.getByPlaceholderText('Type your answer...')).toHaveValue('Cut churn')
+ fireEvent.click(screen.getByText('Submit'))
+ expect(respondToPermission).toHaveBeenCalledTimes(2)
+ expect(respondToPermission.mock.calls[1]).toEqual(respondToPermission.mock.calls[0])
})
})
diff --git a/products/posthog_ai/frontend/components/QuestionInput.tsx b/products/posthog_ai/frontend/components/QuestionInput.tsx
index baa1419d48f9..c69ef48d05cb 100644
--- a/products/posthog_ai/frontend/components/QuestionInput.tsx
+++ b/products/posthog_ai/frontend/components/QuestionInput.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { useCallback, useMemo, useRef, useState } from 'react'
import { IconChat } from '@posthog/icons'
-import { LemonTag, Spinner } from '@posthog/lemon-ui'
+import { LemonTag } from '@posthog/lemon-ui'
import type { MultiQuestionFormQuestion } from '~/queries/schema/schema-assistant-messages'
@@ -137,15 +137,6 @@ export function QuestionInput({ streamKey, request }: QuestionInputProps): JSX.E
return null
}
- if (respondingToPermission) {
- return (
- <div className="flex items-center gap-2 text-muted p-3">
- <Spinner className="size-4" />
- <span>Sending response…</span>
- </div>
- )
- }
-
const isLast = currentIndex === questions.length - 1
return (
@@ -164,6 +155,7 @@ export function QuestionInput({ streamKey, request }: QuestionInputProps): JSX.E
<div className="font-medium text-sm">{question.question}</div>
<QuestionField
key={currentIndex}
+ disabled={respondingToPermission}
question={toFormQuestion(question, currentIndex)}
value={answers[currentIndex]}
onAnswer={handleAnswer}
diff --git a/products/posthog_ai/frontend/components/QueuedMessageList.stories.tsx b/products/posthog_ai/frontend/components/QueuedMessageList.stories.tsx
index 513a64f43bc1..dc5648590901 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 }) => {
+ render: ({ messages, steerPending }) => {
const [queue, setQueue] = useState<QueuedMessage[]>(messages)
return (
<div className="max-w-180 mx-auto p-4">
@@ -18,6 +18,8 @@ const meta: Meta<typeof QueuedMessageList> = {
messages={queue}
onUpdate={(id, content) => setQueue((q) => q.map((m) => (m.id === id ? { ...m, content } : m)))}
onRemove={(id) => setQueue((q) => q.filter((m) => m.id !== id))}
+ onSteer={() => setQueue([])}
+ steerPending={steerPending}
/>
</div>
)
@@ -31,6 +33,11 @@ export const Single: Story = {
args: { messages: [{ id: '1', content: 'Also break it down by browser' }] },
}
+export const WaitingForApproval: Story = {
+ args: { messages: [{ id: '1', content: 'Also break it down by browser' }], steerPending: true },
+ parameters: { testOptions: { waitForLoadersToDisappear: false } },
+}
+
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 c2359f47140a..2b24ca97a1d9 100644
--- a/products/posthog_ai/frontend/components/QueuedMessageList.tsx
+++ b/products/posthog_ai/frontend/components/QueuedMessageList.tsx
@@ -3,12 +3,16 @@ import { useEffect, useRef, useState } from 'react'
import { IconCheck, IconPencil, IconTrash, IconX } from '@posthog/icons'
import { LemonButton, LemonTextArea } from '@posthog/lemon-ui'
+import { KeyboardShortcut } from 'lib/components/KeyboardShortcut/KeyboardShortcut'
+
import type { QueuedMessage } from '../logics/runInteractionLogic'
export interface QueuedMessageListProps {
messages: QueuedMessage[]
onUpdate: (id: string, content: string) => void
onRemove: (id: string) => void
+ onSteer?: () => void
+ steerPending?: boolean
}
interface QueuedMessageItemProps {
@@ -47,7 +51,7 @@ function QueuedMessageItem({
if (isEditing) {
return (
- <div className="space-y-2">
+ <div className="space-y-2" data-attr="run-queue-editor">
<LemonTextArea
ref={textAreaRef}
value={draft}
@@ -106,7 +110,13 @@ function QueuedMessageItem({
* (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({ messages, onUpdate, onRemove }: QueuedMessageListProps): JSX.Element | null {
+export function QueuedMessageList({
+ messages,
+ onUpdate,
+ onRemove,
+ onSteer,
+ steerPending = false,
+}: QueuedMessageListProps): JSX.Element | null {
const [editingId, setEditingId] = useState<string | null>(null)
if (messages.length === 0) {
@@ -115,7 +125,23 @@ export function QueuedMessageList({ messages, onUpdate, onRemove }: QueuedMessag
return (
<div className="flex flex-col gap-0.5 pb-2">
- <p className="text-xs font-medium text-muted px-2 mb-0">Up next</p>
+ <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>
+ {onSteer && (
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ data-attr="run-queue-steer"
+ onClick={onSteer}
+ loading={steerPending}
+ disabledReason={editingId ? 'Save or cancel your edit first' : undefined}
+ tooltip="Send queued messages before the turn ends"
+ sideIcon={<KeyboardShortcut escape />}
+ >
+ Steer
+ </LemonButton>
+ )}
+ </div>
{messages.map((message) => (
<QueuedMessageItem
key={message.id}
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
index 040b0eac3404..a10841fd59ab 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx
@@ -1,12 +1,14 @@
import '@testing-library/jest-dom'
-import { cleanup, render, screen } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { useActions, useValues } from 'kea'
+import { useState } from 'react'
import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
import type { RunStatus } from '../logics/runStreamLogic'
import type { PermissionRequestRecord } from '../types/streamTypes'
+import { useDebouncedDraft } from './composer/useDebouncedDraft'
import { RunSurface } from './RunSurfaceImpl'
jest.mock('kea', () => ({
@@ -35,6 +37,7 @@ function setValues(
overrides: Partial<{
currentRunStatus: RunStatus | null
pendingPermissionRequest: PermissionRequestRecord | null
+ respondingToPermission: boolean
bootstrapLoading: boolean
threadItems: unknown[]
task: { origin_product: string; runtime?: TaskRuntimeEnumApi } | null
@@ -44,6 +47,7 @@ function setValues(
bootstrapLoading: false,
threadItems: [],
pendingPermissionRequest: null,
+ respondingToPermission: false,
currentRunStatus: 'in_progress',
task: { origin_product: 'user_created', runtime: TaskRuntimeEnumApi.Acp },
taskLoading: false,
@@ -70,6 +74,12 @@ function renderLiveWithComposer(statusOrOverrides: RunStatus | null | Parameters
)
}
+function DraftComposer(): JSX.Element {
+ const [saved, setSaved] = useState('')
+ const draft = useDebouncedDraft(saved, setSaved)
+ return <textarea data-attr="draft" value={draft.value} onChange={(event) => draft.onChange(event.target.value)} />
+}
+
describe('RunSurface', () => {
beforeEach(() => {
jest.clearAllMocks()
@@ -142,7 +152,7 @@ describe('RunSurface', () => {
pendingPermissionRequest: { requestId: 'r1' } as PermissionRequestRecord,
})
expect(screen.getByTestId('permission')).toBeInTheDocument()
- expect(screen.queryByTestId('composer')).not.toBeInTheDocument()
+ expect(screen.getByTestId('composer')).not.toBeVisible()
})
it('renders the question input when the pending request carries questions', () => {
@@ -154,7 +164,47 @@ describe('RunSurface', () => {
} as PermissionRequestRecord,
})
expect(screen.getByTestId('question')).toBeInTheDocument()
- expect(screen.queryByTestId('composer')).not.toBeInTheDocument()
+ expect(screen.getByTestId('composer')).not.toBeVisible()
+ })
+
+ it('hides the approval during delivery and preserves a draft across restoration before its debounce commits', () => {
+ jest.useFakeTimers()
+ try {
+ const request = { requestId: 'r1', sourceRunId: 'run-1' } as PermissionRequestRecord
+ const surface = (): JSX.Element => (
+ <RunSurface.Root taskId="task-1" runId="run-1" interaction="live">
+ <RunSurface.Composer>
+ <DraftComposer />
+ </RunSurface.Composer>
+ </RunSurface.Root>
+ )
+ setValues({ pendingPermissionRequest: request })
+ const { rerender } = render(surface())
+ const card = screen.getByTestId('permission')
+ const draft = screen.getByTestId('draft')
+ expect(card).toBeVisible()
+ setValues({ pendingPermissionRequest: request, respondingToPermission: true })
+ rerender(surface())
+ expect(card).not.toBeVisible()
+ expect(draft).toBeVisible()
+ fireEvent.change(draft, { target: { value: 'a newer draft' } })
+ setValues({ pendingPermissionRequest: request, respondingToPermission: false })
+ rerender(surface())
+ expect(screen.getByTestId('permission')).toBe(card)
+ expect(card).toBeVisible()
+ expect(draft).toHaveValue('a newer draft')
+ act(() => {
+ jest.advanceTimersByTime(150)
+ })
+ setValues({ pendingPermissionRequest: null })
+ rerender(surface())
+ expect(screen.getByTestId('draft')).toBe(draft)
+ expect(draft).toBeVisible()
+ expect(draft).toHaveValue('a newer draft')
+ } finally {
+ cleanup()
+ jest.useRealTimers()
+ }
})
it('renders nothing in read-only mode', () => {
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
index 25094b78803f..2b671d752a5e 100644
--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx
@@ -246,33 +246,38 @@ function RunSurfaceThread({
*/
function RunSurfaceComposer({ children }: { children?: ReactNode }): JSX.Element | null {
const { interaction, streamKey } = useRunSurfaceContext()
- const { pendingPermissionRequest, currentRunStatus } = useValues(runStreamLogic)
+ const { pendingPermissionRequest, respondingToPermission, currentRunStatus } = useValues(runStreamLogic)
if (interaction !== 'live') {
return null
}
- // Pending approval/question takes precedence over the composer.
- if (pendingPermissionRequest && !isTerminalRunStatus(currentRunStatus)) {
- const isQuestion = !!pendingPermissionRequest.questions && pendingPermissionRequest.questions.length > 0
- return (
- <div className="border-t px-4 py-3">
- <div className="mx-auto w-full max-w-180">
- {isQuestion ? (
- <QuestionInput streamKey={streamKey} request={pendingPermissionRequest} />
- ) : (
- <PermissionInput streamKey={streamKey} request={pendingPermissionRequest} />
- )}
- </div>
- </div>
- )
- }
- if (!children || currentRunStatus === null) {
- return null // no composer UI supplied (e.g. ReadonlyRunSurface) or pre-bootstrap
- }
+ const request = !isTerminalRunStatus(currentRunStatus) ? pendingPermissionRequest : null
+ const showApproval = !!request && !respondingToPermission
+
+ // Both inputs keep their local state through delivery and restoration, including uncommitted draft keystrokes.
return (
- <div data-attr="composer" className="px-4 pb-[calc(1rem_+_env(safe-area-inset-bottom))]">
- <LemonDivider className="mt-0 mb-4" />
- <div className="mx-auto w-full max-w-180">{children}</div>
- </div>
+ <>
+ {request && (
+ <div hidden={!showApproval} className="border-t px-4 py-3" data-attr="run-approval">
+ <div key={`${request.sourceRunId}:${request.requestId}`} className="mx-auto w-full max-w-180">
+ {request.questions?.length ? (
+ <QuestionInput streamKey={streamKey} request={request} />
+ ) : (
+ <PermissionInput streamKey={streamKey} request={request} />
+ )}
+ </div>
+ </div>
+ )}
+ {children && currentRunStatus !== null && (
+ <div
+ hidden={showApproval}
+ data-attr="composer"
+ className="px-4 pb-[calc(1rem_+_env(safe-area-inset-bottom))]"
+ >
+ <LemonDivider className="mt-0 mb-4" />
+ <div className="mx-auto w-full max-w-180">{children}</div>
+ </div>
+ )}
+ </>
)
}
diff --git a/products/posthog_ai/frontend/components/composer/Composer.test.tsx b/products/posthog_ai/frontend/components/composer/Composer.test.tsx
index 7d0aa71c0263..5e3da9742d7f 100644
--- a/products/posthog_ai/frontend/components/composer/Composer.test.tsx
+++ b/products/posthog_ai/frontend/components/composer/Composer.test.tsx
@@ -1,8 +1,11 @@
import '@testing-library/jest-dom'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { createRef, useState } from 'react'
+import { QueuedMessageList } from '../QueuedMessageList'
import { Composer } from './Composer'
+import { ComposerSteerShortcut } from './ComposerSteerShortcut'
describe('Composer', () => {
const onChange = jest.fn()
@@ -33,6 +36,113 @@ describe('Composer', () => {
const getSend = (container: HTMLElement): HTMLButtonElement =>
container.querySelector('[data-attr="composer-send"]') as HTMLButtonElement
+ it.each(['Escape', 'Steer', 'Escape after closing a menu'])(
+ 'steers the saved queue once through %s without submitting the draft',
+ (trigger) => {
+ const steer = jest.fn()
+ function QueuedComposer(): JSX.Element {
+ const [pending, setPending] = useState(false)
+ const textAreaRef = createRef<HTMLTextAreaElement>()
+ const onSteer = (): void => {
+ setPending(true)
+ steer()
+ }
+ return (
+ <Composer.Root
+ value="unsent draft"
+ onChange={onChange}
+ onSubmit={onSubmit}
+ textAreaRef={textAreaRef}
+ >
+ <ComposerSteerShortcut textAreaRef={textAreaRef} onSteer={onSteer} disabled={pending} />
+ <QueuedMessageList
+ messages={[{ id: 'queued', content: 'saved message' }]}
+ onUpdate={jest.fn()}
+ onRemove={jest.fn()}
+ onSteer={onSteer}
+ steerPending={pending}
+ />
+ <Composer.Textarea data-attr="composer-input" />
+ </Composer.Root>
+ )
+ }
+ render(<QueuedComposer />)
+ if (trigger === 'Escape after closing a menu') {
+ render(
+ <div aria-hidden="true">
+ <div role="listbox" />
+ </div>
+ )
+ jest.spyOn(document.querySelector('[role="listbox"]')!, 'getClientRects').mockReturnValue({
+ length: 1,
+ } as DOMRectList)
+ }
+ const input = screen.getByTestId('composer-input')
+ input.focus()
+ for (let i = 0; i < 2; i++) {
+ if (trigger.startsWith('Escape')) {
+ fireEvent.keyDown(input, { key: 'Escape' })
+ } else {
+ fireEvent.click(screen.getByTestId('run-queue-steer'))
+ }
+ }
+ expect(steer).toHaveBeenCalledTimes(1)
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(input).toHaveValue('unsent draft')
+ }
+ )
+
+ it.each([
+ 'empty queue',
+ 'repeat',
+ 'composing',
+ 'menu',
+ 'dialog',
+ 'listbox',
+ 'other input',
+ 'queue editor',
+ 'hidden',
+ 'handled',
+ ])('leaves Escape alone for %s', (reason) => {
+ const textAreaRef = createRef<HTMLTextAreaElement>()
+ const steer = jest.fn()
+ const { container } = render(
+ <div hidden={reason === 'hidden'}>
+ <Composer.Root value="unsent draft" onChange={onChange} onSubmit={onSubmit} textAreaRef={textAreaRef}>
+ <ComposerSteerShortcut
+ textAreaRef={textAreaRef}
+ onSteer={steer}
+ disabled={reason === 'empty queue'}
+ />
+ <Composer.Textarea data-attr="composer-input" />
+ {reason === 'queue editor' && <textarea data-attr="run-queue-editor" />}
+ </Composer.Root>
+ <input data-attr="other-input" />
+ {['menu', 'dialog', 'listbox'].includes(reason) && <div role={reason} />}
+ </div>
+ )
+ const target =
+ reason === 'other input' ? screen.getByTestId('other-input') : screen.getByTestId('composer-input')
+ if (['menu', 'dialog', 'listbox'].includes(reason)) {
+ jest.spyOn(screen.getByRole(reason), 'getClientRects').mockReturnValue({ length: 1 } as DOMRectList)
+ }
+ const event = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ repeat: reason === 'repeat',
+ isComposing: reason === 'composing',
+ })
+ if (reason === 'handled') {
+ event.preventDefault()
+ }
+ target.dispatchEvent(event)
+ expect(steer).not.toHaveBeenCalled()
+ expect(event.defaultPrevented).toBe(reason === 'handled')
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(container.querySelector('textarea')).toHaveValue('unsent draft')
+ })
+
it('shows the placeholder only while empty', () => {
const { rerender } = renderComposer()
expect(screen.getByText('Send a message…')).toBeInTheDocument()
diff --git a/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.test.tsx b/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.test.tsx
index 4054d0ddd117..ba42961070ae 100644
--- a/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.test.tsx
+++ b/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.test.tsx
@@ -21,6 +21,13 @@ describe('ComposerModeShortcut', () => {
expect(onCycle).not.toHaveBeenCalled()
})
+ it('does not cycle while an approval hides the normal composer', () => {
+ const onCycle = jest.fn()
+ render(<ComposerModeShortcut onCycle={onCycle} disabled />)
+ fireEvent.keyDown(document.body, { key: 'Tab', shiftKey: true })
+ expect(onCycle).not.toHaveBeenCalled()
+ })
+
it('yields to a handler that already consumed the key', () => {
const onCycle = jest.fn()
render(<ComposerModeShortcut onCycle={onCycle} />)
diff --git a/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.tsx b/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.tsx
index 1dfea11e430e..3216276603fe 100644
--- a/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.tsx
+++ b/products/posthog_ai/frontend/components/composer/ComposerModeShortcut.tsx
@@ -3,6 +3,7 @@ import { useEffect } from 'react'
export interface ComposerModeShortcutProps {
/** Fired on Shift+Tab — cycle to the next permission mode. */
onCycle: () => void
+ disabled?: boolean
}
/**
@@ -12,12 +13,12 @@ export interface ComposerModeShortcutProps {
* anything that already handled the key (`defaultPrevented`) and to open menus/dialogs, which own Tab for
* their internal focus order.
*/
-export function ComposerModeShortcut({ onCycle }: ComposerModeShortcutProps): null {
+export function ComposerModeShortcut({ onCycle, disabled = false }: ComposerModeShortcutProps): null {
// No dep array on purpose: re-attaching keeps the listener's `onCycle` closure current (callers pass
// inline arrows over the selected mode) — same pattern as the plan-approval selector's shortcuts.
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent): void => {
- if (e.key !== 'Tab' || !e.shiftKey || e.defaultPrevented) {
+ if (disabled || e.key !== 'Tab' || !e.shiftKey || e.defaultPrevented) {
return
}
if (e.target instanceof HTMLElement && e.target.closest('[role="menu"],[role="dialog"]')) {
diff --git a/products/posthog_ai/frontend/components/composer/ComposerSteerShortcut.tsx b/products/posthog_ai/frontend/components/composer/ComposerSteerShortcut.tsx
new file mode 100644
index 000000000000..c637f3afe907
--- /dev/null
+++ b/products/posthog_ai/frontend/components/composer/ComposerSteerShortcut.tsx
@@ -0,0 +1,45 @@
+import type { RefObject } from 'react'
+
+import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'
+
+export function ComposerSteerShortcut({
+ textAreaRef,
+ onSteer,
+ disabled,
+}: {
+ textAreaRef: RefObject<HTMLTextAreaElement>
+ onSteer: () => void
+ disabled: boolean
+}): null {
+ useKeyboardHotkeys({
+ escape: {
+ disabled,
+ willHandleEvent: true,
+ action: (event) => {
+ if (
+ event.defaultPrevented ||
+ event.repeat ||
+ event.isComposing ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.altKey ||
+ event.shiftKey ||
+ event.target !== textAreaRef.current ||
+ textAreaRef.current?.closest('[hidden], [inert]') ||
+ textAreaRef.current?.closest('form')?.querySelector('[data-attr="run-queue-editor"]') ||
+ [...document.querySelectorAll('[role="menu"], [role="dialog"], [role="listbox"]')].some(
+ (overlay) =>
+ !overlay.closest('[hidden], [inert], [aria-hidden="true"]') &&
+ overlay.getClientRects().length > 0 &&
+ getComputedStyle(overlay).visibility !== 'hidden'
+ )
+ ) {
+ return
+ }
+ event.preventDefault()
+ onSteer()
+ },
+ },
+ })
+ return null
+}
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
index 6360c4573bf2..f6de4e43243b 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
@@ -15,6 +15,7 @@ import {
tasksWarmResumeCreate,
} from 'products/tasks/frontend/generated/api'
+import type { PermissionRequestRecord } from '../types/streamTypes'
import { contextItemLine } from '../utils/posthogContextBlock'
import { attachedContextLogic } from './attachedContextLogic'
import { runInteractionLogic } from './runInteractionLogic'
@@ -37,10 +38,18 @@ jest.mock('./runStreamLogic', () => {
cancelRun: (run?: unknown) => ({ run }),
markTurnComplete: true,
setCurrentMode: (mode: string) => ({ mode }),
- handleTerminalStatus: (status: string) => ({ status }),
+ handleTerminalStatus: (status: { status: string }) => status,
setStubStatus: (status: string | null) => ({ status }),
setStubThinking: (thinking: boolean) => ({ thinking }),
setStubClearSupported: (supported: boolean) => ({ supported }),
+ ingestPermissionRequest: (record: PermissionRequestRecord) => ({ record }),
+ markPermissionRequestResolved: (requestId: string) => ({ requestId }),
+ deliverPermission: (record: PermissionRequestRecord) => ({ record }),
+ permissionResponseFailed: (requestId: string) => ({ requestId }),
+ permissionRunChanged: true,
+ cancelPermissionDelivery: true,
+ clearPermissionRequest: true,
+ reset: true,
}),
reducers({
currentRunStatus: [
@@ -56,14 +65,48 @@ jest.mock('./runStreamLogic', () => {
setStubThinking: (_: boolean, { thinking }: { thinking: boolean }) => thinking,
},
],
- pendingPermissionRequest: [null, {}],
+ bootstrappedRunId: [null, {}],
+ bootstrappedTaskId: [null, {}],
+ pendingPermissionRequest: [
+ null,
+ {
+ ingestPermissionRequest: (_: unknown, { record }: { record: PermissionRequestRecord }) => record,
+ markPermissionRequestResolved: (
+ state: PermissionRequestRecord | null,
+ { requestId }: { requestId: string }
+ ) => (state?.requestId === requestId ? null : state),
+ clearPermissionRequest: () => null,
+ permissionRunChanged: () => null,
+ reset: () => null,
+ },
+ ],
+ permissionResponseRequestIds: [
+ new Set<string>(),
+ {
+ deliverPermission: (_: unknown, { record }: { record: PermissionRequestRecord }) =>
+ new Set([record.requestId]),
+ markPermissionRequestResolved: () => new Set<string>(),
+ permissionResponseFailed: () => new Set<string>(),
+ cancelPermissionDelivery: () => new Set<string>(),
+ reset: () => new Set<string>(),
+ },
+ ],
conversationClearSupported: [
true,
{
setStubClearSupported: (_: boolean, { supported }: { supported: boolean }) => supported,
},
],
- respondingToPermission: [false, {}],
+ respondingToPermission: [
+ false,
+ {
+ deliverPermission: () => true,
+ markPermissionRequestResolved: () => false,
+ permissionResponseFailed: () => false,
+ cancelPermissionDelivery: () => false,
+ reset: () => false,
+ },
+ ],
currentMode: [
null,
{
@@ -140,7 +183,7 @@ describe('runInteractionLogic', () => {
beforeEach(() => {
jest.clearAllMocks()
- ;(tasksRunsCommandCreate as jest.Mock).mockResolvedValue({})
+ ;(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({})
;(tasksWarmResumeCreate as jest.Mock).mockResolvedValue({ task_id: TASK_ID, run_id: 'warm-run' })
@@ -334,6 +377,204 @@ describe('runInteractionLogic', () => {
expect(logic.values.queuedMessages).toEqual([])
})
+ it.each(['approval first', 'turn first'])('holds ordinary delivery until both gates clear: %s', async (order) => {
+ const record = { requestId: 'approval-1', sourceRunId: RUN_ID } as PermissionRequestRecord
+ stream.actions.ingestPermissionRequest(record)
+ setThinking(true)
+ logic.actions.setComposerFormValues({ draft: 'follow up' })
+ logic.actions.submitComposerForm()
+ const resolveApproval = (): void => stream.actions.markPermissionRequestResolved(record.requestId)
+ const endTurn = (): void => {
+ setThinking(false)
+ stream.actions.markTurnComplete()
+ }
+ const [first, last] = order === 'approval first' ? [resolveApproval, endTurn] : [endTurn, resolveApproval]
+ first()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ last()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('follow up'))
+ })
+
+ it('defers steering through approval confirmation and sends the current saved queue once', async () => {
+ const record = { requestId: 'approval-1', sourceRunId: RUN_ID } as PermissionRequestRecord
+ stream.actions.ingestPermissionRequest(record)
+ stream.actions.deliverPermission(record, 'allow_once')
+ setThinking(true)
+ logic.actions.enqueueMessage('first')
+ logic.actions.setComposerFormValues({ draft: 'still drafting' })
+ logic.actions.steerQueue()
+ logic.actions.steerQueue()
+ logic.actions.enqueueMessage('second')
+ expect(logic.values.steerPending).toBe(true)
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+
+ await expectLogic(logic, () =>
+ stream.actions.markPermissionRequestResolved(record.requestId)
+ ).toFinishAllListeners()
+ stream.actions.markPermissionRequestResolved(record.requestId)
+ logic.actions.steerQueue()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, {
+ jsonrpc: '2.0',
+ method: 'user_message',
+ params: { content: 'first\n\nsecond', steer: true },
+ })
+ expect(logic.values.composerForm.draft).toBe('still drafting')
+ expect(logic.values.queuedMessages).toEqual([])
+ })
+
+ it.each(['failure', 'replacement approval', 'replacement run', 'terminal', 'cancel', 'reset', 'empty', 'unmount'])(
+ 'cancels deferred steering on %s',
+ async (event) => {
+ const record = { requestId: 'approval-1', sourceRunId: RUN_ID } as PermissionRequestRecord
+ stream.actions.ingestPermissionRequest(record)
+ stream.actions.deliverPermission(record, 'allow_once')
+ setThinking(true)
+ logic.actions.enqueueMessage('saved')
+ logic.actions.steerQueue()
+ expect(logic.values.steerPending).toBe(true)
+
+ switch (event) {
+ case 'failure':
+ stream.actions.permissionResponseFailed(record.requestId)
+ break
+ case 'replacement approval':
+ stream.actions.ingestPermissionRequest({ ...record, requestId: 'approval-2' })
+ break
+ case 'replacement run':
+ stream.actions.permissionRunChanged()
+ break
+ case 'terminal':
+ setStatus('completed')
+ stream.actions.handleTerminalStatus({ status: 'completed' })
+ break
+ case 'cancel':
+ stream.actions.cancelPermissionDelivery()
+ break
+ case 'reset':
+ stream.actions.reset()
+ break
+ case 'empty':
+ logic.actions.updateQueuedMessage(logic.values.queuedMessages[0].id, '')
+ break
+ case 'unmount':
+ logic.unmount()
+ logic.mount()
+ break
+ }
+ stream.actions.markPermissionRequestResolved(record.requestId)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ expect(logic.values.steerPending).toBe(false)
+ }
+ )
+
+ it.each([
+ { jsonrpc: '2.0', error: { code: -32000, message: 'Rejected' } },
+ { jsonrpc: '2.0', result: { queued: false } },
+ { result: { queued: true } },
+ undefined,
+ ])('restores unconfirmed steering before newer queued text: %j', async (response) => {
+ let complete!: (response: unknown) => void
+ ;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(
+ new Promise((resolve) => {
+ complete = resolve
+ })
+ )
+ setThinking(true)
+ logic.actions.enqueueMessage('first')
+ logic.actions.setComposerFormValues({ draft: 'unsent draft' })
+ logic.actions.steerQueue()
+ logic.actions.enqueueMessage('second')
+ 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.composerForm.draft).toBe('unsent draft')
+ expect(logic.values.steerPending).toBe(false)
+ expect(lemonToast.error).toHaveBeenCalled()
+ setThinking(false)
+ stream.actions.markTurnComplete()
+ stream.actions.markPermissionRequestResolved('earlier-approval')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
+ })
+
+ it.each(['reset', 'replacement run', 'cancel', 'terminal', 'unmount'])(
+ 'ignores a config completion after %s without sending a message',
+ async (event) => {
+ let complete!: (response: unknown) => void
+ ;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(
+ new Promise((resolve) => {
+ complete = resolve
+ })
+ )
+ setThinking(true)
+ logic.actions.setModel('claude-opus-4-8')
+ logic.actions.enqueueMessage('saved')
+ logic.actions.steerQueue()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
+ switch (event) {
+ case 'reset':
+ stream.actions.reset()
+ break
+ case 'replacement run':
+ stream.actions.permissionRunChanged()
+ break
+ case 'cancel':
+ stream.actions.cancelPermissionDelivery()
+ break
+ case 'terminal':
+ setStatus('completed')
+ stream.actions.handleTerminalStatus({ status: 'completed' })
+ break
+ case 'unmount':
+ logic.unmount()
+ logic.mount()
+ break
+ }
+ await expectLogic(logic, () => complete({ jsonrpc: '2.0', result: {} })).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
+ }
+ )
+
+ it('does nothing on an empty queue and keeps unsent context after failed steering', async () => {
+ setThinking(true)
+ const context = attachedContextLogic()
+ context.actions.registerContext('test', [{ type: 'insight', key: 'fake', value: 'example insight' }])
+ logic.actions.setComposerFormValues({ draft: 'unsent' })
+ logic.actions.steerQueue()
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ ;(tasksRunsCommandCreate as jest.Mock).mockRejectedValue(new Error('Connection lost'))
+ logic.actions.enqueueMessage('saved')
+ await expectLogic(logic, () => logic.actions.steerQueue()).toFinishAllListeners()
+ expect(logic.values.pendingContextItems).toHaveLength(1)
+ expect(logic.values.composerForm.draft).toBe('unsent')
+ expect(logic.values.queuedMessages[0].content).toBe('saved')
+ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
+ })
+
+ it.each(['remove', 'edit'])('delivers a fresh queue after discarding a failed submission: %s', async (action) => {
+ ;(tasksRunsCommandCreate as jest.Mock).mockRejectedValueOnce(new Error('Connection lost'))
+ setThinking(true)
+ logic.actions.enqueueMessage('discard this')
+ await expectLogic(logic, () => logic.actions.steerQueue()).toFinishAllListeners()
+ const { id } = logic.values.queuedMessages[0]
+ if (action === 'remove') {
+ logic.actions.removeQueuedMessage(id)
+ } else {
+ logic.actions.updateQueuedMessage(id, '')
+ }
+ logic.actions.enqueueMessage('new follow-up')
+ setThinking(false)
+ await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(2)
+ expect(tasksRunsCommandCreate).toHaveBeenLastCalledWith(...userMessageCommand('new follow-up'))
+ expect(logic.values.queuedMessages).toEqual([])
+ })
+
it('edits and removes staged messages', async () => {
setThinking(true)
logic.actions.setComposerFormValues({ draft: 'typo' })
@@ -766,8 +1007,8 @@ describe('runInteractionLogic', () => {
it('keeps text typed into the composer during an in-flight draft send instead of clobbering it on success', async () => {
let resolveSend: () => void = () => {}
;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(
- new Promise<void>((resolve) => {
- resolveSend = () => resolve()
+ new Promise((resolve) => {
+ resolveSend = () => resolve({ jsonrpc: '2.0', result: { queued: true } })
})
)
@@ -817,8 +1058,8 @@ describe('runInteractionLogic', () => {
it('keeps a follow-up typed during an in-flight queue flush instead of clearing it with the send', async () => {
let resolveSend: () => void = () => {}
;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(
- new Promise<void>((resolve) => {
- resolveSend = () => resolve()
+ new Promise((resolve) => {
+ resolveSend = () => resolve({ jsonrpc: '2.0', result: { queued: true } })
})
)
@@ -880,40 +1121,59 @@ describe('runInteractionLogic', () => {
// terminal run) must be blocked client-side before it reaches `tasksRunsCommandCreate` /
// `tasksRunCreate`. Uses a distinct `runId` key so the logic is built (and connects to
// `aiConsentLogic`) after the selector is stubbed.
- it('blocks composerForm.submit and sends nothing when consent is not accepted', async () => {
- const consent = aiConsentLogic()
- consent.mount()
- jest.spyOn(consent.selectors, 'dataProcessingAccepted').mockReturnValue(false)
-
- const blockedRunId = 'run-blocked'
- const blockedStream = runStreamLogic({ streamKey: blockedRunId })
- blockedStream.mount()
- const blockedLogic = runInteractionLogic({ taskId: TASK_ID, runId: blockedRunId, onRunStarted })
- blockedLogic.mount()
-
- // Terminal, so typing would otherwise warm a successor — which boots a cloud sandbox and
- // restores the repository snapshot, before the organization has accepted anything.
- ;(blockedStream.actions as unknown as { setStubStatus: (status: string | null) => void }).setStubStatus(
- 'completed'
- )
- jest.useFakeTimers()
- blockedLogic.actions.setComposerFormValues({ draft: 'ship it' })
- jest.advanceTimersByTime(300)
- jest.useRealTimers()
- await expectLogic(blockedLogic, () => {
- blockedLogic.actions.submitComposerForm()
- }).toFinishAllListeners()
+ it.each(['draft', 'steer'])(
+ 'blocks %s without consent and never substitutes the unsent draft for steering',
+ async (source) => {
+ const consent = aiConsentLogic()
+ consent.mount()
+ const consentAccepted = jest.spyOn(consent.selectors, 'dataProcessingAccepted').mockReturnValue(false)
+
+ const blockedRunId = 'run-blocked'
+ const blockedStream = runStreamLogic({ streamKey: blockedRunId })
+ blockedStream.mount()
+ const blockedLogic = runInteractionLogic({ taskId: TASK_ID, runId: blockedRunId, onRunStarted })
+ blockedLogic.mount()
+
+ // Terminal, so typing would otherwise warm a successor — which boots a cloud sandbox and
+ // restores the repository snapshot, before the organization has accepted anything.
+ ;(blockedStream.actions as unknown as { setStubStatus: (status: string | null) => void }).setStubStatus(
+ source === 'draft' ? 'completed' : 'in_progress'
+ )
+ jest.useFakeTimers()
+ blockedLogic.actions.setComposerFormValues({ draft: 'ship it' })
+ jest.advanceTimersByTime(300)
+ jest.useRealTimers()
+ await expectLogic(blockedLogic, () => {
+ if (source === 'draft') {
+ blockedLogic.actions.submitComposerForm()
+ } else {
+ blockedLogic.actions.enqueueMessage('saved follow up')
+ blockedLogic.actions.steerQueue()
+ }
+ }).toFinishAllListeners()
- expect(tasksWarmResumeCreate).not.toHaveBeenCalled()
- expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
- expect(tasksRunCreate).not.toHaveBeenCalled()
- expect(blockedLogic.values.consentBlocked).toBe(true)
+ expect(tasksWarmResumeCreate).not.toHaveBeenCalled()
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ expect(tasksRunCreate).not.toHaveBeenCalled()
+ expect(blockedLogic.values.consentBlocked).toBe(true)
+
+ if (source === 'steer') {
+ consentAccepted.mockReturnValue(true)
+ await expectLogic(blockedLogic, () => blockedLogic.actions.submitAfterConsent()).toFinishAllListeners()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', TASK_ID, blockedRunId, {
+ jsonrpc: '2.0',
+ method: 'user_message',
+ params: { content: 'saved follow up', steer: true },
+ })
+ expect(blockedLogic.values.composerForm.draft).toBe('ship it')
+ }
- blockedLogic.unmount()
- blockedStream.unmount()
- consent.unmount()
- jest.restoreAllMocks()
- })
+ blockedLogic.unmount()
+ blockedStream.unmount()
+ consent.unmount()
+ jest.restoreAllMocks()
+ }
+ )
it('no-ops on submit with an empty draft', async () => {
await expectLogic(logic, () => {
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
index 8943f1f4d221..76a68e15a654 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
@@ -94,16 +94,20 @@ export interface runInteractionLogicValues {
sentContextKeysByTask: Record<string, string[]> // attachedContextLogic
catalogue: ModelChoiceApi[] // modelCatalogueLogic
currentProjectId: number | null // projectLogic
+ bootstrappedRunId: string | null // runStreamLogic
+ bootstrappedTaskId: string | null // runStreamLogic
conversationClearSupported: boolean // runStreamLogic
currentMode: string | null // runStreamLogic
currentRunStatus: RunStatus | null // runStreamLogic
isThinking: boolean // runStreamLogic
pendingPermissionRequest: PermissionRequestRecord | null // runStreamLogic
+ permissionResponseRequestIds: Set<string> // runStreamLogic
respondingToPermission: boolean // runStreamLogic
defaultEffort: string | null // taskRunDefaultsLogic
defaultModel: string | null // taskRunDefaultsLogic
canSend: boolean
clearing: boolean
+ composerActive: boolean
composerForm: {
draft: string
}
@@ -126,7 +130,10 @@ export interface runInteractionLogicValues {
ValidationErrorType
>
consentBlocked: boolean
+ consentBlockedSource: 'draft' | 'queue' | 'steer'
+ deferredSteerRequestId: string | null
effortOverride: string | null
+ hasUnresolvedApproval: boolean
isBusy: boolean
isComposerFormSubmitting: boolean
isComposerFormValid: boolean
@@ -135,6 +142,7 @@ export interface runInteractionLogicValues {
modeOverride: PermissionMode | null
modelOverride: string | null
pendingContextItems: AttachedContextItem[]
+ queueNeedsRetry: boolean
queuedMessages: QueuedMessage[]
selectedEffort: ReasoningEffortEnumApi
selectedMode: PermissionMode
@@ -145,6 +153,7 @@ export interface runInteractionLogicValues {
sentModel: string | null
showComposerFormErrors: boolean
startingRun: boolean
+ steerPending: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -156,6 +165,9 @@ export interface runInteractionLogicActions {
keys: string[]
taskId: string
} // attachedContextLogic
+ cancelPermissionDelivery: () => {
+ value: true
+ } // runStreamLogic
cancelRun: (
run?:
| {
@@ -171,6 +183,9 @@ export interface runInteractionLogicActions {
}
| undefined
} // runStreamLogic
+ clearPermissionRequest: () => {
+ value: true
+ } // runStreamLogic
handleTerminalStatus: (status: {
errorMessage?: string | null
replayedFromHistory?: boolean
@@ -180,15 +195,34 @@ export interface runInteractionLogicActions {
replayedFromHistory?: boolean | undefined
status: RunStatus
} // runStreamLogic
+ ingestPermissionRequest: (
+ record: PermissionRequestRecord,
+ replayedFromHistory?: boolean | undefined
+ ) => {
+ record: PermissionRequestRecord
+ replayedFromHistory: boolean
+ } // runStreamLogic
+ markPermissionRequestResolved: (requestId: string) => {
+ requestId: string
+ } // runStreamLogic
markTurnComplete: () => {
value: true
} // runStreamLogic
+ permissionResponseFailed: (requestId: string) => {
+ requestId: string
+ } // runStreamLogic
+ permissionRunChanged: () => {
+ value: true
+ } // runStreamLogic
pushConversationCleared: () => {
value: true
} // runStreamLogic
pushHumanMessage: (content: string) => {
content: string
} // runStreamLogic
+ resetStream: () => {
+ value: true
+ } // runStreamLogic
respondToPermission: (payload: {
answers?: Record<string, string>
customInput?: string
@@ -229,8 +263,8 @@ export interface runInteractionLogicActions {
fromStreamKey: string
toStreamKey: string
} // toolStreamEventsLogic
- blockOnConsent: () => {
- value: true
+ blockOnConsent: (source?: 'draft' | 'queue' | 'steer') => {
+ source: 'draft' | 'queue' | 'steer'
}
clearConsentBlock: () => {
value: true
@@ -244,12 +278,15 @@ export interface runInteractionLogicActions {
enqueueMessage: (content: string) => {
content: string
}
- flushQueue: () => {
- value: true
+ flushQueue: (steer?: boolean) => {
+ steer: boolean
}
prependQueuedMessage: (content: string) => {
content: string
}
+ queueDeliveryFailed: () => {
+ value: true
+ }
removeQueuedMessage: (id: string) => {
id: string
}
@@ -260,10 +297,12 @@ export interface runInteractionLogicActions {
}
sendNow: (
content: string,
- source: 'draft' | 'queue'
+ source: 'draft' | 'queue',
+ steer?: boolean
) => {
content: string
source: 'draft' | 'queue'
+ steer: boolean
}
setClearing: (clearing: boolean) => {
clearing: boolean
@@ -287,6 +326,9 @@ export interface runInteractionLogicActions {
draft: string
}>
}
+ setDeferredSteer: (requestId: string | null) => {
+ requestId: string | null
+ }
setEffort: (effort: string) => {
effort: string
}
@@ -314,6 +356,12 @@ export interface runInteractionLogicActions {
startNewRun: (content: string) => {
content: string
}
+ steerQueue: () => {
+ value: true
+ }
+ submitAfterConsent: () => {
+ value: true
+ }
submitComposerForm: () => {
value: boolean
}
@@ -350,6 +398,16 @@ export interface runInteractionLogicActions {
export interface runInteractionLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ hasUnresolvedApproval: (
+ pendingPermissionRequest: PermissionRequestRecord | null,
+ permissionResponseRequestIds: Set<string>
+ ) => boolean
+ steerPending: (deferredSteerRequestId: string | null, sending: boolean) => boolean
+ composerActive: (
+ pendingPermissionRequest: PermissionRequestRecord | null,
+ respondingToPermission: boolean,
+ isTerminal: boolean
+ ) => boolean
isTerminal: (currentRunStatus: RunStatus | null) => boolean
selectedModel: (modelOverride: string | null, arg: any, defaultModel: string | null) => string
selectedEffort: (
@@ -366,7 +424,16 @@ export interface runInteractionLogicMeta {
arg2: any
) => PermissionMode
isBusy: (isThinking: boolean) => boolean
- canSend: (sending: boolean, isTerminal: boolean, currentProjectId: number | null) => boolean
+ canSend: (
+ sending: boolean,
+ isTerminal: boolean,
+ currentProjectId: number | null,
+ currentRunStatus: RunStatus | null,
+ bootstrappedRunId: string | null,
+ bootstrappedTaskId: string | null,
+ runId: string,
+ taskId: string
+ ) => boolean
isSubmitting: (sending: boolean, startingRun: boolean, clearing: boolean) => boolean
pendingContextItems: (
contextItems: AttachedContextItem[],
@@ -414,6 +481,9 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
'isThinking',
'currentMode',
'conversationClearSupported',
+ 'permissionResponseRequestIds',
+ 'bootstrappedRunId',
+ 'bootstrappedTaskId',
],
attachedContextLogic,
['contextItems', 'sentContextKeysByTask', 'seenContextLinesByTask'],
@@ -434,6 +504,13 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
'markTurnComplete',
'setCurrentMode',
'handleTerminalStatus',
+ 'markPermissionRequestResolved',
+ 'permissionResponseFailed',
+ 'ingestPermissionRequest',
+ 'permissionRunChanged',
+ 'cancelPermissionDelivery',
+ 'clearPermissionRequest',
+ 'reset as resetStream',
],
attachedContextLogic,
['markContextSent'],
@@ -446,8 +523,9 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
actions({
setSending: (sending: boolean) => ({ sending }),
- blockOnConsent: true,
+ blockOnConsent: (source: 'draft' | 'queue' | 'steer' = 'draft') => ({ source }),
clearConsentBlock: true,
+ submitAfterConsent: true,
// Start a fresh run on the task, seeded with this message and chained from the finished run.
startNewRun: (content: string) => ({ content }),
setStartingRun: (starting: boolean) => ({ starting }),
@@ -456,7 +534,7 @@ 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') => ({ content, source }),
+ 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 }),
// Re-stage unsent content ahead of anything queued since — used to restore a failed queue flush.
@@ -465,7 +543,10 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
removeQueuedMessage: (id: string) => ({ id }),
clearQueue: true,
// Internal: drain the staged "Up next" message when the agent is idle.
- flushQueue: true,
+ flushQueue: (steer: boolean = false) => ({ steer }),
+ steerQueue: true,
+ setDeferredSteer: (requestId: string | null) => ({ requestId }),
+ queueDeliveryFailed: true,
// 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.
@@ -482,6 +563,22 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
}),
reducers({
+ queueNeedsRetry: [false, { queueDeliveryFailed: () => true, clearQueue: () => false }],
+ consentBlockedSource: ['draft' as 'draft' | 'queue' | 'steer', { blockOnConsent: (_, { source }) => source }],
+ deferredSteerRequestId: [
+ null as string | null,
+ {
+ setDeferredSteer: (_, { requestId }) => requestId,
+ permissionResponseFailed: () => null,
+ ingestPermissionRequest: (state, { record }) => (state === record.requestId ? state : null),
+ permissionRunChanged: () => null,
+ cancelPermissionDelivery: () => null,
+ clearPermissionRequest: () => null,
+ resetStream: () => null,
+ handleTerminalStatus: (state, { status }) => (isTerminalRunStatus(status) ? null : state),
+ clearQueue: () => null,
+ },
+ ],
sending: [
false,
{
@@ -523,7 +620,9 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
? [{ id: QUEUED_MESSAGE_ID, content: `${content}\n\n${state[0].content}` }]
: [{ id: QUEUED_MESSAGE_ID, content }],
updateQueuedMessage: (state, { id, content }) =>
- state.map((message) => (message.id === id ? { ...message, content } : message)),
+ state.flatMap((message) =>
+ message.id === id ? (content.trim() ? [{ ...message, content }] : []) : [message]
+ ),
removeQueuedMessage: (state, { id }) => state.filter((message) => message.id !== id),
clearQueue: () => [],
},
@@ -616,7 +715,12 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// While the agent is working, a send is in flight, or a message is already staged — concatenate
// this onto the single queued message so follow-ups never jump ahead or fan out; otherwise send
// it straight from the draft. `flushQueue` self-guards, draining only when the run is fully idle.
- if (values.isBusy || values.sending || values.queuedMessages.length > 0) {
+ if (
+ values.isBusy ||
+ values.hasUnresolvedApproval ||
+ values.sending ||
+ values.queuedMessages.length > 0
+ ) {
actions.enqueueMessage(content)
actions.resetComposerForm()
actions.flushQueue()
@@ -628,6 +732,20 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
})),
selectors({
+ hasUnresolvedApproval: [
+ (s) => [s.pendingPermissionRequest, s.permissionResponseRequestIds],
+ (request: PermissionRequestRecord | null, deliveries: Set<string>): boolean =>
+ !!request || deliveries.size > 0,
+ ],
+ steerPending: [
+ (s) => [s.deferredSteerRequestId, s.sending],
+ (requestId: string | null, sending: boolean): boolean => requestId !== null || sending,
+ ],
+ composerActive: [
+ (s) => [s.pendingPermissionRequest, s.respondingToPermission, s.isTerminal],
+ (request: PermissionRequestRecord | null, responding: boolean, terminal: boolean): boolean =>
+ !request || responding || terminal,
+ ],
isTerminal: [
(s) => [s.currentRunStatus],
(status: null | import('./runStreamLogic').RunStatus): boolean => isTerminalRunStatus(status),
@@ -674,9 +792,32 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// 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],
canSend: [
- (s) => [s.sending, s.isTerminal, s.currentProjectId],
- (sending: boolean, isTerminal: boolean, currentProjectId: number | null): boolean =>
- !sending && !isTerminal && currentProjectId != null,
+ (s, p) => [
+ s.sending,
+ s.isTerminal,
+ s.currentProjectId,
+ s.currentRunStatus,
+ s.bootstrappedRunId,
+ s.bootstrappedTaskId,
+ p.runId,
+ p.taskId,
+ ],
+ (
+ sending: boolean,
+ isTerminal: boolean,
+ currentProjectId: number | null,
+ status: RunStatus | null,
+ activeRunId: string | null,
+ activeTaskId: string | null,
+ runId: string,
+ taskId: string
+ ): boolean =>
+ !sending &&
+ !isTerminal &&
+ currentProjectId != null &&
+ status !== null &&
+ (!activeRunId || activeRunId === runId) &&
+ (!activeTaskId || activeTaskId === taskId),
],
// In-flight indicator for the composer's send button — a live send, a new-run start, or a clear.
isSubmitting: [
@@ -715,6 +856,11 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
}),
listeners(({ actions, values, props, cache }) => {
+ const invalidateSend = (): void => {
+ cache.sendGeneration = (cache.sendGeneration ?? 0) + 1
+ actions.setSending(false)
+ }
+
const noteTerminalDraft = (): void => {
// 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
@@ -742,21 +888,81 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
}
return {
- // Drain the staged "Up next" message — only when the run is idle and can actually take it, so a flush
- // against a busy/terminal/in-flight send is a no-op rather than dropping the message. The buffer is
- // cleared up-front (not after the send) so a follow-up typed during the in-flight send stages cleanly
- // instead of being wiped along with this send on success; `sendNow` re-stages it if the send fails.
- flushQueue: () => {
+ submitAfterConsent: () => {
+ actions.clearConsentBlock()
+ if (values.consentBlockedSource === 'steer') {
+ actions.steerQueue()
+ } else if (values.consentBlockedSource === 'queue') {
+ actions.flushQueue()
+ } else {
+ 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.
+ flushQueue: ({ steer }) => {
const [queued] = values.queuedMessages
- if (!queued || values.isBusy || !values.canSend) {
+ if (
+ !queued ||
+ (!steer && (values.isBusy || values.queueNeedsRetry)) ||
+ values.hasUnresolvedApproval ||
+ !values.canSend
+ ) {
+ return
+ }
+ if (!values.dataProcessingAccepted) {
+ actions.blockOnConsent(steer ? 'steer' : 'queue')
return
}
actions.clearQueue()
- actions.sendNow(queued.content, 'queue')
+ actions.sendNow(queued.content, 'queue', steer)
+ },
+
+ steerQueue: () => {
+ if (!values.queuedMessages.length || values.steerPending || !values.canSend || !values.composerActive) {
+ return
+ }
+ if (!values.dataProcessingAccepted) {
+ actions.blockOnConsent('steer')
+ return
+ }
+ if (values.pendingPermissionRequest && values.pendingPermissionRequest.sourceRunId !== props.runId) {
+ return
+ }
+ const requestId =
+ values.pendingPermissionRequest?.requestId ?? [...values.permissionResponseRequestIds][0]
+ if (requestId) {
+ actions.setDeferredSteer(requestId)
+ } else {
+ actions.flushQueue(true)
+ }
+ },
+
+ markPermissionRequestResolved: ({ requestId }) => {
+ const steer = values.deferredSteerRequestId === requestId
+ if (steer) {
+ actions.setDeferredSteer(null)
+ }
+ actions.flushQueue(steer)
+ },
+ removeQueuedMessage: () => {
+ if (!values.queuedMessages.length) {
+ actions.clearQueue()
+ }
+ },
+ updateQueuedMessage: () => {
+ if (!values.queuedMessages.length) {
+ actions.clearQueue()
+ }
},
- sendNow: async ({ content, source }) => {
- if (values.sending || !content.trim() || values.isTerminal || values.currentProjectId == null) {
+ sendNow: async ({ content, source, steer }) => {
+ if (
+ !values.canSend ||
+ !content.trim() ||
+ values.hasUnresolvedApproval ||
+ !values.dataProcessingAccepted
+ ) {
// 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') {
@@ -764,6 +970,18 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
}
return
}
+ const projectId = values.currentProjectId
+ const runId = props.runId
+ const taskId = props.taskId
+ const disposables = cache.disposables
+ const generation = (cache.sendGeneration = (cache.sendGeneration ?? 0) + 1)
+ const isCurrent = (): boolean =>
+ !disposables.isDisposed &&
+ cache.sendGeneration === generation &&
+ values.currentProjectId === projectId &&
+ !values.isTerminal &&
+ props.runId === runId &&
+ props.taskId === taskId
actions.setSending(true)
const streamKey = props.streamKey ?? props.runId
// `/clear` goes unwrapped: a context block would hide the command behind it (the
@@ -795,6 +1013,9 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
method: 'set_config_option',
params: { configId: MODEL_CONFIG_ID, value: values.selectedModel },
})
+ if (!isCurrent()) {
+ return
+ }
actions.setSentModel(values.selectedModel)
}
if (values.selectedEffort !== activeEffort) {
@@ -803,6 +1024,9 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
method: 'set_config_option',
params: { configId: EFFORT_CONFIG_ID, value: values.selectedEffort },
})
+ if (!isCurrent()) {
+ return
+ }
actions.setSentEffort(values.selectedEffort)
}
const modeAdapter = props.currentRuntimeAdapter ?? RuntimeAdapterEnumApi.Claude
@@ -819,19 +1043,45 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
method: 'set_config_option',
params: { configId: MODE_CONFIG_ID, value: values.selectedMode },
})
+ if (!isCurrent()) {
+ return
+ }
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).
- await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {
+ if (!isCurrent() || values.hasUnresolvedApproval) {
+ throw new Error('The run cannot accept this message yet')
+ }
+ const response = await tasksRunsCommandCreate(String(projectId), taskId, runId, {
jsonrpc: '2.0',
method: 'user_message',
- params: { content: wrapWithPosthogContext(content, pendingContext) },
+ params: {
+ content: wrapWithPosthogContext(content, pendingContext),
+ ...(steer ? { steer: true } : {}),
+ },
})
+ if (!isCurrent()) {
+ return
+ }
+ const result = response?.result
+ if (
+ response?.jsonrpc !== '2.0' ||
+ 'error' in response ||
+ typeof result !== 'object' ||
+ result === null ||
+ !('queued' in result) ||
+ result.queued !== true
+ ) {
+ throw new Error('The agent did not confirm this message')
+ }
// The SSE echo (`pushHumanMessage`) reopens the turn — always the raw text the user typed.
actions.pushHumanMessage(content)
markPendingContextSent(pendingContext)
} catch {
+ if (!isCurrent()) {
+ return
+ }
actions.releaseApplyBackTargets(streamKey)
// Restore unsent content for retry, preserving send order — draft content goes back ahead of
// anything typed during the failed send, queue content re-stages ahead of anything staged since.
@@ -840,11 +1090,14 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
draft: values.composerForm.draft ? `${content}\n\n${values.composerForm.draft}` : content,
})
} else {
+ actions.queueDeliveryFailed()
actions.prependQueuedMessage(content)
}
lemonToast.error('Failed to send message. Please try again.')
} finally {
- actions.setSending(false)
+ if (isCurrent()) {
+ actions.setSending(false)
+ }
}
},
@@ -868,7 +1121,15 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
setMode: noteTerminalDraft,
setComposerFormValue: noteTerminalDraft,
setComposerFormValues: noteTerminalDraft,
- handleTerminalStatus: noteTerminalDraft,
+ handleTerminalStatus: () => {
+ if (values.isTerminal) {
+ invalidateSend()
+ }
+ noteTerminalDraft()
+ },
+ permissionRunChanged: invalidateSend,
+ resetStream: invalidateSend,
+ cancelPermissionDelivery: invalidateSend,
startNewRun: async ({ content }) => {
if (values.startingRun || !content.trim() || values.currentProjectId == null) {
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
index a2774e1bc20d..649d1e83503b 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
@@ -1,5 +1,6 @@
import { BindLogic, useActions, useValues } from 'kea'
import { router } from 'kea-router'
+import { useRef } from 'react'
import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
import { urls } from 'scenes/urls'
@@ -19,6 +20,7 @@ import { AttachedContextBar } from '../../../components/composer/AttachedContext
import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'
import { ComposerModePicker } from '../../../components/composer/ComposerModePicker'
import { ComposerModeShortcut } from '../../../components/composer/ComposerModeShortcut'
+import { ComposerSteerShortcut } from '../../../components/composer/ComposerSteerShortcut'
import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'
import { useForegroundStream } from '../../../hooks/useForegroundStream'
import { taskDetailSceneLogic } from '../taskDetailSceneLogic'
@@ -123,6 +125,8 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):
selectedEffort,
consentBlocked,
selectedMode,
+ composerActive,
+ steerPending,
} = useValues(runInteractionLogic(logicProps))
const { catalogue } = useValues(modelCatalogueLogic)
// A live run's harness is whatever it booted on; once terminal the next run follows the picked model.
@@ -137,15 +141,26 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):
setEffort,
clearConsentBlock,
setMode,
+ steerQueue,
+ submitAfterConsent,
} = useActions(runInteractionLogic(logicProps))
const draft = useDebouncedDraft(composerForm.draft, (value) => setComposerFormValues({ draft: value }))
+ const textAreaRef = useRef<HTMLTextAreaElement>(null)
return (
<>
- {/* Inside the slot children: detaches while a pending approval replaces the composer. */}
- <ComposerModeShortcut onCycle={() => setMode(cycleMode(composerAdapter, selectedMode))} />
+ <ComposerModeShortcut
+ disabled={!composerActive}
+ onCycle={() => setMode(cycleMode(composerAdapter, selectedMode))}
+ />
+ <ComposerSteerShortcut
+ textAreaRef={textAreaRef}
+ onSteer={steerQueue}
+ disabled={!composerActive || steerPending || !queuedMessages.length}
+ />
<Composer.Root
+ textAreaRef={textAreaRef}
value={draft.value}
onChange={draft.onChange}
onSubmit={() => draft.submit(submitComposerForm)}
@@ -159,6 +174,8 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):
messages={queuedMessages}
onUpdate={updateQueuedMessage}
onRemove={removeQueuedMessage}
+ onSteer={steerQueue}
+ steerPending={steerPending}
/>
</Composer.Banner>
)}
@@ -203,7 +220,7 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):
showArrow
ignoreDismissal
hidden={!consentBlocked}
- onApprove={() => submitComposerForm()}
+ onApprove={submitAfterConsent}
onDismiss={() => clearConsentBlock()}
>
<Composer.Submit data-attr="sandbox-composer-send" />