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): unify run surface with PostHog AI-style composer (#65513)

Georgiy Tarasov4510979af1c1
diff --git a/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx b/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx
index b9faadb610fc..2ad022ffdeaa 100644
--- a/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx
+++ b/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx
@@ -192,7 +192,7 @@ function TaskLogBody({
return (
<div className="h-[calc(100dvh-22rem)] min-h-[420px] w-full overflow-hidden rounded border border-primary bg-surface-primary">
{/* In-progress runs stream live; terminal runs show the static replay. */}
- <SandboxRunViewer taskId={task.id} runId={runId} replayOnly={replayOnly} />
+ <SandboxRunViewer taskId={task.id} runId={runId} interaction={replayOnly ? 'read-only' : 'live'} />
</div>
)
}
diff --git a/frontend/src/scenes/inbox/components/detail/ArtefactTaskRun.tsx b/frontend/src/scenes/inbox/components/detail/ArtefactTaskRun.tsx
index ebb3bd9a3325..5c57086ee33f 100644
--- a/frontend/src/scenes/inbox/components/detail/ArtefactTaskRun.tsx
+++ b/frontend/src/scenes/inbox/components/detail/ArtefactTaskRun.tsx
@@ -106,7 +106,7 @@ export function ArtefactTaskRun({
{expanded && task && runId ? (
<div className="mt-2 h-[420px] overflow-hidden rounded border border-primary bg-surface-primary">
- <SandboxRunViewer taskId={task.id} runId={runId} replayOnly={replayOnly} />
+ <SandboxRunViewer taskId={task.id} runId={runId} interaction={replayOnly ? 'read-only' : 'live'} />
</div>
) : null}
</div>
diff --git a/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx b/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx
index f70d66ba7a46..f553aa60b706 100644
--- a/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx
+++ b/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx
@@ -88,7 +88,7 @@ function TaskRow({
<SandboxRunViewer
taskId={task.id}
runId={runId}
- replayOnly={replayOnly}
+ interaction={replayOnly ? 'read-only' : 'live'}
className="px-3 py-2"
/>
</div>
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxComposer.test.tsx b/products/posthog_ai/frontend/sandbox/components/SandboxComposer.test.tsx
new file mode 100644
index 000000000000..6a8991b8ecd2
--- /dev/null
+++ b/products/posthog_ai/frontend/sandbox/components/SandboxComposer.test.tsx
@@ -0,0 +1,68 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+import { SandboxComposer } from './SandboxComposer'
+
+describe('SandboxComposer', () => {
+ const onChange = jest.fn()
+ const onSubmit = jest.fn()
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ const renderComposer = (props: Partial<Parameters<typeof SandboxComposer>[0]> = {}): ReturnType<typeof render> =>
+ render(<SandboxComposer value="" onChange={onChange} onSubmit={onSubmit} {...props} />)
+
+ const getSendButton = (container: HTMLElement): HTMLButtonElement =>
+ container.querySelector('[data-attr="sandbox-composer-send"]') as HTMLButtonElement
+
+ const getTextArea = (): HTMLTextAreaElement =>
+ screen.getByRole('textbox', { name: undefined }) as HTMLTextAreaElement
+
+ it('shows the placeholder when empty and hides it once there is a value', () => {
+ const { rerender } = renderComposer({ placeholder: 'Send a follow-up message…' })
+ expect(screen.getByText('Send a follow-up message…')).toBeInTheDocument()
+
+ rerender(
+ <SandboxComposer
+ value="hi"
+ onChange={onChange}
+ onSubmit={onSubmit}
+ placeholder="Send a follow-up message…"
+ />
+ )
+ expect(screen.queryByText('Send a follow-up message…')).not.toBeInTheDocument()
+ })
+
+ it('relays typing through onChange', () => {
+ renderComposer()
+ fireEvent.change(getTextArea(), { target: { value: 'hello' } })
+ expect(onChange).toHaveBeenCalledWith('hello')
+ })
+
+ it('disables send and does not submit when the input is empty', () => {
+ const { container } = renderComposer({ value: ' ' })
+ expect(getSendButton(container)).toHaveAttribute('aria-disabled', 'true')
+ fireEvent.click(getSendButton(container))
+ expect(onSubmit).not.toHaveBeenCalled()
+ })
+
+ it('submits when there is a non-empty value', () => {
+ const { container } = renderComposer({ value: 'ship it' })
+ fireEvent.click(getSendButton(container))
+ expect(onSubmit).toHaveBeenCalledTimes(1)
+ })
+
+ it('blocks submission while loading', () => {
+ const { container } = renderComposer({ value: 'ship it', loading: true })
+ expect(getSendButton(container)).toHaveAttribute('aria-disabled', 'true')
+ fireEvent.click(getSendButton(container))
+ expect(onSubmit).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxComposer.tsx b/products/posthog_ai/frontend/sandbox/components/SandboxComposer.tsx
new file mode 100644
index 000000000000..116decc4563d
--- /dev/null
+++ b/products/posthog_ai/frontend/sandbox/components/SandboxComposer.tsx
@@ -0,0 +1,56 @@
+import { Composer } from './composer/Composer'
+
+export interface SandboxComposerProps {
+ value: string
+ onChange: (value: string) => void
+ onSubmit: () => void
+ placeholder?: string
+ /** Shows the send button as in-flight and blocks submission while true. */
+ loading?: boolean
+ /** Extra reason to block the send button (empty input is handled internally). */
+ disabledReason?: string
+ autoFocus?: boolean
+ className?: string
+}
+
+/**
+ * Prepackaged composer for the sandbox run surface — a thin composition of the logic-free
+ * {@link Composer} primitives that reproduces the PostHog AI input look (bordered rounded container,
+ * large textarea with an overlaid placeholder, an absolutely-positioned primary send button) without
+ * any of PostHog AI's conversation-only features. It holds no draft or send state of its own: callers
+ * own the value and the submit handler. Surfaces that need to slot extra chrome should compose the
+ * `Composer.*` parts directly instead of using this wrapper.
+ */
+export function SandboxComposer({
+ value,
+ onChange,
+ onSubmit,
+ placeholder = 'Send a follow-up message…',
+ loading = false,
+ disabledReason,
+ autoFocus,
+ className,
+}: SandboxComposerProps): JSX.Element {
+ return (
+ <Composer.Root
+ value={value}
+ onChange={onChange}
+ onSubmit={onSubmit}
+ loading={loading}
+ disabledReason={disabledReason}
+ className={className}
+ >
+ <Composer.Frame>
+ <Composer.Field>
+ <Composer.Placeholder>{placeholder}</Composer.Placeholder>
+ <Composer.Textarea
+ data-attr="sandbox-composer-input"
+ submitShortcut="cmd-enter"
+ autoFocus={autoFocus}
+ />
+ </Composer.Field>
+ </Composer.Frame>
+ <Composer.Submit data-attr="sandbox-composer-send" />
+ </Composer.Root>
+ )
+}
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.test.tsx b/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.test.tsx
new file mode 100644
index 000000000000..73412e70fb5e
--- /dev/null
+++ b/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.test.tsx
@@ -0,0 +1,124 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { useActions, useValues } from 'kea'
+
+import type { SandboxRunStatus } from '../sandboxStreamLogic'
+import type { PermissionRequestRecord } from '../types/sandboxStreamTypes'
+import { SandboxRunViewer } from './SandboxRunViewer'
+
+jest.mock('kea', () => ({
+ ...jest.requireActual('kea'),
+ BindLogic: ({ children }: { children: React.ReactNode }) => children,
+ useActions: jest.fn(),
+ useValues: jest.fn(),
+}))
+
+jest.mock('../sandboxStreamLogic', () => ({
+ sandboxStreamLogic: jest.fn(() => ({ __mock: 'sandboxStreamLogic' })),
+ isTerminalRunStatus: (status: string | null) =>
+ status != null && ['completed', 'failed', 'cancelled'].includes(status),
+}))
+
+jest.mock('./SandboxThreadView', () => ({ SandboxThreadView: () => <div data-attr="thread" /> }))
+jest.mock('./SandboxResourcesBar', () => ({ SandboxResourcesBar: () => <div data-attr="resources" /> }))
+jest.mock('./SandboxContextUsage', () => ({ SandboxContextUsage: () => <div data-attr="context" /> }))
+jest.mock('./SandboxPermissionInput', () => ({ SandboxPermissionInput: () => <div data-attr="permission" /> }))
+jest.mock('./SandboxQuestionInput', () => ({ SandboxQuestionInput: () => <div data-attr="question" /> }))
+
+const composerProps = {
+ composerValue: '',
+ onComposerChange: jest.fn(),
+ onComposerSubmit: jest.fn(),
+ composerLoading: false,
+}
+
+function setValues(
+ overrides: Partial<{
+ currentRunStatus: SandboxRunStatus | null
+ pendingPermissionRequest: PermissionRequestRecord | null
+ bootstrapLoading: boolean
+ threadItems: unknown[]
+ }>
+): void {
+ ;(useValues as jest.Mock).mockReturnValue({
+ bootstrapLoading: false,
+ threadItems: [],
+ pendingPermissionRequest: null,
+ currentRunStatus: 'in_progress',
+ ...overrides,
+ })
+}
+
+describe('SandboxRunViewer', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ ;(useActions as jest.Mock).mockReturnValue({ bootstrapRun: jest.fn(), reset: jest.fn() })
+ setValues({})
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ const renderLive = (statusOrOverrides: SandboxRunStatus | null | Parameters<typeof setValues>[0]): void => {
+ if (typeof statusOrOverrides === 'object' && statusOrOverrides !== null) {
+ setValues(statusOrOverrides)
+ } else {
+ setValues({ currentRunStatus: statusOrOverrides as SandboxRunStatus | null })
+ }
+ render(<SandboxRunViewer taskId="task-1" runId="run-1" interaction="live" {...composerProps} />)
+ }
+
+ it.each<SandboxRunStatus>(['queued', 'in_progress'])('shows the composer for an active run (%s)', (status) => {
+ renderLive(status)
+ expect(screen.getByTestId('composer')).toBeInTheDocument()
+ })
+
+ it('does not show the composer during the null bootstrap window', () => {
+ renderLive(null)
+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()
+ // The thread still renders while bootstrapping.
+ expect(screen.getByTestId('thread')).toBeInTheDocument()
+ })
+
+ it.each<SandboxRunStatus>(['completed', 'failed', 'cancelled'])(
+ 'never shows the composer for a terminal run (%s)',
+ (status) => {
+ renderLive(status)
+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()
+ }
+ )
+
+ it('shows the permission input instead of the composer when a permission request is pending', () => {
+ renderLive({
+ currentRunStatus: 'in_progress',
+ pendingPermissionRequest: { requestId: 'r1' } as PermissionRequestRecord,
+ })
+ expect(screen.getByTestId('permission')).toBeInTheDocument()
+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()
+ })
+
+ it('shows the question input when the pending request carries questions', () => {
+ renderLive({
+ currentRunStatus: 'in_progress',
+ pendingPermissionRequest: { requestId: 'r1', questions: [{ question: 'q' }] } as PermissionRequestRecord,
+ })
+ expect(screen.getByTestId('question')).toBeInTheDocument()
+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()
+ })
+
+ it('does not show a composer in read-only mode even for an active run', () => {
+ setValues({ currentRunStatus: 'in_progress' })
+ render(<SandboxRunViewer taskId="task-1" runId="run-1" interaction="read-only" />)
+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()
+ expect(screen.queryByTestId('resources')).not.toBeInTheDocument()
+ expect(screen.getByTestId('thread')).toBeInTheDocument()
+ })
+
+ it('omits the composer in live mode when no composer props are supplied', () => {
+ setValues({ currentRunStatus: 'in_progress' })
+ render(<SandboxRunViewer taskId="task-1" runId="run-1" interaction="live" />)
+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()
+ })
+})
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsx b/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsx
index 3d624ef8bdf6..5ac942c85c4a 100644
--- a/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsx
+++ b/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsx
@@ -5,7 +5,12 @@ import { Spinner } from '@posthog/lemon-ui'
import { cn } from 'lib/utils/css-classes'
-import { sandboxStreamLogic } from '../sandboxStreamLogic'
+import { isTerminalRunStatus, sandboxStreamLogic } from '../sandboxStreamLogic'
+import { Composer } from './composer/Composer'
+import { SandboxContextUsage } from './SandboxContextUsage'
+import { SandboxPermissionInput } from './SandboxPermissionInput'
+import { SandboxQuestionInput } from './SandboxQuestionInput'
+import { SandboxResourcesBar } from './SandboxResourcesBar'
import { SandboxThreadView } from './SandboxThreadView'
export interface SandboxRunViewerProps {
@@ -16,72 +21,171 @@ export interface SandboxRunViewerProps {
/** Telemetry tag only — omit for conversation-less runs (automation, Slack, signals, PR-triggered). */
conversationId?: string
/**
- * Replay the persisted `logs/` snapshot once and never open SSE (default `true`, the safe choice
- * for a static run viewer). Pass `false` for an in-progress run to stream live frames over SSE,
- * falling back to replay automatically once the run goes terminal. Folded into the logic key, so a
- * live and a replay viewer of the same run can never share state.
+ * `'read-only'` (default) replays the persisted `logs/` snapshot once and never opens SSE — the safe
+ * choice for a static viewer. `'live'` streams an in-progress run over SSE (falling back to replay once
+ * terminal) and adds approvals/questions plus the follow-up composer. The mode is folded into the logic
+ * key, so a live and a read-only viewer of the same run can never share state.
*/
- replayOnly?: boolean
+ interaction?: 'live' | 'read-only'
className?: string
+ /**
+ * Composer wiring — live mode only. Provide all of `composerValue`/`onComposerChange`/`onComposerSubmit`
+ * to render the follow-up composer; the consumer owns the draft and the send (this module never POSTs
+ * task commands itself). Omit to stream live without a composer.
+ */
+ composerValue?: string
+ onComposerChange?: (value: string) => void
+ onComposerSubmit?: () => void
+ composerLoading?: boolean
+ composerPlaceholder?: string
}
/**
- * Embeddable read-only viewer of a task run's agent thread. Binds a `sandboxStreamLogic` instance
- * (keyed apart from any other stream of the same run) and renders the shared `SandboxThreadView`. With
- * the default `replayOnly`, it replays the persisted `logs/` snapshot once — no SSE. With
- * `replayOnly={false}` it streams an in-progress run live (and replays once terminal). No permissions,
- * no composer. Drop in anywhere with just `(taskId, runId)`.
+ * Embeddable viewer of a task run's agent thread. Binds a `sandboxStreamLogic` instance (keyed apart from
+ * any other stream of the same run) and renders the shared `SandboxThreadView`. In `'read-only'` mode it
+ * replays the persisted `logs/` snapshot once — no SSE, no composer. In `'live'` mode it streams an
+ * in-progress run, surfaces permission/question prompts, and (given composer props) renders a follow-up
+ * composer, automatically replaying once the run goes terminal.
*/
export function SandboxRunViewer({
taskId,
runId,
streamKey,
conversationId,
- replayOnly = true,
+ interaction = 'read-only',
className,
+ composerValue,
+ onComposerChange,
+ onComposerSubmit,
+ composerLoading,
+ composerPlaceholder,
}: SandboxRunViewerProps): JSX.Element {
+ const replayOnly = interaction !== 'live'
return (
<BindLogic logic={sandboxStreamLogic} props={{ streamKey: streamKey ?? runId, conversationId, replayOnly }}>
- <SandboxRunViewerContent taskId={taskId} runId={runId} replayOnly={replayOnly} className={className} />
+ <SandboxRunViewerContent
+ taskId={taskId}
+ runId={streamKey ?? runId}
+ rawRunId={runId}
+ interaction={interaction}
+ className={className}
+ composerValue={composerValue}
+ onComposerChange={onComposerChange}
+ onComposerSubmit={onComposerSubmit}
+ composerLoading={composerLoading}
+ composerPlaceholder={composerPlaceholder}
+ />
</BindLogic>
)
}
+interface SandboxRunViewerContentProps {
+ taskId: string
+ /** Logic key (used for child stream keys). */
+ runId: string
+ /** Original run id passed to `bootstrapRun`. */
+ rawRunId: string
+ interaction: 'live' | 'read-only'
+ className?: string
+ composerValue?: string
+ onComposerChange?: (value: string) => void
+ onComposerSubmit?: () => void
+ composerLoading?: boolean
+ composerPlaceholder?: string
+}
+
function SandboxRunViewerContent({
taskId,
runId,
- replayOnly,
+ rawRunId,
+ interaction,
className,
-}: {
- taskId: string
- runId: string
- replayOnly: boolean
- className?: string
-}): JSX.Element {
- const { bootstrapLoading, threadItems } = useValues(sandboxStreamLogic)
+ composerValue,
+ onComposerChange,
+ onComposerSubmit,
+ composerLoading,
+ composerPlaceholder,
+}: SandboxRunViewerContentProps): JSX.Element {
+ const { bootstrapLoading, threadItems, pendingPermissionRequest, currentRunStatus } = useValues(sandboxStreamLogic)
const { bootstrapRun, reset } = useActions(sandboxStreamLogic)
useEffect(() => {
// Reset first so a reused instance (stable streamKey, changed run) replays/streams the new run
// cleanly; the bound logic keys read-only instances apart from any live stream of the same run.
- // `replayOnly` is in the deps so a status transition (live → terminal) re-bootstraps the right
+ // `interaction` is in the deps so a status transition (live → terminal) re-bootstraps the right
// mode — the bound logic re-keys on it, so `bootstrapRun`/`reset` are fresh references anyway.
reset()
- bootstrapRun({ taskId, runId })
- }, [taskId, runId, replayOnly, bootstrapRun, reset])
+ bootstrapRun({ taskId, runId: rawRunId })
+ }, [taskId, rawRunId, interaction, bootstrapRun, reset])
+ const isLive = interaction === 'live'
const showSpinner = bootstrapLoading && threadItems.length === 0
+ // Approvals/questions follow the existing non-terminal precedence: a pending request replaces the
+ // composer. The composer itself is gated on explicit live statuses only — never during the `null`
+ // bootstrap window, never for terminal runs — so a finished run can't flash a follow-up input.
+ const showApproval = isLive && !!pendingPermissionRequest && !isTerminalRunStatus(currentRunStatus)
+ const isQuestion = !!pendingPermissionRequest?.questions && pendingPermissionRequest.questions.length > 0
+ const hasComposer = isLive && !!onComposerSubmit && onComposerChange !== undefined && composerValue !== undefined
+ const showComposer =
+ hasComposer &&
+ !pendingPermissionRequest &&
+ (currentRunStatus === 'queued' || currentRunStatus === 'in_progress')
+
+ const thread = showSpinner ? (
+ <div className="flex justify-center py-8">
+ <Spinner className="text-2xl" />
+ </div>
+ ) : (
+ // An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.
+ <SandboxThreadView />
+ )
+
+ if (!isLive) {
+ return <div className={cn('flex flex-col h-full min-h-0 w-full', className)}>{thread}</div>
+ }
+
return (
- <div className={cn('flex flex-col h-full min-h-0 w-full', className)}>
- {showSpinner ? (
- <div className="flex justify-center py-8">
- <Spinner className="text-2xl" />
+ <div className={cn('@container/thread flex flex-col h-full overflow-hidden', className)}>
+ <div className="flex-1 min-h-0">{thread}</div>
+
+ <SandboxResourcesBar />
+
+ {showApproval && (
+ <div className="border-t px-4 py-3">
+ {isQuestion ? (
+ <SandboxQuestionInput streamKey={runId} request={pendingPermissionRequest!} />
+ ) : (
+ <SandboxPermissionInput streamKey={runId} request={pendingPermissionRequest!} />
+ )}
</div>
- ) : (
- // An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.
- <SandboxThreadView />
)}
+
+ {showComposer && (
+ // Composed from the logic-free Composer.* primitives directly (rather than via
+ // SandboxComposer) so the run surface can slot its own footer/actions later. The
+ // wrapper keeps a stable `data-attr` for the gating tests above.
+ <div data-attr="composer" className="border-t px-4 py-3">
+ <Composer.Root
+ value={composerValue!}
+ onChange={onComposerChange!}
+ onSubmit={onComposerSubmit!}
+ loading={composerLoading}
+ >
+ <Composer.Frame>
+ <Composer.Field>
+ <Composer.Placeholder>
+ {composerPlaceholder ?? 'Send a follow-up message…'}
+ </Composer.Placeholder>
+ <Composer.Textarea data-attr="sandbox-composer-input" submitShortcut="cmd-enter" />
+ </Composer.Field>
+ </Composer.Frame>
+ <Composer.Submit data-attr="sandbox-composer-send" />
+ </Composer.Root>
+ </div>
+ )}
+
+ <SandboxContextUsage />
</div>
)
}
diff --git a/products/posthog_ai/frontend/sandbox/components/composer/Composer.test.tsx b/products/posthog_ai/frontend/sandbox/components/composer/Composer.test.tsx
new file mode 100644
index 000000000000..6f49d8c78cda
--- /dev/null
+++ b/products/posthog_ai/frontend/sandbox/components/composer/Composer.test.tsx
@@ -0,0 +1,85 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+import { Composer } from './Composer'
+
+describe('Composer', () => {
+ const onChange = jest.fn()
+ const onSubmit = jest.fn()
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ const renderComposer = (props: Partial<Parameters<typeof Composer.Root>[0]> = {}): ReturnType<typeof render> =>
+ render(
+ <Composer.Root value="" onChange={onChange} onSubmit={onSubmit} {...props}>
+ <Composer.Frame>
+ <Composer.Field>
+ <Composer.Placeholder>Send a message…</Composer.Placeholder>
+ <Composer.Textarea data-attr="composer-input" />
+ </Composer.Field>
+ </Composer.Frame>
+ <Composer.Submit data-attr="composer-send" />
+ </Composer.Root>
+ )
+
+ const getSend = (container: HTMLElement): HTMLButtonElement =>
+ container.querySelector('[data-attr="composer-send"]') as HTMLButtonElement
+
+ it('shows the placeholder only while empty', () => {
+ const { rerender } = renderComposer()
+ expect(screen.getByText('Send a message…')).toBeInTheDocument()
+
+ rerender(
+ <Composer.Root value="hi" onChange={onChange} onSubmit={onSubmit}>
+ <Composer.Frame>
+ <Composer.Field>
+ <Composer.Placeholder>Send a message…</Composer.Placeholder>
+ <Composer.Textarea data-attr="composer-input" />
+ </Composer.Field>
+ </Composer.Frame>
+ <Composer.Submit data-attr="composer-send" />
+ </Composer.Root>
+ )
+ expect(screen.queryByText('Send a message…')).not.toBeInTheDocument()
+ })
+
+ it('relays typing through onChange', () => {
+ renderComposer()
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'hello' } })
+ expect(onChange).toHaveBeenCalledWith('hello')
+ })
+
+ it('blocks submission and keeps the send button disabled while empty', () => {
+ const { container } = renderComposer({ value: ' ' })
+ expect(getSend(container)).toHaveAttribute('aria-disabled', 'true')
+ fireEvent.click(getSend(container))
+ expect(onSubmit).not.toHaveBeenCalled()
+ })
+
+ it('blocks submission while loading', () => {
+ const { container } = renderComposer({ value: 'ship it', loading: true })
+ expect(getSend(container)).toHaveAttribute('aria-disabled', 'true')
+ fireEvent.click(getSend(container))
+ expect(onSubmit).not.toHaveBeenCalled()
+ })
+
+ it('submits once when there is a non-empty value', () => {
+ const { container } = renderComposer({ value: 'ship it' })
+ fireEvent.click(getSend(container))
+ expect(onSubmit).toHaveBeenCalledTimes(1)
+ })
+
+ it('throws when a part is rendered outside Composer.Root', () => {
+ // Silence the expected React error boundary log.
+ const spy = jest.spyOn(console, 'error').mockImplementation(() => {})
+ expect(() => render(<Composer.Submit />)).toThrow(/inside <Composer.Root>/)
+ spy.mockRestore()
+ })
+})
diff --git a/products/posthog_ai/frontend/sandbox/components/composer/Composer.tsx b/products/posthog_ai/frontend/sandbox/components/composer/Composer.tsx
new file mode 100644
index 000000000000..36727c9a0d0a
--- /dev/null
+++ b/products/posthog_ai/frontend/sandbox/components/composer/Composer.tsx
@@ -0,0 +1,334 @@
+import {
+ createContext,
+ forwardRef,
+ type HTMLAttributes,
+ type ReactNode,
+ type RefObject,
+ useContext,
+ useId,
+ useMemo,
+ useRef,
+} from 'react'
+
+import { IconArrowRight } from '@posthog/icons'
+import { LemonButton, LemonTextArea } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+// Radix-style compound composer: a set of logic-free, presentational surfaces that reproduce the
+// PostHog AI input look (see scenes/max/components/QuestionInput.tsx) without any of its conversation
+// logic. `Composer.Root` owns nothing but the controlled value/submit plumbing it's handed; every
+// other part is a styled slot that reads that plumbing from context. Consumers compose the parts and
+// own all state.
+
+interface ComposerContextValue {
+ value: string
+ onChange: (value: string) => void
+ loading: boolean
+ disabled: boolean
+ /** Empty input / loading / caller's `disabledReason`, collapsed to a single reason (undefined when sendable). */
+ sendDisabledReason: string | undefined
+ /** Focuses the textarea when blocked, otherwise calls the caller's `onSubmit`. */
+ submit: () => void
+ textAreaRef: RefObject<HTMLTextAreaElement>
+ /** Shared id linking `Frame` (htmlFor), `Textarea` (id) and `Placeholder` (describedby). */
+ id: string
+ isThreadVisible: boolean
+}
+
+const ComposerContext = createContext<ComposerContextValue | null>(null)
+
+export function useComposerContext(): ComposerContextValue {
+ const ctx = useContext(ComposerContext)
+ if (!ctx) {
+ throw new Error('Composer.* components must be rendered inside <Composer.Root>')
+ }
+ return ctx
+}
+
+export interface ComposerRootProps {
+ value: string
+ onChange: (value: string) => void
+ onSubmit: () => void
+ /** Marks the send button in-flight and blocks submission. */
+ loading?: boolean
+ /** Disables the textarea. */
+ disabled?: boolean
+ /** Extra reason to block sending, beyond the internally-handled empty input. */
+ disabledReason?: string
+ /** Renders the sticky page-level chrome (bordered, blurred, bottom-pinned) around the input. */
+ isSticky?: boolean
+ /** Follow-up variant: tighter frame border/radius and send-button offset. */
+ isThreadVisible?: boolean
+ className?: string
+ /** Applied to the outermost wrapper when sticky chrome is rendered. */
+ containerClassName?: string
+ /** Supply to read the textarea node from outside; otherwise an internal ref is used. */
+ textAreaRef?: RefObject<HTMLTextAreaElement>
+ /** Override the auto-generated id linking the label, textarea and placeholder. */
+ id?: string
+ children: ReactNode
+}
+
+const ComposerRoot = forwardRef<HTMLDivElement, ComposerRootProps>(function ComposerRoot(
+ {
+ value,
+ onChange,
+ onSubmit,
+ loading = false,
+ disabled = false,
+ disabledReason,
+ isSticky = false,
+ isThreadVisible = false,
+ className,
+ containerClassName,
+ textAreaRef: textAreaRefProp,
+ id: idProp,
+ children,
+ },
+ ref
+): JSX.Element {
+ const internalRef = useRef<HTMLTextAreaElement>(null)
+ const textAreaRef = textAreaRefProp ?? internalRef
+ const generatedId = useId()
+ const id = idProp ?? generatedId
+
+ const sendDisabledReason = !value.trim() ? 'Type a message first' : loading ? 'Sending…' : disabledReason
+
+ const ctx = useMemo<ComposerContextValue>(
+ () => ({
+ value,
+ onChange,
+ loading,
+ disabled,
+ sendDisabledReason,
+ submit: () => {
+ if (sendDisabledReason) {
+ textAreaRef.current?.focus()
+ return
+ }
+ onSubmit()
+ },
+ textAreaRef,
+ id,
+ isThreadVisible,
+ }),
+ [value, onChange, loading, disabled, sendDisabledReason, onSubmit, textAreaRef, id, isThreadVisible]
+ )
+
+ // The relative wrapper is the positioning context for the absolutely-placed Submit + Placeholder.
+ const hasChrome = isSticky || isThreadVisible || !!containerClassName
+ const positioned = (
+ <div
+ data-slot="composer-root"
+ className={cn('relative w-full flex flex-col', hasChrome ? 'z-1' : className)}
+ ref={hasChrome ? undefined : ref}
+ >
+ {children}
+ </div>
+ )
+
+ return (
+ <ComposerContext.Provider value={ctx}>
+ {hasChrome ? (
+ <div
+ className={cn(
+ 'w-full px-3',
+ (isSticky || isThreadVisible) && 'sticky bottom-0 z-10 max-w-180 self-center',
+ containerClassName
+ )}
+ ref={ref}
+ >
+ <div
+ className={cn(
+ 'flex flex-col items-center',
+ isSticky && 'border border-primary rounded-lg backdrop-blur-sm bg-glass-bg-3000',
+ className
+ )}
+ >
+ {positioned}
+ </div>
+ </div>
+ ) : (
+ positioned
+ )}
+ </ComposerContext.Provider>
+ )
+})
+
+/** Free slot above the frame (banners, queue, notices). Logic-free. */
+const ComposerBanner = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(function ComposerBanner(
+ { className, children, ...rest },
+ ref
+): JSX.Element {
+ return (
+ <div data-slot="composer-banner" ref={ref} className={className} {...rest}>
+ {children}
+ </div>
+ )
+})
+
+export interface ComposerFrameProps extends HTMLAttributes<HTMLLabelElement> {
+ /** Toggles the AI focus-ring color (off while the agent is streaming, per QuestionInput). */
+ ringActive?: boolean
+}
+
+/** The bordered, rounded `input-like` container with the AI focus ring; a `<label>` so clicks focus the textarea. */
+const ComposerFrame = forwardRef<HTMLLabelElement, ComposerFrameProps>(function ComposerFrame(
+ { className, children, ringActive = true, ...rest },
+ ref
+): JSX.Element {
+ const { id, isThreadVisible } = useComposerContext()
+ return (
+ <label
+ data-slot="composer-frame"
+ htmlFor={id}
+ ref={ref}
+ className={cn(
+ 'input-like flex flex-col cursor-text',
+ 'border border-primary',
+ 'bg-[var(--color-bg-fill-input)]',
+ isThreadVisible ? 'border-primary m-0.5 rounded-[7px]' : 'rounded-lg',
+ '[--input-ring-size:2px]',
+ ringActive && '[--input-ring-color:var(--color-ai)]',
+ className
+ )}
+ {...rest}
+ >
+ {children}
+ </label>
+ )
+})
+
+/** Positioning context grouping the overlaid Placeholder and the Textarea. */
+const ComposerField = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(function ComposerField(
+ { className, children, ...rest },
+ ref
+): JSX.Element {
+ return (
+ <div data-slot="composer-field" ref={ref} className={cn('relative w-full', className)} {...rest}>
+ {children}
+ </div>
+ )
+})
+
+/** Overlaid hint shown only while the input is empty. */
+const ComposerPlaceholder = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(function ComposerPlaceholder(
+ { className, children, ...rest },
+ ref
+): JSX.Element | null {
+ const { value, id } = useComposerContext()
+ if (value) {
+ return null
+ }
+ return (
+ <div
+ data-slot="composer-placeholder"
+ id={`${id}-hint`}
+ ref={ref}
+ className={cn('text-secondary absolute top-4 left-4 text-sm pointer-events-none', className)}
+ {...rest}
+ >
+ {children}
+ </div>
+ )
+})
+
+export interface ComposerTextareaProps {
+ className?: string
+ autoFocus?: boolean
+ minRows?: number
+ maxRows?: number
+ /** `'enter'` submits on Enter (PostHog AI), `'cmd-enter'` on Cmd/Ctrl+Enter (tasks composer). */
+ submitShortcut?: 'enter' | 'cmd-enter'
+ 'data-attr'?: string
+}
+
+/** The textarea itself, wired to the context value/submit. */
+function ComposerTextarea({
+ className,
+ autoFocus,
+ minRows = 1,
+ maxRows = 10,
+ submitShortcut = 'enter',
+ ...rest
+}: ComposerTextareaProps): JSX.Element {
+ const { value, onChange, submit, textAreaRef, disabled, id } = useComposerContext()
+ // onPressEnter / onPressCmdEnter are mutually exclusive in LemonTextArea's type — pick one.
+ const submitProps =
+ submitShortcut === 'cmd-enter' ? { onPressCmdEnter: () => submit() } : { onPressEnter: () => submit() }
+ return (
+ <LemonTextArea
+ id={id}
+ aria-describedby={!value ? `${id}-hint` : undefined}
+ ref={textAreaRef}
+ value={value}
+ onChange={onChange}
+ disabled={disabled}
+ minRows={minRows}
+ maxRows={maxRows}
+ autoFocus={autoFocus}
+ className={cn('!border-none !bg-transparent min-h-16 py-2 pl-2 pr-12 resize-none', className)}
+ hideFocus
+ {...submitProps}
+ {...rest}
+ />
+ )
+}
+
+/** The in-frame bottom row for context chips / actions. */
+const ComposerFooter = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(function ComposerFooter(
+ { className, children, ...rest },
+ ref
+): JSX.Element {
+ return (
+ <div data-slot="composer-footer" ref={ref} className={cn('pb-2 pr-12', className)} {...rest}>
+ {children}
+ </div>
+ )
+})
+
+export interface ComposerSubmitProps {
+ icon?: JSX.Element | null
+ tooltip?: ReactNode
+ /** Positioned wrapper className. */
+ className?: string
+ 'data-attr'?: string
+}
+
+/** The absolutely-positioned send cluster, sibling of Frame inside Root's relative wrapper. */
+function ComposerSubmit({ icon, tooltip, className, ...rest }: ComposerSubmitProps): JSX.Element {
+ const { sendDisabledReason, loading, submit, isThreadVisible } = useComposerContext()
+ return (
+ <div
+ data-slot="composer-submit"
+ className={cn(
+ 'absolute flex items-center',
+ isThreadVisible ? 'bottom-[9px] right-[9px]' : 'bottom-[7px] right-[7px]',
+ className
+ )}
+ >
+ <LemonButton
+ type="primary"
+ size="small"
+ icon={icon ?? <IconArrowRight />}
+ onClick={() => submit()}
+ loading={loading}
+ disabledReason={sendDisabledReason}
+ tooltip={sendDisabledReason ? undefined : (tooltip ?? "Let's go!")}
+ {...rest}
+ />
+ </div>
+ )
+}
+
+export const Composer = Object.assign(ComposerRoot, {
+ Root: ComposerRoot,
+ Banner: ComposerBanner,
+ Frame: ComposerFrame,
+ Field: ComposerField,
+ Placeholder: ComposerPlaceholder,
+ Textarea: ComposerTextarea,
+ Footer: ComposerFooter,
+ Submit: ComposerSubmit,
+})
diff --git a/products/posthog_ai/frontend/sandbox/index.ts b/products/posthog_ai/frontend/sandbox/index.ts
index 0f717523e3ae..7cf36ae766ff 100644
--- a/products/posthog_ai/frontend/sandbox/index.ts
+++ b/products/posthog_ai/frontend/sandbox/index.ts
@@ -1,10 +1,21 @@
-// Public surface of the sandbox renderer — the conversation-agnostic PostHog AI agent-run UI.
-// PostHog AI (scenes/max), tasks, and the signals inbox consume this barrel, never deep paths.
-// This module talks to tasks only via `api.tasks.*` / `products/tasks/frontend/generated/api`
-// and must never import the conversations API or Max conversation orchestration.
+// Public run surface of the sandbox renderer — the conversation-agnostic PostHog AI agent-run UI.
+// Tasks and the signals inbox consume this barrel (`SandboxRunViewer`, `SandboxComposer`, the logic,
+// and the types), never deep paths. PostHog AI (scenes/max) additionally composes lower-level
+// primitives from the subtree directly, by design. This module talks to tasks only via `api.tasks.*`
+// / `products/tasks/frontend/generated/api` and must never import the conversations API or Max
+// conversation orchestration.
export { SandboxRunViewer } from './components/SandboxRunViewer'
export type { SandboxRunViewerProps } from './components/SandboxRunViewer'
+export { SandboxComposer } from './components/SandboxComposer'
+export type { SandboxComposerProps } from './components/SandboxComposer'
+export { Composer } from './components/composer/Composer'
+export type {
+ ComposerRootProps,
+ ComposerFrameProps,
+ ComposerTextareaProps,
+ ComposerSubmitProps,
+} from './components/composer/Composer'
export { SandboxThreadView } from './components/SandboxThreadView'
export { sandboxStreamLogic, isTerminalRunStatus, SANDBOX_INITIAL_PERMISSION_MODE } from './sandboxStreamLogic'
diff --git a/products/tasks/frontend/components/TaskRunChat.tsx b/products/tasks/frontend/components/TaskRunChat.tsx
index f80db8c37505..c2e314ccef6e 100644
--- a/products/tasks/frontend/components/TaskRunChat.tsx
+++ b/products/tasks/frontend/components/TaskRunChat.tsx
@@ -1,19 +1,6 @@
import { BindLogic, useActions, useValues } from 'kea'
-import { useState } from 'react'
-import { LemonBanner, LemonButton, LemonSkeleton, LemonTextArea } from '@posthog/lemon-ui'
-
-import { NotFound } from 'lib/components/NotFound'
-
-import {
- isTerminalRunStatus,
- SandboxContextUsage,
- SandboxPermissionInput,
- SandboxQuestionInput,
- SandboxResourcesBar,
- SandboxThreadView,
- sandboxStreamLogic,
-} from 'products/posthog_ai/frontend/sandbox'
+import { SandboxRunViewer } from 'products/posthog_ai/frontend/sandbox'
import { taskRunChatLogic } from '../logics/taskRunChatLogic'
@@ -22,134 +9,33 @@ export interface TaskRunChatProps {
runId: string
}
+/**
+ * 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.
+ */
export function TaskRunChat({ taskId, runId }: TaskRunChatProps): JSX.Element {
- // The outer BindLogic binds the shared sandboxStreamLogic instance (keyed by runId) consumed by
- // both the renderer (thread/permission/question views) and taskRunChatLogic. We bind in live mode;
- // bootstrapRun (called from taskRunChatLogic.afterMount) reads the run status from the tasks API and
- // never opens SSE for an already-terminal run — same pattern SandboxRunViewer uses.
return (
- <BindLogic logic={sandboxStreamLogic} props={{ streamKey: runId }}>
- <BindLogic logic={taskRunChatLogic} props={{ taskId, runId }}>
- <TaskRunChatContent taskId={taskId} runId={runId} />
- </BindLogic>
+ <BindLogic logic={taskRunChatLogic} props={{ taskId, runId }}>
+ <TaskRunChatContent taskId={taskId} runId={runId} />
</BindLogic>
)
}
function TaskRunChatContent({ taskId, runId }: TaskRunChatProps): JSX.Element {
- const streamLogic = sandboxStreamLogic({ streamKey: runId })
- const { pendingPermissionRequest, currentRunStatus, threadItems, logBootstrapLoading, bootstrapError } =
- useValues(streamLogic)
- const { reset, bootstrapRun } = useActions(streamLogic)
- const { sendMessage } = useActions(taskRunChatLogic({ taskId, runId }))
- const { sendingMessage } = useValues(taskRunChatLogic({ taskId, runId }))
-
- const isTerminal = isTerminalRunStatus(currentRunStatus)
- const [composerText, setComposerText] = useState('')
-
- const isQuestion = !!pendingPermissionRequest?.questions && pendingPermissionRequest.questions.length > 0
- const isLogPending = logBootstrapLoading
- const showBootstrapError =
- !!bootstrapError && threadItems.length === 1 && threadItems[0]?.type === 'error' && !isLogPending
- const isBlockingBootstrapState = isLogPending || showBootstrapError
-
- const handleSend = (): void => {
- const trimmed = composerText.trim()
- if (!trimmed || sendingMessage || isTerminal || isBlockingBootstrapState) {
- return
- }
- sendMessage(trimmed)
- setComposerText('')
- }
-
- const handleRetryBootstrap = (): void => {
- reset()
- bootstrapRun({ taskId, runId })
- }
-
- return (
- <div className="flex flex-col h-full overflow-hidden">
- <div className="flex-1 min-h-0">
- {isLogPending ? (
- <TaskRunLogSkeleton />
- ) : showBootstrapError && bootstrapError?.status === 404 ? (
- <NotFound object="task run" className="m-0 py-8" />
- ) : showBootstrapError && bootstrapError ? (
- <LemonBanner
- type="error"
- data-attr="task-run-log-error"
- action={{
- children: 'Retry',
- onClick: handleRetryBootstrap,
- }}
- >
- <p>We couldn't load this task run.</p>
- <p className="text-muted mb-0">{bootstrapError.errorMessage || bootstrapError.errorTitle}</p>
- </LemonBanner>
- ) : (
- <SandboxThreadView />
- )}
- </div>
-
- {!isBlockingBootstrapState && (
- <div className="w-full max-w-180 mx-auto">
- <SandboxResourcesBar />
- </div>
- )}
-
- {pendingPermissionRequest && !isTerminal && !isBlockingBootstrapState && (
- <div className="border-t px-4 py-3">
- <div className="w-full max-w-180 mx-auto">
- {isQuestion ? (
- <SandboxQuestionInput streamKey={runId} request={pendingPermissionRequest} />
- ) : (
- <SandboxPermissionInput streamKey={runId} request={pendingPermissionRequest} />
- )}
- </div>
- </div>
- )}
-
- {!isTerminal && !pendingPermissionRequest && !isBlockingBootstrapState && (
- <div className="border-t px-4 py-3">
- <div className="w-full max-w-180 mx-auto flex gap-2 items-end">
- <LemonTextArea
- className="flex-1"
- value={composerText}
- onChange={setComposerText}
- placeholder="Send a follow-up message…"
- minRows={1}
- maxRows={8}
- onPressCmdEnter={handleSend}
- />
- <LemonButton
- type="primary"
- onClick={handleSend}
- loading={sendingMessage}
- disabledReason={!composerText.trim() ? 'Type a message first' : undefined}
- >
- Send
- </LemonButton>
- </div>
- </div>
- )}
-
- {!isBlockingBootstrapState && (
- <div className="w-full max-w-180 mx-auto">
- <SandboxContextUsage />
- </div>
- )}
- </div>
- )
-}
+ const { composerDraft, sendingMessage } = useValues(taskRunChatLogic({ taskId, runId }))
+ const { setComposerDraft, sendMessage } = useActions(taskRunChatLogic({ taskId, runId }))
-function TaskRunLogSkeleton(): JSX.Element {
return (
- <div className="flex flex-col gap-3 p-4" data-attr="task-run-log-skeleton">
- <LemonSkeleton className="h-4 w-1/3" />
- <LemonSkeleton className="h-16 w-11/12" />
- <LemonSkeleton className="h-4 w-1/4 ml-auto" />
- <LemonSkeleton className="h-24 w-4/5 ml-auto opacity-60" />
- <LemonSkeleton className="h-20 w-10/12 opacity-40" />
- </div>
+ <SandboxRunViewer
+ taskId={taskId}
+ runId={runId}
+ interaction="live"
+ composerValue={composerDraft}
+ onComposerChange={setComposerDraft}
+ onComposerSubmit={() => sendMessage(composerDraft)}
+ composerLoading={sendingMessage}
+ />
)
}
diff --git a/products/tasks/frontend/logics/taskRunChatLogic.test.ts b/products/tasks/frontend/logics/taskRunChatLogic.test.ts
new file mode 100644
index 000000000000..b477c9870d18
--- /dev/null
+++ b/products/tasks/frontend/logics/taskRunChatLogic.test.ts
@@ -0,0 +1,174 @@
+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.ts
index 67df4f6c44d8..5996e5854ba4 100644
--- a/products/tasks/frontend/logics/taskRunChatLogic.ts
+++ b/products/tasks/frontend/logics/taskRunChatLogic.ts
@@ -1,4 +1,4 @@
-import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { projectLogic } from 'scenes/projectLogic'
@@ -25,12 +25,14 @@ export const taskRunChatLogic = kea<taskRunChatLogicType>([
sandboxStreamLogic({ streamKey: props.runId }),
['currentRunStatus'],
],
- actions: [sandboxStreamLogic({ streamKey: props.runId }), ['bootstrapRun', 'pushHumanMessage', 'reset']],
+ actions: [sandboxStreamLogic({ streamKey: props.runId }), ['pushHumanMessage']],
})),
actions({
sendMessage: (content: string) => ({ content }),
setSendingMessage: (sending: boolean) => ({ sending }),
+ setComposerDraft: (draft: string) => ({ draft }),
+ clearComposerDraft: true,
}),
reducers({
@@ -40,6 +42,13 @@ export const taskRunChatLogic = kea<taskRunChatLogicType>([
setSendingMessage: (_, { sending }) => sending,
},
],
+ composerDraft: [
+ '',
+ {
+ setComposerDraft: (_, { draft }) => draft,
+ clearComposerDraft: () => '',
+ },
+ ],
}),
selectors({
@@ -55,6 +64,9 @@ export const taskRunChatLogic = kea<taskRunChatLogicType>([
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',
@@ -63,18 +75,11 @@ export const taskRunChatLogic = kea<taskRunChatLogicType>([
})
actions.pushHumanMessage(content)
} catch {
+ actions.setComposerDraft(content)
lemonToast.error('Failed to send message. Please try again.')
} finally {
actions.setSendingMessage(false)
}
},
})),
-
- afterMount(({ props, actions }) => {
- // sandboxStreamLogic is already bound (the BindLogic in TaskRunChat mounts it first), so a
- // reset + bootstrapRun here re-bootstraps cleanly when a reused logic instance is remounted.
- // Live vs. replay mode is resolved inside bootstrapRun from the run status the tasks API returns.
- actions.reset()
- actions.bootstrapRun({ taskId: props.taskId, runId: props.runId })
- }),
])