:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): add PHAI-agnostic task-run interaction logic (#65770)
Georgiy Tarasovdd1a928066cf
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 20adcc53d1fb..5a86f35c8fd8 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4312,6 +4312,46 @@ snapshots:hash: v1.k794b7964.adb3678ff40e8c2e4994ff26d079adb6be3d4c2f5775ea7789e79c6f5590da36.8AD0kOjHRUenn8Rfj-d6hlGsA0LxdZxKjvyCR4RKgmoposthog-3000-keyboard-shortcut--within-tooltip--light:hash: v1.k794b7964.83e30bce6eaf10ec2744cc16017cf71eeaffe0073f6bb86576a79030dde457b7.yEG2vJ43kwDAw3CfEjf2gQQJghMVMNmPDPXHnHp1TCg+ products-posthog-ai-composer--default--dark:+ hash: v1.k794b7964.31c024cc65743b20a76c2b03033bd4ad65fa137cf9e320f3037313905dbae212.Fdh8IsBHGzGigcejkmaY7rpiZZPfPGfI2CLskSAimvs+ products-posthog-ai-composer--default--light:+ hash: v1.k794b7964.0371f5ea5a14c84a8c0187900d23e28d957cefa33b1621b40ee445709099f41b.1yBsKGrmBrC6jS6fQ-ypXmiVhbFHjVb2Ja-n4J_5c9I+ products-posthog-ai-composer--disabled--dark:+ hash: v1.k794b7964.31c024cc65743b20a76c2b03033bd4ad65fa137cf9e320f3037313905dbae212.AJ-0DT6cRklR7ZZF5OzbYiCScBeOAKlVXunqfcxK82g+ products-posthog-ai-composer--disabled--light:+ hash: v1.k794b7964.0371f5ea5a14c84a8c0187900d23e28d957cefa33b1621b40ee445709099f41b.Q2r74gPninxNB4OnyxuwWQAN56tCq47qvcsiH1kk0yE+ products-posthog-ai-composer--filled--dark:+ hash: v1.k794b7964.e558effc1076de991c2d318bf69284ef6214984f9d997a5e33acdf41f450e8c9.62gwuizcqFa1YionZgj975v4gY7ACtXKfbt0-Do4V38+ products-posthog-ai-composer--filled--light:+ hash: v1.k794b7964.283356fd2e2853f0f914818ba50b27f74b28a2e83c830e8448f03a84c5625fb3.k9juWD41diCzQ-6ZRGvPAfiBAcWLzAMtV_eGOGxg7eU+ products-posthog-ai-composer--follow-up--dark:+ hash: v1.k794b7964.1576bc91c8068e6fb97a90cf40a82764ce789ec043fab7a680b4b3fca85827c2.l0axJvDqB5F7RB469DNg5E6fSdaQYnuuR6yjYY7vNro+ products-posthog-ai-composer--follow-up--light:+ hash: v1.k794b7964.47d1d49bb637bf02e2752ac3733d98784e9b3784a17367f3bcc6c6f671e6681b.dn_zPz5goSG5JcBkXp4x_59M_riKFjmva5Psco23oXo+ products-posthog-ai-composer--sticky--dark:+ hash: v1.k794b7964.82189c7eaa68a322167827e5fc88860d7e7da6ad75ccd8f2de4282218eedf127.4em2irQ84IgjnHRntaLlhjwouZDfgBfbyISCT7NbiF8+ products-posthog-ai-composer--sticky--light:+ hash: v1.k794b7964.1c7c39cad1e3581036f6b3ac5deee40b85bb336e6073ee4a52b1aa5136bc4fb7.5Gan-N28a2OElwScG4oTdLXCdbkLBE8_jJezFq3CrJo+ products-posthog-ai-composer--with-footer--dark:+ hash: v1.k794b7964.2e7714e7374f33427c893da6d3a1dbcb4aad48e348371b8b47339d26cda42886.cj22bY5VG6QK_wmKotRb6yYIiHlbdECQSOW6377fW-Y+ products-posthog-ai-composer--with-footer--light:+ hash: v1.k794b7964.a93dbdd90f6b020b5db36445cf6602896a1202e7b70967c87361fea2a22467ba.rZ-jPXNPLZG9ihNMvwFQx6uRlWiQMXdX_Cc5G2h6Pb8+ products-posthog-ai-composer--with-up-next-queue--dark:+ hash: v1.k794b7964.cd2aa250cb0392babd2d101fa53e63e99dd856116a7c95868a0ca224d9bd6711.04JeZhFKzyJ8K8usH1z3pNSFpbC5tElncTKSqpaUztc+ products-posthog-ai-composer--with-up-next-queue--light:+ hash: v1.k794b7964.be10c29dca25fe125d4f04a5a8df8727812636d608a923cc7f76e844e5b36c44.takLdpH-VIpnX3KpQETWZGziuOQDg4Yy3ZV3mwTz-OE+ products-posthog-ai-queuedmessagelist--empty--dark:+ hash: v1.k794b7964.4313fbb59e762d6fc4a87fed828bb6c814697c489997e23111f95df3d84be347.VRvN01m1Gf36IcNO8lzu8q3mqxKWwSRROgPqtbxMiSU+ products-posthog-ai-queuedmessagelist--empty--light:+ hash: v1.k794b7964.8ff99b0d11642dd53f5f0f70fc69106ee0e0158728fd6a73cf8699c4d68f8186.BQuDnKXQn4DwravdDwbmq3GC_BR06D3nntvW0bDvyzE+ products-posthog-ai-queuedmessagelist--multiple--dark:+ hash: v1.k794b7964.9ff0899b9a1563aa162851b530342f34588eccdcf9c1df47d4a9e31dd3507a60.pg3-1N2nigYi2NC1Fu6sB2OygQIZLx-hTkKKeqHutMY+ products-posthog-ai-queuedmessagelist--multiple--light:+ hash: v1.k794b7964.e09799b4e7552fc9539ec21f3552aa4c41d1b331b79e368cca91e8a75d5fea82.l19d_esENqAj3kf85pKCqu__bpDTQlrY6PDOyJCSDzA+ products-posthog-ai-queuedmessagelist--single--dark:+ hash: v1.k794b7964.2c8b08cca3b552e3ee3670eb19b017cd9b760982dff9128cde00bb8ae9029b8b.0_A_iSZDzamyJr0nr6qMXHrLFSVxf2C2WO2ZfzGkjnA+ products-posthog-ai-queuedmessagelist--single--light:+ hash: v1.k794b7964.80c03908f588a87222265093441fb1a923d47c312fdc4936d9396b1759a44232.-zIaOwO0H_QNqp98fu2Of3ZE-TL8tCQdVLfWQoun2wsproducts-workflows-customerioimportmodal--all-steps-completed--dark:hash: v1.k794b7964.679720cf72d72cd35bb4c4a2e86094627df27ff2798b4244c5d29a6a767f3861.AvZ-0V3qNglzE2ZWUOcEjHFnSe9Qs68t-u03-ytn7VIproducts-workflows-customerioimportmodal--all-steps-completed--light:diff --git a/products/posthog_ai/frontend/sandbox/components/QueuedMessageList.stories.tsx b/products/posthog_ai/frontend/sandbox/components/QueuedMessageList.stories.tsxnew file mode 100644index 000000000000..4ef715257ab8--- /dev/null+++ b/products/posthog_ai/frontend/sandbox/components/QueuedMessageList.stories.tsx@@ -0,0 +1,47 @@+import type { Meta, StoryObj } from '@storybook/react'+import { useState } from 'react'++import type { QueuedMessage } from '../taskRunInteractionLogic'+import { QueuedMessageList } from './QueuedMessageList'++// Logic-free and controlled — the story owns the queue and wires `onUpdate` / `onRemove`, exactly as the+// run surface does. Hover a row to reveal edit/remove; editing swaps the row for an inline editor.+const meta: Meta<typeof QueuedMessageList> = {+ title: 'Products/PostHog AI/QueuedMessageList',+ component: QueuedMessageList,+ tags: ['autodocs'],+ render: ({ messages }) => {+ const [queue, setQueue] = useState<QueuedMessage[]>(messages)+ return (+ <div className="max-w-180 mx-auto p-4">+ <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))}+ />+ </div>+ )+ },+}+export default meta++type Story = StoryObj<typeof QueuedMessageList>++export const Single: Story = {+ args: { messages: [{ id: '1', content: 'Also break it down by browser' }] },+}++export const Multiple: Story = {+ args: {+ messages: [+ { id: '1', content: 'Also break it down by browser' },+ { id: '2', content: 'And add a comparison to the previous period' },+ { id: '3', content: 'Then export the result to a dashboard' },+ ],+ },+}++/** Empty queue renders nothing — the consumer hides the Banner slot entirely. */+export const Empty: Story = {+ args: { messages: [] },+}diff --git a/products/posthog_ai/frontend/sandbox/components/QueuedMessageList.tsx b/products/posthog_ai/frontend/sandbox/components/QueuedMessageList.tsxnew file mode 100644index 000000000000..c43738c8464a--- /dev/null+++ b/products/posthog_ai/frontend/sandbox/components/QueuedMessageList.tsx@@ -0,0 +1,135 @@+import { useEffect, useRef, useState } from 'react'++import { IconCheck, IconPencil, IconTrash, IconX } from '@posthog/icons'+import { LemonButton, LemonTextArea } from '@posthog/lemon-ui'++import type { QueuedMessage } from '../taskRunInteractionLogic'++interface QueuedMessageListProps {+ messages: QueuedMessage[]+ onUpdate: (id: string, content: string) => void+ onRemove: (id: string) => void+}++interface QueuedMessageItemProps {+ message: QueuedMessage+ isEditing: boolean+ onEdit: () => void+ onCancel: () => void+ onSave: (id: string, content: string) => void+ onRemove: (id: string) => void+}++/** One staged "Up next" message — read row with edit/remove, or an inline editor. Logic-free (controlled). */+function QueuedMessageItem({+ message,+ isEditing,+ onEdit,+ onCancel,+ onSave,+ onRemove,+}: QueuedMessageItemProps): JSX.Element {+ const [draft, setDraft] = useState(message.content)+ const textAreaRef = useRef<HTMLTextAreaElement | null>(null)++ useEffect(() => {+ setDraft(message.content)+ }, [message.content])++ useEffect(() => {+ if (isEditing) {+ textAreaRef.current?.focus()+ textAreaRef.current?.select()+ }+ }, [isEditing])++ const canSave = draft.trim().length > 0++ if (isEditing) {+ return (+ <div className="space-y-2">+ <LemonTextArea+ ref={textAreaRef}+ value={draft}+ onChange={setDraft}+ minRows={1}+ maxRows={4}+ autoFocus+ onPressCmdEnter={() => {+ if (canSave) {+ onSave(message.id, draft)+ }+ }}+ />+ <div className="flex gap-1">+ <LemonButton+ size="xsmall"+ icon={<IconCheck />}+ onClick={() => onSave(message.id, draft)}+ disabledReason={canSave ? undefined : 'Message cannot be empty'}+ >+ Save+ </LemonButton>+ <LemonButton size="xsmall" type="secondary" icon={<IconX />} onClick={onCancel}>+ Cancel+ </LemonButton>+ </div>+ </div>+ )+ }++ 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">+ <LemonButton+ size="xsmall"+ type="tertiary"+ icon={<IconPencil className="text-muted" />}+ onClick={onEdit}+ tooltip="Edit message"+ />+ <LemonButton+ size="xsmall"+ type="tertiary"+ icon={<IconTrash className="text-muted" />}+ onClick={() => onRemove(message.id)}+ tooltip="Remove from queue"+ />+ </div>+ </div>+ )+}++/**+ * 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+ * `QueuedMessageItem`, minus the conversation/Max coupling.+ */+export function QueuedMessageList({ messages, onUpdate, onRemove }: QueuedMessageListProps): JSX.Element | null {+ const [editingId, setEditingId] = useState<string | null>(null)++ if (messages.length === 0) {+ return null+ }++ 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>+ {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>+ )+}diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.test.tsx b/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.test.tsxindex 73412e70fb5e..b421c1a7eb03 100644--- a/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.test.tsx+++ b/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.test.tsx@@ -83,10 +83,10 @@ describe('SandboxRunViewer', () => {})it.each<SandboxRunStatus>(['completed', 'failed', 'cancelled'])(- 'never shows the composer for a terminal run (%s)',+ 'shows the composer for a terminal run so a new run can be started (%s)',(status) => {renderLive(status)- expect(screen.queryByTestId('composer')).not.toBeInTheDocument()+ expect(screen.getByTestId('composer')).toBeInTheDocument()})diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsx b/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsxindex 5ac942c85c4a..11fc2f680153 100644--- a/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsx+++ b/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsx@@ -6,7 +6,9 @@ import { Spinner } from '@posthog/lemon-ui'import { cn } from 'lib/utils/css-classes'import { isTerminalRunStatus, sandboxStreamLogic } from '../sandboxStreamLogic'+import type { QueuedMessage } from '../taskRunInteractionLogic'import { Composer } from './composer/Composer'+import { QueuedMessageList } from './QueuedMessageList'import { SandboxContextUsage } from './SandboxContextUsage'import { SandboxPermissionInput } from './SandboxPermissionInput'import { SandboxQuestionInput } from './SandboxQuestionInput'@@ -38,6 +40,13 @@ export interface SandboxRunViewerProps {onComposerSubmit?: () => voidcomposerLoading?: booleancomposerPlaceholder?: string+ /**+ * Editable "Up next" queue — live mode only, rendered above the composer when non-empty. Provide all+ * three to surface staged follow-ups; the consumer owns the queue (this module never mutates it).+ */+ queuedMessages?: QueuedMessage[]+ onUpdateQueuedMessage?: (id: string, content: string) => void+ onRemoveQueuedMessage?: (id: string) => void}/**@@ -59,6 +68,9 @@ export function SandboxRunViewer({onComposerSubmit,composerLoading,composerPlaceholder,+ queuedMessages,+ onUpdateQueuedMessage,+ onRemoveQueuedMessage,}: SandboxRunViewerProps): JSX.Element {const replayOnly = interaction !== 'live'return (@@ -74,6 +86,9 @@ export function SandboxRunViewer({onComposerSubmit={onComposerSubmit}composerLoading={composerLoading}composerPlaceholder={composerPlaceholder}+ queuedMessages={queuedMessages}+ onUpdateQueuedMessage={onUpdateQueuedMessage}+ onRemoveQueuedMessage={onRemoveQueuedMessage}/></BindLogic>)@@ -92,6 +107,9 @@ interface SandboxRunViewerContentProps {onComposerSubmit?: () => voidcomposerLoading?: booleancomposerPlaceholder?: string+ queuedMessages?: QueuedMessage[]+ onUpdateQueuedMessage?: (id: string, content: string) => void+ onRemoveQueuedMessage?: (id: string) => void}function SandboxRunViewerContent({@@ -105,6 +123,9 @@ function SandboxRunViewerContent({onComposerSubmit,composerLoading,composerPlaceholder,+ queuedMessages,+ onUpdateQueuedMessage,+ onRemoveQueuedMessage,}: SandboxRunViewerContentProps): JSX.Element {const { bootstrapLoading, threadItems, pendingPermissionRequest, currentRunStatus } = useValues(sandboxStreamLogic)const { bootstrapRun, reset } = useActions(sandboxStreamLogic)@@ -127,10 +148,11 @@ function SandboxRunViewerContent({const showApproval = isLive && !!pendingPermissionRequest && !isTerminalRunStatus(currentRunStatus)const isQuestion = !!pendingPermissionRequest?.questions && pendingPermissionRequest.questions.length > 0const hasComposer = isLive && !!onComposerSubmit && onComposerChange !== undefined && composerValue !== undefined- const showComposer =- hasComposer &&- !pendingPermissionRequest &&- (currentRunStatus === 'queued' || currentRunStatus === 'in_progress')+ // The composer shows for any settled run status — active runs take a follow-up, terminal runs start a+ // fresh run from the typed message. It's hidden only during the `null` bootstrap window and while a+ // permission/question prompt is pending.+ const isRunTerminal = isTerminalRunStatus(currentRunStatus)+ const showComposer = hasComposer && !pendingPermissionRequest && currentRunStatus !== nullconst thread = showSpinner ? (<div className="flex justify-center py-8">@@ -172,10 +194,25 @@ function SandboxRunViewerContent({onSubmit={onComposerSubmit!}loading={composerLoading}>+ {queuedMessages &&+ queuedMessages.length > 0 &&+ onUpdateQueuedMessage &&+ onRemoveQueuedMessage && (+ <Composer.Banner>+ <QueuedMessageList+ messages={queuedMessages}+ onUpdate={onUpdateQueuedMessage}+ onRemove={onRemoveQueuedMessage}+ />+ </Composer.Banner>+ )}<Composer.Frame><Composer.Field><Composer.Placeholder>- {composerPlaceholder ?? 'Send a follow-up message…'}+ {composerPlaceholder ??+ (isRunTerminal+ ? 'Send a message to start a new run…'+ : 'Send a follow-up message…')}</Composer.Placeholder><Composer.Textarea data-attr="sandbox-composer-input" submitShortcut="cmd-enter" /></Composer.Field>diff --git a/products/posthog_ai/frontend/sandbox/components/composer/Composer.stories.tsx b/products/posthog_ai/frontend/sandbox/components/composer/Composer.stories.tsxnew file mode 100644index 000000000000..1e9f66080091--- /dev/null+++ b/products/posthog_ai/frontend/sandbox/components/composer/Composer.stories.tsx@@ -0,0 +1,155 @@+import type { Meta, StoryObj } from '@storybook/react'+import { useState } from 'react'++import { IconGear } from '@posthog/icons'+import { LemonButton, LemonTag } from '@posthog/lemon-ui'++import { QueuedMessageList } from '../QueuedMessageList'+import { Composer } from './Composer'++// The Composer primitives are logic-free and controlled, so the stories own the value/submit state and+// assemble the parts the same way a real surface (the tasks run viewer, PostHog AI) does.+interface ComposerStoryArgs {+ initialValue: string+ placeholder: string+ loading: boolean+ disabled: boolean+ disabledReason?: string+ isSticky: boolean+ isThreadVisible: boolean+ submitShortcut: 'enter' | 'cmd-enter'+}++type Story = StoryObj<ComposerStoryArgs>++const meta: Meta<ComposerStoryArgs> = {+ title: 'Products/PostHog AI/Composer',+ tags: ['autodocs'],+ args: {+ initialValue: '',+ placeholder: 'Ask anything…',+ loading: false,+ disabled: false,+ disabledReason: undefined,+ isSticky: false,+ isThreadVisible: false,+ submitShortcut: 'enter',+ },+ argTypes: {+ submitShortcut: { control: 'radio', options: ['enter', 'cmd-enter'] },+ },+ render: ({ initialValue, placeholder, submitShortcut, ...rootProps }) => {+ const [value, setValue] = useState(initialValue)+ return (+ <div className="max-w-180 mx-auto p-4">+ <Composer.Root value={value} onChange={setValue} onSubmit={() => setValue('')} {...rootProps}>+ <Composer.Frame>+ <Composer.Field>+ <Composer.Placeholder>{placeholder}</Composer.Placeholder>+ <Composer.Textarea submitShortcut={submitShortcut} />+ </Composer.Field>+ </Composer.Frame>+ <Composer.Submit />+ </Composer.Root>+ </div>+ )+ },+}+export default meta++/** Empty input — the overlaid placeholder shows and the send button is blocked. */+export const Default: Story = {}++/** Non-empty input — the placeholder hides and the send button is enabled. */+export const Filled: Story = {+ args: { initialValue: 'Show me weekly active users for the last 90 days' },+}++/** Mid-send: the button spins and submission is blocked. */+export const Loading: Story = {+ args: { initialValue: 'Send this follow-up', loading: true },+ // The send button spins indefinitely while loading, which the snapshot runner waits forever to settle.+ tags: ['test-skip'],+}++/** A caller-supplied reason disables the input beyond the built-in empty/loading gating. */+export const Disabled: Story = {+ args: { disabled: true, disabledReason: 'Connect a data source first' },+}++/** Follow-up variant: tighter frame radius/border and a nudged send button (`isThreadVisible`). */+export const FollowUp: Story = {+ args: { initialValue: 'One more thing…', isThreadVisible: true, submitShortcut: 'cmd-enter' },+}++/** Page-level sticky chrome: bordered, blurred, bottom-pinned container around the frame. */+export const Sticky: Story = {+ args: { isSticky: true },+ decorators: [+ (StoryFn) => (+ <div className="h-96 overflow-y-auto bg-bg-light flex flex-col justify-end">+ <StoryFn />+ </div>+ ),+ ],+}++/** With a footer row for context chips / actions inside the frame. */+export const WithFooter: Story = {+ render: ({ initialValue, placeholder, submitShortcut, ...rootProps }) => {+ const [value, setValue] = useState(initialValue)+ return (+ <div className="max-w-180 mx-auto p-4">+ <Composer.Root value={value} onChange={setValue} onSubmit={() => setValue('')} {...rootProps}>+ <Composer.Frame>+ <Composer.Field>+ <Composer.Placeholder>{placeholder}</Composer.Placeholder>+ <Composer.Textarea submitShortcut={submitShortcut} />+ </Composer.Field>+ <Composer.Footer>+ <div className="flex items-center gap-1 pl-2">+ <LemonTag type="muted">@ Current dashboard</LemonTag>+ <LemonButton size="xsmall" type="tertiary" icon={<IconGear />} tooltip="Settings" />+ </div>+ </Composer.Footer>+ </Composer.Frame>+ <Composer.Submit />+ </Composer.Root>+ </div>+ )+ },+}++/** Editable "Up next" queue rendered in the Banner slot above the frame (the tasks follow-up surface). */+export const WithUpNextQueue: Story = {+ args: { isThreadVisible: true, submitShortcut: 'cmd-enter' },+ render: ({ initialValue, placeholder, submitShortcut, ...rootProps }) => {+ const [value, setValue] = useState(initialValue)+ const [queue, setQueue] = useState([+ { id: '1', content: 'Also break it down by browser' },+ { id: '2', content: 'And add a comparison to the previous period' },+ ])+ return (+ <div className="max-w-180 mx-auto p-4">+ <Composer.Root value={value} onChange={setValue} onSubmit={() => setValue('')} {...rootProps}>+ <Composer.Banner>+ <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))}+ />+ </Composer.Banner>+ <Composer.Frame>+ <Composer.Field>+ <Composer.Placeholder>{placeholder}</Composer.Placeholder>+ <Composer.Textarea submitShortcut={submitShortcut} />+ </Composer.Field>+ </Composer.Frame>+ <Composer.Submit />+ </Composer.Root>+ </div>+ )+ },+}diff --git a/products/posthog_ai/frontend/sandbox/index.ts b/products/posthog_ai/frontend/sandbox/index.tsindex 7cf36ae766ff..7d2c0712f30e 100644--- a/products/posthog_ai/frontend/sandbox/index.ts+++ b/products/posthog_ai/frontend/sandbox/index.ts@@ -21,6 +21,9 @@ export { SandboxThreadView } from './components/SandboxThreadView'export { sandboxStreamLogic, isTerminalRunStatus, SANDBOX_INITIAL_PERMISSION_MODE } from './sandboxStreamLogic'export type { SandboxStreamLogicProps, SandboxSseStatus, SandboxRunStatus } from './sandboxStreamLogic'+export { taskRunInteractionLogic } from './taskRunInteractionLogic'+export type { TaskRunInteractionLogicProps, QueuedMessage } from './taskRunInteractionLogic'+export { SandboxPermissionInput } from './components/SandboxPermissionInput'export { SandboxQuestionInput } from './components/SandboxQuestionInput'export { SandboxResourcesBar } from './components/SandboxResourcesBar'diff --git a/products/posthog_ai/frontend/sandbox/taskRunInteractionLogic.test.ts b/products/posthog_ai/frontend/sandbox/taskRunInteractionLogic.test.tsnew file mode 100644index 000000000000..1fb28c5f79f6--- /dev/null+++ b/products/posthog_ai/frontend/sandbox/taskRunInteractionLogic.test.ts@@ -0,0 +1,382 @@+import { expectLogic } from 'kea-test-utils'++import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { projectLogic } from 'scenes/projectLogic'++import { initKeaTests } from '~/test/init'++import { tasksRunCreate, tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'++import { sandboxStreamLogic } from './sandboxStreamLogic'+import { taskRunInteractionLogic } from './taskRunInteractionLogic'++// Minimal kea stub for the shared sandbox stream logic — gives the test full control over the busy gate+// (`isThinking`) and `currentRunStatus`, and lets us fire `markTurnComplete` and observe `pushHumanMessage`+// without the real SSE machinery.+jest.mock('./sandboxStreamLogic', () => {+ const { kea, actions, key, path, props, reducers } = jest.requireActual('kea')+ const stub = kea([+ path(['test', 'sandboxStreamLogicStub']),+ props({}),+ key((p: { streamKey: string }) => p.streamKey),+ actions({+ pushHumanMessage: (content: string) => ({ content }),+ respondToPermission: (payload: unknown) => ({ payload }),+ cancelRun: (run?: unknown) => ({ run }),+ markTurnComplete: true,+ setStubStatus: (status: string | null) => ({ status }),+ setStubThinking: (thinking: boolean) => ({ thinking }),+ }),+ reducers({+ currentRunStatus: [+ 'in_progress',+ {+ setStubStatus: (_: string | null, { status }: { status: string | null }) => status,+ },+ ],+ isThinking: [+ false,+ {+ setStubThinking: (_: boolean, { thinking }: { thinking: boolean }) => thinking,+ },+ ],+ pendingPermissionRequest: [null, {}],+ respondingToPermission: [false, {}],+ }),+ ])+ return {+ sandboxStreamLogic: stub,+ isTerminalRunStatus: (status: string | null) =>+ status != null && ['completed', 'failed', 'cancelled'].includes(status),+ }+})++jest.mock('scenes/projectLogic', () => {+ const { kea, actions, path, reducers } = jest.requireActual('kea')+ const stub = kea([+ path(['test', 'projectLogicStub']),+ actions({ setCurrentProjectId: (id: number | null) => ({ id }) }),+ reducers({+ currentProjectId: [+ 997,+ {+ setCurrentProjectId: (_: number | null, { id }: { id: number | null }) => id,+ },+ ],+ }),+ ])+ return { projectLogic: stub }+})++jest.mock('products/tasks/frontend/generated/api', () => ({+ tasksRunsCommandCreate: jest.fn(),+ tasksRunCreate: jest.fn(),+}))++jest.mock('lib/lemon-ui/LemonToast', () => ({+ lemonToast: { error: jest.fn() },+}))++describe('taskRunInteractionLogic', () => {+ let logic: ReturnType<typeof taskRunInteractionLogic.build>+ let stream: ReturnType<typeof sandboxStreamLogic.build>+ let project: ReturnType<typeof projectLogic.build>++ const TASK_ID = 'task-1'+ const RUN_ID = 'run-1'+ const onRunStarted = jest.fn()++ // `setStubStatus` / `setStubThinking` exist only on the jest-mocked stub, not the real logic type.+ const setStatus = (status: string | null): void =>+ (stream.actions as unknown as { setStubStatus: (status: string | null) => void }).setStubStatus(status)+ const setThinking = (thinking: boolean): void =>+ (stream.actions as unknown as { setStubThinking: (thinking: boolean) => void }).setStubThinking(thinking)++ const userMessageCommand = (content: string): [string, string, string, Record<string, unknown>] => [+ '997',+ TASK_ID,+ RUN_ID,+ { jsonrpc: '2.0', method: 'user_message', params: { content } },+ ]++ beforeEach(() => {+ jest.clearAllMocks()+ ;(tasksRunsCommandCreate as jest.Mock).mockResolvedValue({})+ ;(tasksRunCreate as jest.Mock).mockResolvedValue({ latest_run: 'run-2' })+ initKeaTests()+ project = projectLogic()+ project.mount()+ stream = sandboxStreamLogic({ streamKey: RUN_ID })+ stream.mount()+ logic = taskRunInteractionLogic({ taskId: TASK_ID, runId: RUN_ID, onRunStarted })+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ stream?.unmount()+ project?.unmount()+ })++ it('sends immediately and echoes the message when the agent is idle', async () => {+ setThinking(false)+ logic.actions.setDraft('ship it')++ await expectLogic(logic, () => {+ logic.actions.submit()+ }).toFinishAllListeners()++ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('ship it'))+ await expectLogic(stream).toDispatchActions(['pushHumanMessage'])+ expect(logic.values.draft).toBe('')+ expect(logic.values.queuedMessages).toEqual([])+ })++ it('stages the message in the queue while the agent is busy', async () => {+ setThinking(true)+ logic.actions.setDraft('follow up')++ await expectLogic(logic, () => {+ logic.actions.submit()+ }).toFinishAllListeners()++ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()+ expect(logic.values.draft).toBe('')+ 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 () => {+ setThinking(true)+ logic.actions.setDraft('first')+ logic.actions.submit()+ logic.actions.setDraft('second')+ logic.actions.submit()+ // 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' }])++ // Turn completes → drain. The flush itself sends while idle.+ setThinking(false)+ await expectLogic(logic, () => {+ stream.actions.markTurnComplete()+ }).toFinishAllListeners()++ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('first\n\nsecond'))+ expect(logic.values.queuedMessages).toEqual([])+ })++ it('edits and removes staged messages', async () => {+ setThinking(true)+ logic.actions.setDraft('typo')+ logic.actions.submit()+ const { id } = logic.values.queuedMessages[0]++ logic.actions.updateQueuedMessage(id, 'fixed')+ expect(logic.values.queuedMessages).toEqual([{ id, content: 'fixed' }])++ logic.actions.removeQueuedMessage(id)+ expect(logic.values.queuedMessages).toEqual([])+ })++ it('keeps the draft and toasts when the send fails', async () => {+ ;(tasksRunsCommandCreate as jest.Mock).mockRejectedValue(new Error('boom'))+ setThinking(false)+ logic.actions.setDraft('ship it')++ await expectLogic(logic, () => {+ logic.actions.submit()+ }).toFinishAllListeners()++ expect(lemonToast.error).toHaveBeenCalled()+ expect(logic.values.draft).toBe('ship it')+ expect(logic.values.sending).toBe(false)+ })++ it('starts a fresh run seeded with the message when the run is terminal', async () => {+ setStatus('completed')+ logic.actions.setDraft('continue from here')++ await expectLogic(logic, () => {+ logic.actions.submit()+ }).toFinishAllListeners()++ // No live-run signal for a finished run — it resumes into a new run instead.+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()+ expect(tasksRunCreate).toHaveBeenCalledWith('997', TASK_ID, {+ resume_from_run_id: RUN_ID,+ pending_user_message: 'continue from here',+ })+ expect(onRunStarted).toHaveBeenCalledWith('run-2')+ expect(logic.values.queuedMessages).toEqual([])+ expect(logic.values.draft).toBe('')+ })++ it('keeps the draft and toasts when starting a new run fails', async () => {+ ;(tasksRunCreate as jest.Mock).mockRejectedValue(new Error('boom'))+ setStatus('completed')+ logic.actions.setDraft('continue from here')++ await expectLogic(logic, () => {+ logic.actions.submit()+ }).toFinishAllListeners()++ expect(lemonToast.error).toHaveBeenCalled()+ expect(onRunStarted).not.toHaveBeenCalled()+ expect(logic.values.draft).toBe('continue from here')+ })++ const setProjectId = (id: number | null): void =>+ (project.actions as unknown as { setCurrentProjectId: (id: number | null) => void }).setCurrentProjectId(id)++ it('no-ops and keeps the draft when submitting idle without a current project', async () => {+ setProjectId(null)+ setThinking(false)+ logic.actions.setDraft('ship it')++ await expectLogic(logic, () => {+ logic.actions.submit()+ }).toFinishAllListeners()++ // Nothing can be sent without a project — the draft is preserved rather than dropped.+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()+ expect(logic.values.draft).toBe('ship it')+ expect(logic.values.queuedMessages).toEqual([])+ })++ it('stages the message while busy without a current project and never silently sends it', async () => {+ setProjectId(null)+ setThinking(true)+ logic.actions.setDraft('follow up')++ await expectLogic(logic, () => {+ logic.actions.submit()+ }).toFinishAllListeners()++ // Busy + no project: the message is staged, and the guarded flush keeps it there rather than POSTing.+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()+ expect(logic.values.draft).toBe('')+ expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'follow up' }])+ })++ 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()+ })+ )++ // Idle send straight from the draft: the draft is cleared up-front, before the await.+ setThinking(false)+ logic.actions.setDraft('ship it')+ logic.actions.submit()+ expect(logic.values.sending).toBe(true)+ expect(logic.values.draft).toBe('')++ // The user keeps typing while the send is in flight.+ logic.actions.setDraft('next thought')++ await expectLogic(logic, () => {+ resolveSend()+ }).toFinishAllListeners()++ // Success leaves the composer alone — the newly typed text survives rather than being wiped.+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('ship it'))+ expect(logic.values.draft).toBe('next thought')+ })++ it('restores a failed draft send ahead of text typed during the send, preserving order', async () => {+ let rejectSend: () => void = () => {}+ ;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(+ new Promise<void>((_, reject) => {+ rejectSend = () => reject(new Error('boom'))+ })+ )++ setThinking(false)+ logic.actions.setDraft('ship it')+ logic.actions.submit()+ expect(logic.values.draft).toBe('')++ logic.actions.setDraft('next thought')++ await expectLogic(logic, () => {+ rejectSend()+ }).toFinishAllListeners()++ // The failed send puts the original back in front of what was typed since, so nothing is lost.+ expect(lemonToast.error).toHaveBeenCalled()+ expect(logic.values.draft).toBe('ship it\n\nnext thought')+ })++ 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()+ })+ )++ // Stage a message while busy, then complete the turn to start flushing it.+ setThinking(true)+ logic.actions.setDraft('first')+ logic.actions.submit()++ setThinking(false)+ stream.actions.markTurnComplete()+ // The flush is now in flight: the buffer is cleared up-front so a new follow-up stages cleanly.+ expect(logic.values.sending).toBe(true)+ expect(logic.values.queuedMessages).toEqual([])++ logic.actions.setDraft('second')+ logic.actions.submit()+ expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'second' }])++ await expectLogic(logic, () => {+ resolveSend()+ }).toFinishAllListeners()++ // Only the first message was sent; the follow-up survives the flush rather than being lost.+ expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('first'))+ expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'second' }])+ })++ it('re-stages a queued message ahead of newer follow-ups when its flush fails', async () => {+ let rejectSend: () => void = () => {}+ ;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(+ new Promise<void>((_, reject) => {+ rejectSend = () => reject(new Error('boom'))+ })+ )++ setThinking(true)+ logic.actions.setDraft('first')+ logic.actions.submit()++ setThinking(false)+ stream.actions.markTurnComplete()+ expect(logic.values.queuedMessages).toEqual([])++ // A follow-up staged while the flush is in flight.+ logic.actions.setDraft('second')+ logic.actions.submit()++ await expectLogic(logic, () => {+ rejectSend()+ }).toFinishAllListeners()++ // 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' }])+ })++ it('no-ops on submit with an empty draft', async () => {+ await expectLogic(logic, () => {+ logic.actions.submit()+ }).toFinishAllListeners()++ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()+ expect(logic.values.queuedMessages).toEqual([])+ })+})diff --git a/products/posthog_ai/frontend/sandbox/taskRunInteractionLogic.ts b/products/posthog_ai/frontend/sandbox/taskRunInteractionLogic.tsnew file mode 100644index 000000000000..3bcbc4618a25--- /dev/null+++ b/products/posthog_ai/frontend/sandbox/taskRunInteractionLogic.ts@@ -0,0 +1,243 @@+import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'++import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { projectLogic } from 'scenes/projectLogic'++import { tasksRunCreate, tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'+import type { TaskRunResumeRequestSchemaApi } from 'products/tasks/frontend/generated/api.schemas'++import { isTerminalRunStatus, sandboxStreamLogic } from './sandboxStreamLogic'+import type { taskRunInteractionLogicType } from './taskRunInteractionLogicType'++export interface TaskRunInteractionLogicProps {+ taskId: string+ runId: string+ /** Called with the new run's id after a terminal-run send starts a fresh run, so the surface can+ * re-point selection to it (the run lifecycle / selection is a tasks-scene concern, injected here). */+ onRunStarted?: (runId: string) => void+}++/** The follow-up staged in the "Up next" buffer 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'++/**+ * Max-agnostic interaction facade for a single task run. The UI binds to this one logic to drive every+ * user → run interaction — sending follow-ups, staging an editable "Up next" message while the agent is+ * busy, and (re-exposed from `sandboxStreamLogic`) answering questions / approving operations. It owns no+ * transport: the SSE stream, thread projection, run status, and permission routing all live in+ * `sandboxStreamLogic`, 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.+ */+export const taskRunInteractionLogic = kea<taskRunInteractionLogicType>([+ path(['products', 'posthog_ai', 'frontend', 'sandbox', 'taskRunInteractionLogic']),+ props({} as TaskRunInteractionLogicProps),+ key((props) => props.runId),++ connect((props: TaskRunInteractionLogicProps) => ({+ values: [+ projectLogic,+ ['currentProjectId'],+ sandboxStreamLogic({ streamKey: props.runId }),+ ['currentRunStatus', 'pendingPermissionRequest', 'respondingToPermission', 'isThinking'],+ ],+ actions: [+ sandboxStreamLogic({ streamKey: props.runId }),+ ['pushHumanMessage', 'respondToPermission', 'cancelRun', 'markTurnComplete'],+ ],+ })),++ actions({+ setDraft: (draft: string) => ({ draft }),+ clearDraft: true,+ // Single entry point the composer's `onSubmit` calls — decides send-now vs enqueue vs new-run.+ submit: true,+ setSending: (sending: boolean) => ({ sending }),+ // 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 }),+ // 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 }),+ // 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.+ prependQueuedMessage: (content: string) => ({ content }),+ updateQueuedMessage: (id: string, content: string) => ({ id, content }),+ removeQueuedMessage: (id: string) => ({ id }),+ clearQueue: true,+ // Internal: drain the staged "Up next" message when the agent is idle.+ flushQueue: true,+ }),++ reducers({+ draft: [+ '',+ {+ setDraft: (_, { draft }) => draft,+ clearDraft: () => '',+ },+ ],+ sending: [+ false,+ {+ setSending: (_, { sending }) => sending,+ },+ ],+ startingRun: [+ false,+ {+ setStartingRun: (_, { starting }) => starting,+ },+ ],+ 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 }],+ updateQueuedMessage: (state, { id, content }) =>+ state.map((message) => (message.id === id ? { ...message, content } : message)),+ removeQueuedMessage: (state, { id }) => state.filter((message) => message.id !== id),+ clearQueue: () => [],+ },+ ],+ }),++ selectors({+ isTerminal: [(s) => [s.currentRunStatus], (status): boolean => isTerminalRunStatus(status)],+ // The agent is actively working a turn — a follow-up typed now should stage rather than send.+ isBusy: [(s) => [s.isThinking], (isThinking): boolean => isThinking],+ canSend: [+ (s) => [s.sending, s.isTerminal, s.currentProjectId],+ (sending, isTerminal, currentProjectId): boolean => !sending && !isTerminal && currentProjectId != null,+ ],+ // In-flight indicator for the composer's send button — a live send or a new-run start.+ isSubmitting: [(s) => [s.sending, s.startingRun], (sending, startingRun): boolean => sending || startingRun],+ }),++ listeners(({ actions, values, props }) => ({+ submit: () => {+ const content = values.draft.trim()+ if (!content) {+ return+ }+ // A finished run can't take a follow-up signal — send starts a fresh run instead, seeded with+ // this message and chained from the run just viewed.+ if (values.isTerminal) {+ actions.startNewRun(content)+ return+ }+ // 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) {+ actions.enqueueMessage(content)+ actions.clearDraft()+ actions.flushQueue()+ } else {+ actions.sendNow(content, 'draft')+ }+ },++ // 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: () => {+ const [queued] = values.queuedMessages+ if (!queued || values.isBusy || !values.canSend) {+ return+ }+ actions.clearQueue()+ actions.sendNow(queued.content, 'queue')+ },++ sendNow: async ({ content, source }) => {+ if (values.sending || !content.trim() || values.isTerminal || values.currentProjectId == null) {+ // 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)+ }+ return+ }+ actions.setSending(true)+ // Clear the draft synchronously before the await so text the user types while the send is in+ // flight isn't clobbered when the request resolves; a failed send restores it ahead of anything+ // typed since. The queue buffer was already cleared up-front in `flushQueue`.+ if (source === 'draft') {+ actions.clearDraft()+ }+ try {+ await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {+ jsonrpc: '2.0',+ method: 'user_message',+ params: { content },+ })+ // The SSE echo (`pushHumanMessage`) reopens the turn.+ actions.pushHumanMessage(content)+ } catch {+ // Restore unsent content for retry, preserving send order — draft content goes back ahead of+ // anything typed during the failed send, queue content re-stages ahead of anything staged since.+ if (source === 'draft') {+ actions.setDraft(values.draft ? `${content}\n\n${values.draft}` : content)+ } else {+ actions.prependQueuedMessage(content)+ }+ lemonToast.error('Failed to send message. Please try again.')+ } finally {+ actions.setSending(false)+ }+ },++ // The agent finished a turn — drain any staged follow-ups.+ markTurnComplete: () => {+ actions.flushQueue()+ },++ startNewRun: async ({ content }) => {+ if (values.startingRun || !content.trim() || values.currentProjectId == null) {+ return+ }+ actions.setStartingRun(true)+ try {+ // Same endpoint as the "Run again" button, but seeded with the user's message and chained+ // from the finished run so the new run continues the thread. The response carries the new+ // run id as `latest_run`; the consumer-provided `onRunStarted` re-points selection to it.+ const resumeRequest: TaskRunResumeRequestSchemaApi = {+ resume_from_run_id: props.runId,+ pending_user_message: content,+ }+ const result = await tasksRunCreate(String(values.currentProjectId), props.taskId, resumeRequest)+ actions.clearDraft()+ if (result.latest_run) {+ props.onRunStarted?.(result.latest_run)+ }+ } catch {+ lemonToast.error('Failed to start a new run. Please try again.')+ } finally {+ actions.setStartingRun(false)+ }+ },+ })),+])diff --git a/products/tasks/frontend/components/TaskRunChat.tsx b/products/tasks/frontend/components/TaskRunChat.tsxindex c2e314ccef6e..19ff2c95bf4c 100644--- a/products/tasks/frontend/components/TaskRunChat.tsx+++ b/products/tasks/frontend/components/TaskRunChat.tsx@@ -1,8 +1,12 @@import { BindLogic, useActions, useValues } from 'kea'-import { SandboxRunViewer } from 'products/posthog_ai/frontend/sandbox'+import {+ SandboxRunViewer,+ type TaskRunInteractionLogicProps,+ taskRunInteractionLogic,+} from 'products/posthog_ai/frontend/sandbox'-import { taskRunChatLogic } from '../logics/taskRunChatLogic'+import { taskDetailSceneLogic } from '../logics/taskDetailSceneLogic'export interface TaskRunChatProps {taskId: string@@ -10,32 +14,49 @@ export interface TaskRunChatProps {}/**- * Live task-run surface. Binds `taskRunChatLogic` (which connects to the shared `sandboxStreamLogic`- * keyed by `runId`) and renders `SandboxRunViewer` in live mode with the composer wired to the task-run- * command logic. The viewer owns bootstrap: it reads the run status from the tasks API and never opens- * SSE for an already-terminal run.+ * Live task-run surface. Binds `taskRunInteractionLogic` (the Max-agnostic interaction facade, which+ * connects to the shared `sandboxStreamLogic` keyed by `runId`) and renders `SandboxRunViewer` in live+ * mode with the composer + "Up next" queue wired to it. The composer stays visible after a run finishes;+ * sending then starts a fresh run (seeded with the message), and `onRunStarted` re-points scene selection+ * to it. The viewer owns bootstrap: it reads the run status from the tasks API and never opens SSE for an+ * already-terminal run.*/export function TaskRunChat({ taskId, runId }: TaskRunChatProps): JSX.Element {+ const { setSelectedRunId, loadTaskRuns } = useActions(taskDetailSceneLogic({ taskId }))+ const logicProps: TaskRunInteractionLogicProps = {+ taskId,+ runId,+ onRunStarted: (newRunId) => {+ setSelectedRunId(newRunId, taskId)+ loadTaskRuns()+ },+ }+return (- <BindLogic logic={taskRunChatLogic} props={{ taskId, runId }}>- <TaskRunChatContent taskId={taskId} runId={runId} />+ <BindLogic logic={taskRunInteractionLogic} props={logicProps}>+ <TaskRunChatContent logicProps={logicProps} /></BindLogic>)}-function TaskRunChatContent({ taskId, runId }: TaskRunChatProps): JSX.Element {- const { composerDraft, sendingMessage } = useValues(taskRunChatLogic({ taskId, runId }))- const { setComposerDraft, sendMessage } = useActions(taskRunChatLogic({ taskId, runId }))+function TaskRunChatContent({ logicProps }: { logicProps: TaskRunInteractionLogicProps }): JSX.Element {+ const { draft, isSubmitting, queuedMessages } = useValues(taskRunInteractionLogic(logicProps))+ const { setDraft, submit, updateQueuedMessage, removeQueuedMessage } = useActions(+ taskRunInteractionLogic(logicProps)+ )return (<SandboxRunViewer- taskId={taskId}- runId={runId}+ taskId={logicProps.taskId}+ runId={logicProps.runId}interaction="live"- composerValue={composerDraft}- onComposerChange={setComposerDraft}- onComposerSubmit={() => sendMessage(composerDraft)}- composerLoading={sendingMessage}+ composerValue={draft}+ onComposerChange={setDraft}+ onComposerSubmit={submit}+ composerLoading={isSubmitting}+ queuedMessages={queuedMessages}+ onUpdateQueuedMessage={updateQueuedMessage}+ onRemoveQueuedMessage={removeQueuedMessage}/>)}diff --git a/products/tasks/frontend/logics/taskRunChatLogic.test.ts b/products/tasks/frontend/logics/taskRunChatLogic.test.tsdeleted file mode 100644index b477c9870d18..000000000000--- a/products/tasks/frontend/logics/taskRunChatLogic.test.ts+++ /dev/null@@ -1,174 +0,0 @@-import { expectLogic } from 'kea-test-utils'--import { lemonToast } from 'lib/lemon-ui/LemonToast'-import { projectLogic } from 'scenes/projectLogic'--import { initKeaTests } from '~/test/init'--import { sandboxStreamLogic } from 'products/posthog_ai/frontend/sandbox'--import { tasksRunsCommandCreate } from '../generated/api'-import { taskRunChatLogic } from './taskRunChatLogic'--// Minimal kea stub for the shared sandbox stream logic — gives the test full control over-// `currentRunStatus` and lets us observe `pushHumanMessage` without the real SSE machinery.-jest.mock('products/posthog_ai/frontend/sandbox', () => {- const { kea, actions, key, path, props, reducers } = jest.requireActual('kea')- const stub = kea([- path(['test', 'sandboxStreamLogicStub']),- props({}),- key((p: { streamKey: string }) => p.streamKey),- actions({- pushHumanMessage: (content: string) => ({ content }),- setStubStatus: (status: string | null) => ({ status }),- }),- reducers({- currentRunStatus: [- null,- {- setStubStatus: (_: string | null, { status }: { status: string | null }) => status,- },- ],- }),- ])- return {- sandboxStreamLogic: stub,- isTerminalRunStatus: (status: string | null) =>- status != null && ['completed', 'failed', 'cancelled'].includes(status),- }-})--jest.mock('scenes/projectLogic', () => {- const { kea, actions, path, reducers } = jest.requireActual('kea')- const stub = kea([- path(['test', 'projectLogicStub']),- actions({ setCurrentProjectId: (id: number | null) => ({ id }) }),- reducers({- currentProjectId: [- 997,- {- setCurrentProjectId: (_: number | null, { id }: { id: number | null }) => id,- },- ],- }),- ])- return { projectLogic: stub }-})--jest.mock('../generated/api', () => ({- tasksRunsCommandCreate: jest.fn(),-}))--jest.mock('lib/lemon-ui/LemonToast', () => ({- lemonToast: { error: jest.fn() },-}))--describe('taskRunChatLogic', () => {- let logic: ReturnType<typeof taskRunChatLogic.build>- let stream: ReturnType<typeof sandboxStreamLogic.build>- let project: ReturnType<typeof projectLogic.build>-- const TASK_ID = 'task-1'- const RUN_ID = 'run-1'-- beforeEach(() => {- jest.clearAllMocks()- initKeaTests()- project = projectLogic()- project.mount()- stream = sandboxStreamLogic({ streamKey: RUN_ID })- stream.mount()- logic = taskRunChatLogic({ taskId: TASK_ID, runId: RUN_ID })- logic.mount()- })-- afterEach(() => {- logic?.unmount()- stream?.unmount()- project?.unmount()- })-- it('clears the draft and echoes the human message on a successful send', async () => {- ;(tasksRunsCommandCreate as jest.Mock).mockResolvedValue({})- logic.actions.setComposerDraft('ship it')-- await expectLogic(logic, () => {- logic.actions.sendMessage('ship it')- }).toFinishAllListeners()-- expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, {- jsonrpc: '2.0',- method: 'user_message',- params: { content: 'ship it' },- })- await expectLogic(stream).toDispatchActions(['pushHumanMessage'])- expect(logic.values.composerDraft).toBe('')- expect(logic.values.sendingMessage).toBe(false)- })-- it('preserves text typed while the send is in flight', async () => {- let resolveSend: (value: unknown) => void = () => {}- ;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(- new Promise((resolve) => {- resolveSend = resolve- })- )- logic.actions.setComposerDraft('hello')-- await expectLogic(logic, () => {- logic.actions.sendMessage('hello')- }).toDispatchActions(['clearComposerDraft'])-- // User keeps typing before the request resolves; the new text must not be clobbered on success.- logic.actions.setComposerDraft('world')- resolveSend({})- await expectLogic(logic).toFinishAllListeners()-- expect(logic.values.composerDraft).toBe('world')- })-- it('keeps the draft and toasts when the send fails', async () => {- ;(tasksRunsCommandCreate as jest.Mock).mockRejectedValue(new Error('boom'))- logic.actions.setComposerDraft('ship it')-- await expectLogic(logic, () => {- logic.actions.sendMessage('ship it')- }).toFinishAllListeners()-- expect(lemonToast.error).toHaveBeenCalled()- expect(logic.values.composerDraft).toBe('ship it')- expect(logic.values.sendingMessage).toBe(false)- })-- it('no-ops without a current project and preserves the draft', async () => {- ;(project.actions as any).setCurrentProjectId(null)- logic.actions.setComposerDraft('ship it')-- await expectLogic(logic, () => {- logic.actions.sendMessage('ship it')- }).toFinishAllListeners()-- expect(tasksRunsCommandCreate).not.toHaveBeenCalled()- expect(logic.values.composerDraft).toBe('ship it')- })-- it('no-ops for a terminal run', async () => {- ;(stream.actions as any).setStubStatus('completed')- logic.actions.setComposerDraft('ship it')-- await expectLogic(logic, () => {- logic.actions.sendMessage('ship it')- }).toFinishAllListeners()-- expect(tasksRunsCommandCreate).not.toHaveBeenCalled()- expect(logic.values.composerDraft).toBe('ship it')- })-- it('no-ops for an empty message', async () => {- await expectLogic(logic, () => {- logic.actions.sendMessage(' ')- }).toFinishAllListeners()-- expect(tasksRunsCommandCreate).not.toHaveBeenCalled()- })-})diff --git a/products/tasks/frontend/logics/taskRunChatLogic.ts b/products/tasks/frontend/logics/taskRunChatLogic.tsdeleted file mode 100644index 5996e5854ba4..000000000000--- a/products/tasks/frontend/logics/taskRunChatLogic.ts+++ /dev/null@@ -1,85 +0,0 @@-import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'--import { lemonToast } from 'lib/lemon-ui/LemonToast'-import { projectLogic } from 'scenes/projectLogic'--import { isTerminalRunStatus, sandboxStreamLogic } from 'products/posthog_ai/frontend/sandbox'-import { tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'--import type { taskRunChatLogicType } from './taskRunChatLogicType'--export interface TaskRunChatLogicProps {- taskId: string- runId: string-}--export const taskRunChatLogic = kea<taskRunChatLogicType>([- path(['products', 'tasks', 'logics', 'taskRunChatLogic']),- props({} as TaskRunChatLogicProps),- key((props) => props.runId),-- connect((props: TaskRunChatLogicProps) => ({- values: [- projectLogic,- ['currentProjectId'],- sandboxStreamLogic({ streamKey: props.runId }),- ['currentRunStatus'],- ],- actions: [sandboxStreamLogic({ streamKey: props.runId }), ['pushHumanMessage']],- })),-- actions({- sendMessage: (content: string) => ({ content }),- setSendingMessage: (sending: boolean) => ({ sending }),- setComposerDraft: (draft: string) => ({ draft }),- clearComposerDraft: true,- }),-- reducers({- sendingMessage: [- false,- {- setSendingMessage: (_, { sending }) => sending,- },- ],- composerDraft: [- '',- {- setComposerDraft: (_, { draft }) => draft,- clearComposerDraft: () => '',- },- ],- }),-- selectors({- isTerminal: [(s) => [s.currentRunStatus], (status): boolean => isTerminalRunStatus(status)],- }),-- listeners(({ actions, values, props }) => ({- sendMessage: async ({ content }) => {- if (values.sendingMessage || !content.trim() || values.isTerminal) {- return- }- if (values.currentProjectId == null) {- return- }- actions.setSendingMessage(true)- // Clear the draft synchronously before the await so text the user types while the send is in- // flight isn't clobbered when the request resolves. A failed send restores the original text.- actions.clearComposerDraft()- try {- await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {- jsonrpc: '2.0',- method: 'user_message',- params: { content },- })- actions.pushHumanMessage(content)- } catch {- actions.setComposerDraft(content)- lemonToast.error('Failed to send message. Please try again.')- } finally {- actions.setSendingMessage(false)- }- },- })),-])