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.

102 KB
Raw Blame
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'

import { ApiError } from 'lib/api-error'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { projectLogic } from 'scenes/projectLogic'

import { aiConsentLogic } from '~/layout/ai/aiConsentLogic'
import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'
import { initKeaTests } from '~/test/init'

import {
    tasksRunCreate,
    tasksRunsCancelCreate,
    tasksRunsClearConversationCreate,
    tasksRunsCommandCreate,
    tasksWarmResumeCreate,
} from 'products/tasks/frontend/generated/api'
import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'

import type { PermissionRequestRecord } from '../types/streamTypes'
import type { StoredLogEntry } from '../types/wireTypes'
import { uploadRunAttachments, uploadStagedTaskAttachments } from '../utils/artifactUpload'
import { contextItemLine } from '../utils/posthogContextBlock'
import { composerAttachmentsLogic } from './composerAttachmentsLogic'
import { runCancellationLogic } from './runCancellationLogic'
import { runInteractionLogic } from './runInteractionLogic'
import { runStreamLogic } from './runStreamLogic'
import { taskCommentContextsLogic } from './taskCommentContextsLogic'
import { TaskDraftPersistence, taskDraftStorageKey } from './taskDraftPersistence'
import { toolStreamEventsLogic } from './toolStreamEventsLogic'

const GENERIC_FAILURE = 'Failed to start a new run. Please try again.'

// 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('./runStreamLogic', () => {
    const { kea, actions, key, path, props, reducers } = jest.requireActual('kea')
    const stub = kea([
        path(['test', 'runStreamLogicStub']),
        props({}),
        key((p: { streamKey: string }) => p.streamKey),
        actions({
            pushHumanMessage: (content: string) => ({ content }),
            startOptimisticResume: (message: string) => ({ message }),
            rollbackOptimisticResume: true,
            attachOptimisticResume: (taskId: string, run: unknown) => ({ taskId, run }),
            pushConversationCleared: true,
            respondToPermission: (payload: unknown) => ({ payload }),
            cancelRun: (run?: unknown) => ({ run }),
            markTurnComplete: (isReplay: boolean = false) => ({ isReplay }),
            markRunStarted: true,
            setCurrentMode: (mode: string) => ({ mode }),
            handleTerminalStatus: (status: { status: string }) => status,
            setStubStatus: (status: string | null) => ({ status }),
            setStubThinking: (thinking: boolean) => ({ thinking }),
            setStubReady: (ready: boolean) => ({ ready }),
            setStubClearSupported: (supported: boolean) => ({ supported }),
            setStubReplySuggestions: (replySuggestions: unknown) => ({ replySuggestions }),
            ingestPermissionRequest: (record: PermissionRequestRecord) => ({ record }),
            markPermissionRequestResolved: (requestId: string) => ({ requestId }),
            deliverPermission: (record: PermissionRequestRecord) => ({ record }),
            permissionResponseFailed: (requestId: string) => ({ requestId }),
            permissionRunChanged: true,
            cancelPermissionDelivery: true,
            clearPermissionRequest: true,
            reset: true,
            appendEntries: true,
            ingestAcpFrame: (entry: unknown, source: string = 'live') => ({ entry, source }),
            closeSse: true,
            bootstrapRun: true,
        }),
        reducers({
            runOpening: [false, {}],
            runStarted: [true, { setStubReady: (_: boolean, { ready }: { ready: boolean }) => ready }],
            currentRunStatus: [
                'in_progress',
                {
                    setStubStatus: (_: string | null, { status }: { status: string | null }) => status,
                    handleTerminalStatus: (_: string | null, { status }: { status: string }) => status,
                },
            ],
            isThinking: [
                false,
                {
                    setStubThinking: (_: boolean, { thinking }: { thinking: boolean }) => thinking,
                },
            ],
            bootstrappedRunId: [null, {}],
            bootstrappedTaskId: [null, {}],
            log: [{ entries: [], toolUpdateIndex: new Map() }, {}],
            pendingPermissionRequest: [
                null,
                {
                    ingestPermissionRequest: (_: unknown, { record }: { record: PermissionRequestRecord }) => record,
                    markPermissionRequestResolved: (
                        state: PermissionRequestRecord | null,
                        { requestId }: { requestId: string }
                    ) => (state?.requestId === requestId ? null : state),
                    clearPermissionRequest: () => null,
                    permissionRunChanged: () => null,
                    reset: () => null,
                },
            ],
            permissionResponseRequestIds: [
                new Set<string>(),
                {
                    deliverPermission: (_: unknown, { record }: { record: PermissionRequestRecord }) =>
                        new Set([record.requestId]),
                    markPermissionRequestResolved: () => new Set<string>(),
                    permissionResponseFailed: () => new Set<string>(),
                    cancelPermissionDelivery: () => new Set<string>(),
                    reset: () => new Set<string>(),
                },
            ],
            conversationClearSupported: [
                true,
                {
                    setStubClearSupported: (_: boolean, { supported }: { supported: boolean }) => supported,
                },
            ],
            respondingToPermission: [
                false,
                {
                    deliverPermission: () => true,
                    markPermissionRequestResolved: () => false,
                    permissionResponseFailed: () => false,
                    cancelPermissionDelivery: () => false,
                    reset: () => false,
                },
            ],
            currentMode: [
                null,
                {
                    setCurrentMode: (_: string | null, { mode }: { mode: string }) => mode,
                },
            ],
            replySuggestions: [
                null,
                {
                    setStubReplySuggestions: (_: unknown, { replySuggestions }: { replySuggestions: unknown }) =>
                        replySuggestions,
                },
            ],
        }),
    ])
    return {
        runStreamLogic: 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(),
    tasksRunsClearConversationCreate: jest.fn(),
    tasksWarmResumeCreate: jest.fn(),
    tasksRunsCancelCreate: jest.fn(),
}))

jest.mock('lib/lemon-ui/LemonToast', () => ({
    lemonToast: { error: jest.fn() },
}))

jest.mock('../utils/artifactUpload', () => ({
    uploadRunAttachments: jest.fn(),
    uploadStagedTaskAttachments: jest.fn(),
}))

describe('runInteractionLogic', () => {
    let logic: ReturnType<typeof runInteractionLogic.build>
    let stream: ReturnType<typeof runStreamLogic.build>
    let project: ReturnType<typeof projectLogic.build>
    let toolEvents: ReturnType<typeof toolStreamEventsLogic.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 } },
    ]

    const setConfigCommand = (configId: string, value: string): [string, string, string, Record<string, unknown>] => [
        '997',
        TASK_ID,
        RUN_ID,
        { jsonrpc: '2.0', method: 'set_config_option', params: { configId, value } },
    ]

    beforeEach(() => {
        jest.clearAllMocks()
        localStorage.clear()
        ;(tasksRunsCommandCreate as jest.Mock).mockResolvedValue({ jsonrpc: '2.0', result: { queued: true } })
        ;(tasksRunCreate as jest.Mock).mockResolvedValue({ run: { id: 'run-2' }, latest_run: { id: 'run-2' } })
        ;(tasksRunsClearConversationCreate as jest.Mock).mockResolvedValue({})
        ;(tasksWarmResumeCreate as jest.Mock).mockResolvedValue({ task_id: TASK_ID, run_id: 'warm-run' })
        window.localStorage.clear()
        initKeaTests()
        project = projectLogic()
        project.mount()
        toolEvents = toolStreamEventsLogic()
        toolEvents.mount()
        toolEvents.actions.registerToolListener('editor', {
            tools: ['create_insight'],
            applyBackTargetId: 'insight-1:activation-1',
            onEvent: jest.fn(),
        })
        stream = runStreamLogic({ streamKey: RUN_ID })
        stream.mount()
        logic = runInteractionLogic({ taskId: TASK_ID, runId: RUN_ID, onRunStarted })
        logic.mount()
    })

    afterEach(() => {
        logic?.unmount()
        stream?.unmount()
        project?.unmount()
        toolEvents?.unmount()
    })

    describe('reply suggestions', () => {
        const REPLY = 'Yes, write the snippet'
        const offer = (turnIndex: number): void =>
            (
                stream.actions as unknown as { setStubReplySuggestions: (value: unknown) => void }
            ).setStubReplySuggestions({ turnIndex, replies: [REPLY] })

        it.each([
            ['offers the first reply when the agent waits', () => {}, REPLY],
            ['hides it while the agent is working', () => setThinking(true), null],
            ['hides it for the turn the user dismissed', () => logic.actions.dismissReplySuggestion(2), null],
            ['hides it once the user accepted it', () => logic.actions.acceptReplySuggestion(REPLY, 'Tab'), null],
            ['hides it while a message is sending', () => logic.actions.setSending(true), null],
        ])('%s', (_name, act, expected) => {
            offer(2)
            act()
            expect(logic.values.replySuggestion).toBe(expected)
        })

        it('shows the next turn after a dismissed one', () => {
            offer(2)
            logic.actions.dismissReplySuggestion(2)
            offer(3)
            expect(logic.values.replySuggestion).toBe(REPLY)
        })

        it.each([
            [REPLY, false],
            [`${REPLY} in TypeScript`, true],
        ])('reports whether the accepted reply was sent as %s', async (sent, edited) => {
            const capture = jest.spyOn(posthog, 'capture')
            offer(2)
            logic.actions.acceptReplySuggestion(REPLY, 'Tab')
            await expectLogic(logic, () => stream.actions.pushHumanMessage(sent)).toFinishAllListeners()
            expect(capture).toHaveBeenCalledWith('posthog ai reply suggestion sent', { task_id: TASK_ID, edited })
            expect(logic.values.acceptedReplySuggestion).toBeNull()
        })
    })

    describe('file attachments', () => {
        let attachments: ReturnType<typeof composerAttachmentsLogic.build>

        beforeEach(() => {
            attachments = composerAttachmentsLogic({ attachmentsKey: RUN_ID })
            attachments.mount()
            attachments.actions.addFiles([new File(['a'], 'rows.csv')])
        })

        afterEach(() => {
            attachments.unmount()
        })

        it('uploads the staged files to the run and carries their ids on the follow-up', async () => {
            ;(uploadRunAttachments as jest.Mock).mockResolvedValue(['art-1'])

            logic.actions.setComposerFormValues({ draft: 'What is wrong here?' })
            await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()

            expect(uploadRunAttachments).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, [expect.any(File)])
            expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, {
                jsonrpc: '2.0',
                method: 'user_message',
                params: { content: 'What is wrong here?', artifact_ids: ['art-1'] },
            })
            expect(attachments.values.attachments).toEqual([])
            expect(attachments.values.uploading).toBe(false)
        })

        it('uploads a comment chip screenshot with the message and names it in the chip block', async () => {
            ;(uploadRunAttachments as jest.Mock).mockResolvedValue(['art-1', 'art-2'])
            const comments = taskCommentContextsLogic({ taskId: TASK_ID })
            comments.mount()
            const screenshot = new File(['png'], 'comment-1.png', { type: 'image/png' })
            comments.actions.addCommentToChat(
                { label: 'chart.png (region)', body: '- **Artifact** chart.png' },
                'x',
                screenshot
            )

            logic.actions.setComposerFormValues({ draft: 'Fix this bar' })
            await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()

            expect(uploadRunAttachments).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, [
                expect.objectContaining({ name: 'rows.csv' }),
                screenshot,
            ])
            expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, {
                jsonrpc: '2.0',
                method: 'user_message',
                params: {
                    content:
                        '<comment_context label="chart.png (region)" screenshot="comment-1.png">\n- **Artifact** chart.png\n</comment_context>\nFix this bar',
                    artifact_ids: ['art-1', 'art-2'],
                },
            })
            comments.unmount()
        })

        it('keeps the chip screenshot name when a failed send is retried', async () => {
            ;(uploadRunAttachments as jest.Mock).mockRejectedValueOnce(new Error('S3 said no'))
            ;(uploadRunAttachments as jest.Mock).mockResolvedValueOnce(['art-1', 'art-2'])
            const comments = taskCommentContextsLogic({ taskId: TASK_ID })
            comments.mount()
            const screenshot = new File(['png'], 'comment-1.png', { type: 'image/png' })
            comments.actions.addCommentToChat(
                { label: 'chart.png (region)', body: '- **Artifact** chart.png' },
                'x',
                screenshot
            )

            logic.actions.setComposerFormValues({ draft: 'Fix this bar' })
            await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
            await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()

            expect(tasksRunsCommandCreate).toHaveBeenCalledWith(
                '997',
                TASK_ID,
                RUN_ID,
                expect.objectContaining({
                    params: expect.objectContaining({
                        content:
                            '<comment_context label="chart.png (region)" screenshot="comment-1.png">\n- **Artifact** chart.png\n</comment_context>\nFix this bar',
                    }),
                })
            )
            comments.unmount()
        })

        it('keeps the files staged when the send fails', async () => {
            ;(uploadRunAttachments as jest.Mock).mockRejectedValue(new Error('S3 said no'))

            logic.actions.setComposerFormValues({ draft: 'What is wrong here?' })
            await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()

            expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
            expect(attachments.values.attachments).toHaveLength(1)
            expect(attachments.values.uploading).toBe(false)
            expect(logic.values.composerForm.draft).toBe('What is wrong here?')
        })

        it('sends the files queued with a message, not the ones attached since', async () => {
            ;(uploadRunAttachments as jest.Mock).mockResolvedValue(['art-queued'])
            setThinking(true)
            logic.actions.setComposerFormValues({ draft: 'first message' })
            await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()

            attachments.actions.addFiles([new File(['b'], 'next-draft.csv')])
            setThinking(false)
            await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()

            expect(uploadRunAttachments).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, [
                expect.objectContaining({ name: 'rows.csv' }),
            ])
            expect(attachments.values.stagedAttachments.map((attachment) => attachment.file.name)).toEqual([
                'next-draft.csv',
            ])
        })

        it('hands the files back when the queued message they belong to is removed', async () => {
            setThinking(true)
            logic.actions.setComposerFormValues({ draft: 'first message' })
            await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
            expect(attachments.values.stagedAttachments).toEqual([])

            await expectLogic(logic, () =>
                logic.actions.removeQueuedMessage(logic.values.queuedMessages[0].id)
            ).toFinishAllListeners()

            expect(attachments.values.stagedAttachments.map((attachment) => attachment.file.name)).toEqual(['rows.csv'])
        })

        it('stages the files on the task when a terminal run starts a new one', async () => {
            ;(uploadStagedTaskAttachments as jest.Mock).mockResolvedValue(['art-2'])
            setStatus('completed')

            logic.actions.setComposerFormValues({ draft: 'Try again with this' })
            await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()

            expect(uploadStagedTaskAttachments).toHaveBeenCalledWith('997', TASK_ID, [expect.any(File)])
            expect(tasksRunCreate).toHaveBeenCalledWith(
                '997',
                TASK_ID,
                expect.objectContaining({ pending_user_artifact_ids: ['art-2'] }),
                expect.anything()
            )
            expect(attachments.values.attachments).toEqual([])
        })
    })

    it('sends a follow-up with no artifact ids when nothing is attached', async () => {
        logic.actions.setComposerFormValues({ draft: 'Plain follow-up' })
        await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()

        expect(uploadRunAttachments).not.toHaveBeenCalled()
        expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('Plain follow-up'))
    })

    it('restores queued text and the latest page-exit draft without sending on readiness or turn completion', async () => {
        logic.actions.enableTaskDraftPersistence('user-1', 997)
        setThinking(true)
        logic.actions.setComposerFormValues({ draft: 'queued first' })
        logic.actions.submitComposerForm()
        logic.actions.setComposerFormValues({ draft: 'queued second' })
        logic.actions.submitComposerForm()
        runInteractionLogic({
            ...logic.props,
            flushDraft: () => logic.actions.setComposerFormValues({ draft: 'last keystroke' }),
        })
        window.dispatchEvent(new Event('pagehide'))
        logic.unmount()
        logic = runInteractionLogic({ taskId: TASK_ID, runId: RUN_ID, onRunStarted })
        logic.mount()
        logic.actions.enableTaskDraftPersistence('user-1', 997)
        expect(logic.values.composerForm.draft).toBe('queued first\n\nqueued second\n\nlast keystroke')
        expect(logic.values.queuedMessages).toEqual([])
        expect(logic.values.draftRecovery).toBe('restored')
        setThinking(false)
        await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()
        expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
        expect(tasksRunCreate).not.toHaveBeenCalled()
        expect(tasksWarmResumeCreate).not.toHaveBeenCalled()
        await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
        expect(tasksRunsCommandCreate).toHaveBeenCalledWith(
            ...userMessageCommand('queued first\n\nqueued second\n\nlast keystroke')
        )
        expect(new TaskDraftPersistence(taskDraftStorageKey('user-1', 997, TASK_ID)).restore()).toBeNull()
    })

    it('restores the saved draft and its chips, then adds comment text and sends every chip before it', async () => {
        const comments = taskCommentContextsLogic({ taskId: TASK_ID })
        comments.mount()
        new TaskDraftPersistence(taskDraftStorageKey('user-1', 997, TASK_ID)).save({
            runId: RUN_ID,
            draft: '<comment_context label="chart.png">\n- **Artifact** chart.png\n</comment_context>\nsaved draft',
            queuedText: '',
            recovery: null,
        })
        comments.actions.addCommentToChat({ label: 'report.md', body: '- **Artifact** report.md' }, 'Fix the title')
        logic.actions.applyPendingCommentText()
        expect(logic.values.composerForm.draft).toBe('')

        logic.actions.enableTaskDraftPersistence('user-1', 997)
        expect(logic.values.composerForm.draft).toBe('saved draft\n\nFix the title')

        logic.actions.persistTaskDraft()
        logic.unmount()
        logic = runInteractionLogic({ taskId: TASK_ID, runId: RUN_ID, onRunStarted })
        logic.mount()
        logic.actions.enableTaskDraftPersistence('user-1', 997)
        expect(comments.values.commentContexts.map((context) => context.label)).toEqual(['chart.png', 'report.md'])
        expect(logic.values.composerForm.draft).toBe('saved draft\n\nFix the title')

        await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()

        expect(tasksRunsCommandCreate).toHaveBeenCalledWith(
            ...userMessageCommand(
                '<comment_context label="chart.png">\n- **Artifact** chart.png\n</comment_context>\n<comment_context label="report.md">\n- **Artifact** report.md\n</comment_context>\nsaved draft\n\nFix the title'
            )
        )
        expect(comments.values.commentContexts).toEqual([])
        comments.unmount()
    })

    it('gives the comment chips back and keeps the XML out of the draft when a send fails', async () => {
        ;(tasksRunsCommandCreate as jest.Mock).mockRejectedValue(new Error('network'))
        const comments = taskCommentContextsLogic({ taskId: TASK_ID })
        comments.mount()
        comments.actions.addCommentToChat({ label: 'report.md', body: '- **Artifact** report.md' }, 'unused')

        logic.actions.setComposerFormValues({ draft: 'Fix the title' })
        await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()

        expect(logic.values.composerForm.draft).toBe('Fix the title')
        expect(comments.values.commentContexts).toEqual([
            { id: expect.any(String), label: 'report.md', body: '- **Artifact** report.md' },
        ])
        comments.unmount()
    })

    it('does not prewarm a recovered terminal draft or copy it into another user or project', async () => {
        const key = taskDraftStorageKey('user-1', 997, TASK_ID)
        new TaskDraftPersistence(key).save({ runId: RUN_ID, draft: 'saved draft', queuedText: '', recovery: null })
        setStatus('completed')
        await expectLogic(logic, () => logic.actions.enableTaskDraftPersistence('user-1', 997)).toFinishAllListeners()
        expect(logic.values.composerForm.draft).toBe('saved draft')
        expect(tasksWarmResumeCreate).not.toHaveBeenCalled()
        logic.actions.setComposerFormValues({ draft: 'edited after recovery' })
        logic.actions.enableTaskDraftPersistence('user-1', 997)
        expect(logic.values.composerForm.draft).toBe('edited after recovery')
        logic.actions.enableTaskDraftPersistence('user-2', 997)
        expect(logic.values.composerForm.draft).toBe('')
        logic.actions.enableTaskDraftPersistence('user-1', 998)
        expect(logic.values.composerForm.draft).toBe('')
        expect(new TaskDraftPersistence(key).restore()?.draft).toBe('edited after recovery')
    })

    it('keeps startup input and settings through attachment and sends the queue after the first turn', async () => {
        const pending = runInteractionLogic({ taskId: '', runId: '', streamKey: RUN_ID, interactionKey: 'creation' })
        const unmount = pending.mount()
        const other = runInteractionLogic({
            taskId: '',
            runId: '',
            streamKey: 'other-draft',
            interactionKey: 'other-draft',
        })
        const unmountOther = other.mount()
        const setReady = (ready: boolean): void =>
            (stream.actions as unknown as { setStubReady: (ready: boolean) => void }).setStubReady(ready)
        try {
            pending.actions.enableTaskDraftPersistence('user-1', 997)
            other.actions.setComposerFormValues({ draft: 'another task follow-up' })
            other.actions.submitComposerForm()
            setStatus(null)
            setReady(false)
            pending.actions.setEffort('low')
            pending.actions.setMode('plan')
            pending.actions.setComposerFormValues({ draft: 'first follow-up' })
            pending.actions.submitComposerForm()
            pending.actions.setComposerFormValues({ draft: 'second follow-up' })
            pending.actions.submitComposerForm()
            pending.actions.setComposerFormValues({ draft: 'unfinished draft' })
            pending.actions.handleEscape()
            expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
            expect(tasksWarmResumeCreate).not.toHaveBeenCalled()
            expect(pending.values.queuedMessages).toEqual([
                { id: expect.any(String), content: 'first follow-up' },
                { id: expect.any(String), content: 'second follow-up' },
            ])

            pending.actions.hydrateTaskDraft(TASK_ID)
            expect(new TaskDraftPersistence(taskDraftStorageKey('user-1', 997, TASK_ID)).restore()?.draft).toBe(
                'first follow-up\n\nsecond follow-up\n\nunfinished draft'
            )

            const attached = runInteractionLogic({ ...pending.props, taskId: TASK_ID, runId: RUN_ID })
            expect(attached).toBe(pending)
            expect(new TaskDraftPersistence(taskDraftStorageKey('user-1', 997, TASK_ID)).restore()?.draft).toBe(
                'first follow-up\n\nsecond follow-up\n\nunfinished draft'
            )
            expect(attached.values.draftRecovery).toBeNull()
            setStatus('queued')
            attached.actions.steerQueue()
            expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
            setThinking(true)
            setReady(true)
            stream.actions.setCurrentMode('default')
            expect(attached.values.composerForm.draft).toBe('unfinished draft')
            expect(attached.values.effortOverride).toBe('low')
            expect(attached.values.selectedMode).toBe('plan')
            expect(tasksRunsCommandCreate).not.toHaveBeenCalled()

            setThinking(false)
            await expectLogic(attached, () => stream.actions.markTurnComplete()).toFinishAllListeners()
            expect(attached.values.queuedMessages).toEqual([])
            expect(attached.values.composerForm.draft).toBe('unfinished draft')
            const messages = (tasksRunsCommandCreate as jest.Mock).mock.calls.filter(
                (call) => call[3].method === 'user_message'
            )
            expect(messages).toEqual([userMessageCommand('first follow-up\n\nsecond follow-up')])
            expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, {
                jsonrpc: '2.0',
                method: 'set_config_option',
                params: { configId: 'mode', value: 'plan' },
            })
            expect(attached.values.selectedMode).toBe('plan')
            stream.actions.setCurrentMode('auto')
            expect(attached.values.selectedMode).toBe('auto')
            expect(other.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'another task follow-up' }])
        } finally {
            unmountOther()
            unmount()
        }
    })

    it('holds the queue after Stop until the user explicitly steers it', async () => {
        setThinking(true)
        logic.actions.enqueueMessage('keep this follow-up')
        logic.actions.requestCancellation()
        setThinking(false)
        runCancellationLogic({ streamKey: RUN_ID }).actions.clearCancellation()
        await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()
        expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
        expect(logic.values.queuedMessages[0].content).toBe('keep this follow-up')
        await expectLogic(logic, () => logic.actions.steerQueue()).toFinishAllListeners()
        expect(logic.values.queuedMessages).toEqual([])
    })

    it('drains a follow-up queued after a Stop that had nothing staged', async () => {
        setThinking(true)
        logic.actions.requestCancellation()
        runCancellationLogic({ streamKey: RUN_ID }).actions.clearCancellation()
        setThinking(false)
        await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()

        setThinking(true)
        logic.actions.setComposerFormValues({ draft: 'follow-up after the stop' })
        logic.actions.submitComposerForm()
        expect(logic.values.queuedMessages[0].content).toBe('follow-up after the stop')

        setThinking(false)
        await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()
        expect(logic.values.queuedMessages).toEqual([])
        expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('follow-up after the stop'))
    })

    it('adopts the startup draft once and clears it after sending', async () => {
        const onDraftAdopted = jest.fn()
        const attached = runInteractionLogic({
            taskId: TASK_ID,
            runId: 'attached-run',
            initialDraft: 'startup draft',
            onDraftAdopted,
        })
        const unmount = attached.mount()
        try {
            expect(attached.values.composerForm.draft).toBe('startup draft')
            expect(onDraftAdopted).toHaveBeenCalledTimes(1)
            await expectLogic(attached, () => attached.actions.submitComposerForm()).toFinishAllListeners()
            expect(attached.values.composerForm.draft).toBe('')
        } finally {
            unmount()
        }
    })

    it.each(['queue', 'run', 'idle', 'approval'])(
        'routes Escape for %s and preserves the unsent draft',
        async (state) => {
            setThinking(state !== 'idle')
            logic.actions.setComposerFormValues({ draft: 'unsent draft' })
            if (state === 'queue') {
                logic.actions.enqueueMessage('saved message')
            }
            if (state === 'approval') {
                stream.actions.ingestPermissionRequest({
                    requestId: 'approval',
                    sourceRunId: RUN_ID,
                } as PermissionRequestRecord)
            }
            await expectLogic(logic, () => logic.actions.handleEscape()).toFinishAllListeners()
            expect(logic.values.composerForm.draft).toBe('unsent draft')
            expect(logic.values.cancellationState).toBe(['run', 'approval'].includes(state) ? 'waiting' : null)
            if (state === 'queue') {
                expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, {
                    jsonrpc: '2.0',
                    method: 'user_message',
                    params: { content: 'saved message', steer: true },
                })
            } else {
                expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
            }
        }
    )

    it('blocks sends and steering while stopping without clearing either draft or queue', async () => {
        logic.actions.setComposerFormValues({ draft: 'unsent draft' })
        logic.actions.enqueueMessage('saved message')
        runCancellationLogic({ streamKey: RUN_ID }).actions.requestCancellation()
        await expectLogic(logic, () => {
            logic.actions.handleEscape()
            logic.actions.submitComposerForm()
            logic.actions.steerQueue()
            logic.actions.flushQueue()
        }).toFinishAllListeners()
        expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
        expect(logic.values.composerForm.draft).toBe('unsent draft')
        expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'saved message' }])
    })

    it('sends immediately and echoes the message when the agent is idle', async () => {
        setThinking(false)
        logic.actions.setComposerFormValues({ draft: 'ship it' })

        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('ship it'))
        await expectLogic(stream).toDispatchActions(['pushHumanMessage'])
        expect(logic.values.composerForm.draft).toBe('')
        expect(logic.values.queuedMessages).toEqual([])
        expect(toolEvents.values.applyBackTargetClaims[RUN_ID]).toEqual([
            { targetId: 'insight-1:activation-1', tools: ['create_insight'] },
        ])
    })

    it('does not send any command when the model or effort is picked', async () => {
        setThinking(false)
        logic.actions.setModel('claude-opus-4-8')
        logic.actions.setEffort('low')

        await expectLogic(logic).toFinishAllListeners()

        // Picking is client-side only now — nothing is synced until the message is sent.
        expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
        expect(logic.values.selectedModel).toBe('claude-opus-4-8')
        expect(logic.values.selectedEffort).toBe('low')
    })

    it('syncs a changed model to the agent right before the message, and only when it changed', async () => {
        setThinking(false)
        logic.actions.setModel('claude-opus-4-8')
        logic.actions.setComposerFormValues({ draft: 'ship it' })

        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        // The config sync lands before the message, never inside it.
        expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([
            setConfigCommand('model', 'claude-opus-4-8'),
            userMessageCommand('ship it'),
        ])

        // A follow-up with the same selection re-syncs nothing — just the message.
        ;(tasksRunsCommandCreate as jest.Mock).mockClear()
        logic.actions.setComposerFormValues({ draft: 'again' })

        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([userMessageCommand('again')])
    })

    it('syncs a changed permission mode to the agent right before the message, and only when it changed', async () => {
        setThinking(false)
        // Not `plan` — that's the runtime's default, so it would be no change to sync.
        logic.actions.setMode('bypassPermissions')
        logic.actions.setComposerFormValues({ draft: 'ship it' })

        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        // The mode sync is a `set_config_option { configId: 'mode' }` command that lands before the message.
        expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([
            setConfigCommand('mode', 'bypassPermissions'),
            userMessageCommand('ship it'),
        ])

        // A follow-up with the same mode re-syncs nothing — just the message.
        ;(tasksRunsCommandCreate as jest.Mock).mockClear()
        logic.actions.setComposerFormValues({ draft: 'again' })

        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([userMessageCommand('again')])
    })

    it('adopts the agent-confirmed mode over a stale manual pick and stays in sync at send time', async () => {
        setThinking(false)
        logic.actions.setMode('plan')
        expect(logic.values.selectedMode).toBe('plan')

        // The agent transitions autonomously (e.g. a plan approval leaves Plan mode) and confirms via a
        // `current_mode_update` frame — the live mode replaces the earlier pick.
        stream.actions.setCurrentMode('auto')
        expect(logic.values.selectedMode).toBe('auto')

        logic.actions.setComposerFormValues({ draft: 'go on' })
        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        // Already in sync with the agent — only the message goes out, no stale mode re-sync.
        expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([userMessageCommand('go on')])
    })

    it('seeds the picker from the stored launch mode and coerces the other runtime\u2019s modes', () => {
        // No live `current_mode_update` yet — the run's REST-stored launch mode drives the display.
        logic = runInteractionLogic({ taskId: TASK_ID, runId: RUN_ID, onRunStarted, currentMode: 'plan' })
        expect(logic.values.selectedMode).toBe('plan')

        // A wire mode in the other runtime's vocabulary (a run started from desktop or Slack on Codex)
        // is coerced to this runtime's nearest ceiling rather than shown — or sent — as-is.
        stream.actions.setCurrentMode('full-access')
        expect(logic.values.selectedMode).toBe('bypassPermissions')

        // `acceptEdits` is one of Claude's own modes, so it stays put.
        stream.actions.setCurrentMode('acceptEdits')
        expect(logic.values.selectedMode).toBe('acceptEdits')
    })

    it('seeds a fresh run with the picked permission mode when the run is terminal', async () => {
        setStatus('completed')
        logic.actions.setMode('bypassPermissions')
        logic.actions.setComposerFormValues({ draft: 'continue from here' })

        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        expect(tasksRunCreate).toHaveBeenCalledWith(
            '997',
            TASK_ID,
            expect.objectContaining({ initial_permission_mode: 'bypassPermissions' }),
            expect.objectContaining({ signal: expect.any(AbortSignal) })
        )
    })

    it('stages the message in the queue while the agent is busy', async () => {
        setThinking(true)
        logic.actions.setComposerFormValues({ draft: 'follow up' })

        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
        expect(logic.values.composerForm.draft).toBe('')
        expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'follow up' }])
    })

    it('stages each follow-up on its own row and flushes them as one message when the turn completes', async () => {
        setThinking(true)
        logic.actions.setComposerFormValues({ draft: 'first' })
        logic.actions.submitComposerForm()
        logic.actions.setComposerFormValues({ draft: 'second' })
        logic.actions.submitComposerForm()
        // Each follow-up keeps its own row, so the user can edit or drop one without rewriting the other.
        expect(logic.values.queuedMessages).toEqual([
            { id: expect.any(String), content: 'first' },
            { id: expect.any(String), content: 'second' },
        ])

        // Turn completes → drain. The flush itself sends while idle.
        setThinking(false)
        await expectLogic(logic, () => {
            stream.actions.markTurnComplete()
        }).toFinishAllListeners()

        expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
        expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('first\n\nsecond'))
        expect(logic.values.queuedMessages).toEqual([])
    })

    it('keeps a staged follow-up queued when history replays an older turn completion', async () => {
        setThinking(true)
        logic.actions.setComposerFormValues({ draft: 'follow up' })
        logic.actions.submitComposerForm()
        expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'follow up' }])

        setThinking(false)
        await expectLogic(logic, () => {
            stream.actions.markTurnComplete(true)
        }).toFinishAllListeners()

        expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
        expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'follow up' }])
    })

    it.each(['approval first', 'turn first'])('holds ordinary delivery until both gates clear: %s', async (order) => {
        const record = { requestId: 'approval-1', sourceRunId: RUN_ID } as PermissionRequestRecord
        stream.actions.ingestPermissionRequest(record)
        setThinking(true)
        logic.actions.setComposerFormValues({ draft: 'follow up' })
        logic.actions.submitComposerForm()
        const resolveApproval = (): void => stream.actions.markPermissionRequestResolved(record.requestId)
        const endTurn = (): void => {
            setThinking(false)
            stream.actions.markTurnComplete()
        }
        const [first, last] = order === 'approval first' ? [resolveApproval, endTurn] : [endTurn, resolveApproval]
        first()
        await expectLogic(logic).toFinishAllListeners()
        expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
        last()
        await expectLogic(logic).toFinishAllListeners()
        expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('follow up'))
    })

    it.each(['before approval', 'during confirmation'])(
        'defers Escape steering %s and sends the current saved queue once',
        async (phase) => {
            const record = { requestId: 'approval-1', sourceRunId: RUN_ID } as PermissionRequestRecord
            stream.actions.ingestPermissionRequest(record)
            if (phase === 'during confirmation') {
                stream.actions.deliverPermission(record, 'allow_once')
            }
            setThinking(true)
            logic.actions.enqueueMessage('first')
            logic.actions.setComposerFormValues({ draft: 'still drafting' })
            logic.actions.handleEscape()
            logic.actions.handleEscape()
            logic.actions.enqueueMessage('second')
            expect(logic.values.steerPending).toBe(true)
            expect(tasksRunsCommandCreate).not.toHaveBeenCalled()

            if (phase === 'before approval') {
                stream.actions.deliverPermission(record, 'allow_once')
            }
            expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
            await expectLogic(logic, () =>
                stream.actions.markPermissionRequestResolved(record.requestId)
            ).toFinishAllListeners()
            stream.actions.markPermissionRequestResolved(record.requestId)
            logic.actions.steerQueue()
            expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
            expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, {
                jsonrpc: '2.0',
                method: 'user_message',
                params: { content: 'first\n\nsecond', steer: true },
            })
            expect(logic.values.composerForm.draft).toBe('still drafting')
            expect(logic.values.queuedMessages).toEqual([])
        }
    )

    it.each(['failure', 'replacement approval', 'replacement run', 'terminal', 'cancel', 'reset', 'empty', 'unmount'])(
        'cancels deferred steering on %s',
        async (event) => {
            const record = { requestId: 'approval-1', sourceRunId: RUN_ID } as PermissionRequestRecord
            stream.actions.ingestPermissionRequest(record)
            stream.actions.deliverPermission(record, 'allow_once')
            setThinking(true)
            logic.actions.enqueueMessage('saved')
            logic.actions.steerQueue()
            expect(logic.values.steerPending).toBe(true)

            switch (event) {
                case 'failure':
                    stream.actions.permissionResponseFailed(record.requestId)
                    break
                case 'replacement approval':
                    stream.actions.ingestPermissionRequest({ ...record, requestId: 'approval-2' })
                    break
                case 'replacement run':
                    stream.actions.permissionRunChanged()
                    break
                case 'terminal':
                    setStatus('completed')
                    stream.actions.handleTerminalStatus({ status: 'completed' })
                    break
                case 'cancel':
                    stream.actions.cancelPermissionDelivery()
                    break
                case 'reset':
                    stream.actions.reset()
                    break
                case 'empty':
                    logic.actions.updateQueuedMessage(logic.values.queuedMessages[0].id, '')
                    break
                case 'unmount':
                    logic.unmount()
                    logic.mount()
                    break
            }
            stream.actions.markPermissionRequestResolved(record.requestId)
            await expectLogic(logic).toFinishAllListeners()
            expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
            expect(logic.values.steerPending).toBe(false)
        }
    )

    it.each([
        { jsonrpc: '2.0', error: { code: -32000, message: 'Rejected' } },
        { jsonrpc: '2.0', result: { queued: false } },
        { result: { queued: true } },
        undefined,
    ])('restores unconfirmed steering before newer queued text: %j', async (response) => {
        let complete!: (response: unknown) => void
        ;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(
            new Promise((resolve) => {
                complete = resolve
            })
        )
        setThinking(true)
        logic.actions.enqueueMessage('first')
        logic.actions.setComposerFormValues({ draft: 'unsent draft' })
        logic.actions.steerQueue()
        logic.actions.enqueueMessage('second')
        logic.actions.steerQueue()
        await expectLogic(logic, () => complete(response)).toFinishAllListeners()
        expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
        expect(logic.values.queuedMessages.map((message) => message.content)).toEqual(['first', 'second'])
        expect(logic.values.composerForm.draft).toBe('unsent draft')
        expect(logic.values.steerPending).toBe(false)
        expect(lemonToast.error).toHaveBeenCalled()
        setThinking(false)
        stream.actions.markTurnComplete()
        stream.actions.markPermissionRequestResolved('earlier-approval')
        await expectLogic(logic).toFinishAllListeners()
        expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
    })

    it.each(['reset', 'replacement run', 'cancel', 'terminal', 'unmount'])(
        'ignores a config completion after %s without sending a message',
        async (event) => {
            let complete!: (response: unknown) => void
            ;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(
                new Promise((resolve) => {
                    complete = resolve
                })
            )
            setThinking(true)
            logic.actions.setModel('claude-opus-4-8')
            logic.actions.enqueueMessage('saved')
            logic.actions.steerQueue()
            expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
            switch (event) {
                case 'reset':
                    stream.actions.reset()
                    break
                case 'replacement run':
                    stream.actions.permissionRunChanged()
                    break
                case 'cancel':
                    stream.actions.cancelPermissionDelivery()
                    break
                case 'terminal':
                    setStatus('completed')
                    stream.actions.handleTerminalStatus({ status: 'completed' })
                    break
                case 'unmount':
                    logic.unmount()
                    logic.mount()
                    break
            }
            await expectLogic(logic, () => complete({ jsonrpc: '2.0', result: {} })).toFinishAllListeners()
            expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
        }
    )

    it('does nothing on an empty queue and keeps unsent context after failed steering', async () => {
        setThinking(true)
        const context = attachedContextLogic()
        context.actions.registerContext('test', [
            { type: 'insight', key: 'fake', value: 'example insight', hidden: true },
        ])
        logic.actions.setComposerFormValues({ draft: 'unsent' })
        logic.actions.steerQueue()
        expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
        ;(tasksRunsCommandCreate as jest.Mock).mockRejectedValue(new Error('Connection lost'))
        logic.actions.enqueueMessage('saved')
        await expectLogic(logic, () => logic.actions.steerQueue()).toFinishAllListeners()
        expect(logic.values.pendingContextItems).toHaveLength(1)
        expect(logic.values.composerForm.draft).toBe('unsent')
        expect(logic.values.queuedMessages[0].content).toBe('saved')
        expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
    })

    it.each(['remove', 'edit'])('delivers a fresh queue after discarding a failed submission: %s', async (action) => {
        ;(tasksRunsCommandCreate as jest.Mock).mockRejectedValueOnce(new Error('Connection lost'))
        setThinking(true)
        logic.actions.enqueueMessage('discard this')
        await expectLogic(logic, () => logic.actions.steerQueue()).toFinishAllListeners()
        const { id } = logic.values.queuedMessages[0]
        if (action === 'remove') {
            logic.actions.removeQueuedMessage(id)
        } else {
            logic.actions.updateQueuedMessage(id, '')
        }
        logic.actions.enqueueMessage('new follow-up')
        setThinking(false)
        await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()
        expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(2)
        expect(tasksRunsCommandCreate).toHaveBeenLastCalledWith(...userMessageCommand('new follow-up'))
        expect(logic.values.queuedMessages).toEqual([])
    })

    it('sends a message held by a stop together with the next one the user submits', async () => {
        setThinking(true)
        logic.actions.enqueueMessage('first follow-up')
        logic.actions.requestCancellation()
        expect(logic.values.queueHeld).toBe(true)

        // The stop lands and the turn ends, so the run is idle again when the user types.
        setThinking(false)
        runCancellationLogic({ streamKey: RUN_ID }).actions.clearCancellation()
        logic.actions.setComposerFormValues({ draft: 'are you there?' })
        await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()

        expect(tasksRunsCommandCreate).toHaveBeenLastCalledWith(
            ...userMessageCommand('first follow-up\n\nare you there?')
        )
        expect(logic.values.queuedMessages).toEqual([])
        expect(logic.values.queueHeld).toBe(false)
    })

    it.each([
        ['steer', 'steer'],
        ['stop', 'user_stop'],
        ['failed stop then steer', 'steer'],
        ['failed steer', 'unknown'],
        ['nothing', 'unknown'],
    ])('reports what came before a cancelled turn: %s', async (trigger, cause) => {
        const capture = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
        setThinking(true)
        if (trigger.includes('stop')) {
            logic.actions.requestCancellation()
        }
        if (trigger.startsWith('failed stop')) {
            runCancellationLogic({ streamKey: RUN_ID }).actions.cancellationFailed()
        }
        if (trigger === 'failed steer') {
            ;(tasksRunsCommandCreate as jest.Mock).mockRejectedValueOnce(new Error('Connection lost'))
        }
        if (trigger.includes('steer')) {
            logic.actions.enqueueMessage('change course')
            await expectLogic(logic, () => logic.actions.steerQueue()).toFinishAllListeners()
        }
        const turnComplete = (stopReason: string): StoredLogEntry => ({
            type: 'notification',
            notification: { method: '_posthog/turn_complete', params: { stopReason } },
        })

        stream.actions.ingestAcpFrame(turnComplete('cancelled'))
        stream.actions.ingestAcpFrame(turnComplete('cancelled'))

        const causes = capture.mock.calls
            .filter(([event]) => event === 'task_run_turn_cancelled')
            .map(([, properties]) => properties?.cause)
        expect(causes).toEqual([cause, 'unknown'])
    })

    it('holds an unconfirmed send as its own rows until the user asks for it again', async () => {
        ;(tasksRunsCommandCreate as jest.Mock).mockRejectedValueOnce(new Error('Connection lost'))
        setThinking(true)
        logic.actions.enqueueMessage('first')
        logic.actions.enqueueMessage('second')
        await expectLogic(logic, () => logic.actions.steerQueue()).toFinishAllListeners()

        // The send may have reached the agent, so the rows come back as they were rather than as one blob.
        expect(logic.values.queuedMessages.map((message) => message.content)).toEqual(['first', 'second'])
        expect(logic.values.queueHeld).toBe(true)
        ;(tasksRunsCommandCreate as jest.Mock).mockClear()

        // Typing more must not re-deliver them: only an explicit send may repeat an unconfirmed message.
        setThinking(false)
        logic.actions.setComposerFormValues({ draft: 'third' })
        await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
        await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()
        expect(tasksRunsCommandCreate).not.toHaveBeenCalled()

        await expectLogic(logic, () => logic.actions.steerQueue()).toFinishAllListeners()
        expect(tasksRunsCommandCreate).toHaveBeenCalledTimes(1)
        expect(logic.values.queuedMessages).toEqual([])
    })

    it('carries staged rows into the run a terminal send starts', async () => {
        setThinking(true)
        logic.actions.enqueueMessage('staged while running')
        setStatus('completed')
        stream.actions.handleTerminalStatus({ status: 'completed' })

        logic.actions.setComposerFormValues({ draft: 'and now this' })
        await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()

        expect(tasksRunCreate).toHaveBeenCalledWith(
            '997',
            TASK_ID,
            expect.objectContaining({ pending_user_message: 'staged while running\n\nand now this' }),
            expect.anything()
        )
        expect(logic.values.queuedMessages).toEqual([])
    })

    it('waits for an open row editor before a terminal send carries the rows', async () => {
        setThinking(true)
        logic.actions.enqueueMessage('half-written')
        setStatus('completed')
        stream.actions.handleTerminalStatus({ status: 'completed' })
        logic.actions.setQueueEditing(true)

        logic.actions.setComposerFormValues({ draft: 'and now this' })
        await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()

        // Sending would have carried the row as it stood before the edit the user is still typing.
        expect(tasksRunCreate).not.toHaveBeenCalled()
        expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'half-written' }])

        logic.actions.setQueueEditing(false)
        await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
        expect(tasksRunCreate).toHaveBeenCalledWith(
            '997',
            TASK_ID,
            expect.objectContaining({ pending_user_message: 'half-written\n\nand now this' }),
            expect.anything()
        )
    })

    it('waits for an open row editor before draining on turn completion', async () => {
        setThinking(true)
        logic.actions.enqueueMessage('half-written')
        logic.actions.setQueueEditing(true)

        setThinking(false)
        await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()
        expect(tasksRunsCommandCreate).not.toHaveBeenCalled()

        // Closing the editor drains on its own: no turn completion is coming, so nothing else would.
        await expectLogic(logic, () => logic.actions.setQueueEditing(false)).toFinishAllListeners()
        expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('half-written'))
        expect(logic.values.queuedMessages).toEqual([])
    })

    it('edits and removes staged messages', async () => {
        setThinking(true)
        logic.actions.setComposerFormValues({ draft: 'typo' })
        logic.actions.submitComposerForm()
        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.setComposerFormValues({ draft: 'ship it' })

        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        expect(lemonToast.error).toHaveBeenCalled()
        expect(logic.values.composerForm.draft).toBe('ship it')
        expect(logic.values.sending).toBe(false)
        expect(toolEvents.values.applyBackTargetClaims[RUN_ID]).toBeUndefined()
    })

    describe('Pi task', () => {
        let piLogic: ReturnType<typeof runInteractionLogic.build>

        beforeEach(() => {
            logic.unmount()
            piLogic = runInteractionLogic({
                taskId: TASK_ID,
                runId: RUN_ID,
                onRunStarted,
                taskRuntime: TaskRuntimeEnumApi.Pi,
            })
            piLogic.mount()
        })

        afterEach(() => {
            piLogic.unmount()
            logic.mount()
        })

        const configCommand = (configId: string, value: string): [string, string, string, Record<string, unknown>] => [
            '997',
            TASK_ID,
            RUN_ID,
            { jsonrpc: '2.0', method: 'set_config_option', params: { configId, value } },
        ]

        it.each([
            { caseName: 'no pick', pick: () => {}, commands: [] },
            {
                caseName: 'a picked model',
                pick: () => piLogic.actions.setModel('claude-opus-5-5'),
                commands: [configCommand('model', 'claude-opus-5-5')],
            },
            {
                caseName: 'a picked effort',
                pick: () => piLogic.actions.setEffort('low'),
                commands: [configCommand('effort', 'low')],
            },
        ])('syncs $caseName to the Pi session before a follow-up', async ({ pick, commands }) => {
            pick()
            piLogic.actions.setComposerFormValues({ draft: 'keep going' })
            await expectLogic(piLogic, () => piLogic.actions.submitComposerForm()).toFinishAllListeners()

            expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([
                ...commands,
                userMessageCommand('keep going'),
            ])
        })

        it.each([
            { caseName: 'no pick', pick: () => {}, selection: {} },
            {
                caseName: 'a picked model and effort',
                pick: () => {
                    piLogic.actions.setModel('claude-opus-5-5')
                    piLogic.actions.setEffort('low')
                },
                selection: { model: 'claude-opus-5-5', reasoning_effort: 'low' },
            },
        ])('resumes a terminal run with $caseName', async ({ pick, selection }) => {
            setStatus('completed')
            pick()
            piLogic.actions.setComposerFormValues({ draft: 'continue from here' })
            await expectLogic(piLogic, () => piLogic.actions.submitComposerForm()).toFinishAllListeners()

            expect(tasksRunCreate).toHaveBeenCalledWith(
                '997',
                TASK_ID,
                { resume_from_run_id: RUN_ID, pending_user_message: 'continue from here', ...selection },
                expect.objectContaining({ signal: expect.any(AbortSignal) })
            )
        })
    })

    it('starts a fresh run seeded with the message when the run is terminal', async () => {
        let resolveRun!: (value: unknown) => void
        ;(tasksRunCreate as jest.Mock).mockReturnValueOnce(
            new Promise((resolve) => {
                resolveRun = resolve
            })
        )
        setStatus('completed')
        logic.actions.setComposerFormValues({ draft: 'continue from here' })
        logic.actions.submitComposerForm()
        expect(logic.values.composerForm.draft).toBe('')
        expect(logic.values.startingRun).toBe(true)
        logic.actions.setComposerFormValues({ draft: 'also check the result' })

        await expectLogic(logic, () => {
            resolveRun({ latest_run: { id: 'run-2' } })
        }).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,
            {
                runtime_adapter: 'claude',
                model: 'claude-sonnet-5-5',
                reasoning_effort: 'high',
                initial_permission_mode: 'auto',
                resume_from_run_id: RUN_ID,
                pending_user_message: 'continue from here',
            },
            expect.objectContaining({ signal: expect.any(AbortSignal) })
        )
        expect(onRunStarted).toHaveBeenCalledWith(
            'run-2',
            expect.objectContaining({ streamKey: RUN_ID, draft: 'also check the result' })
        )
        expect(toolEvents.values.applyBackTargetClaims[RUN_ID]).toEqual([
            { targetId: 'insight-1:activation-1', tools: ['create_insight'] },
        ])
        expect(logic.values.queuedMessages).toEqual([])
        expect(logic.values.composerForm.draft).toBe('also check the result')
    })

    it.each(['failure', 'missing run'])(
        'restores the submitted message ahead of a newer draft after %s',
        async (outcome) => {
            let resolveRun!: (value: unknown) => void
            let rejectRun!: (error: Error) => void
            ;(tasksRunCreate as jest.Mock).mockReturnValueOnce(
                new Promise((resolve, reject) => {
                    resolveRun = resolve
                    rejectRun = reject
                })
            )
            setStatus('completed')
            logic.actions.setComposerFormValues({ draft: 'continue from here' })
            logic.actions.submitComposerForm()
            expect(logic.values.composerForm.draft).toBe('')
            logic.actions.setComposerFormValues({ draft: 'and check the tests' })

            await expectLogic(logic, () => {
                if (outcome === 'failure') {
                    rejectRun(new Error('failed'))
                } else {
                    resolveRun({ latest_run: null })
                }
            }).toFinishAllListeners()

            expect(logic.values.composerForm.draft).toBe('continue from here\n\nand check the tests')
            expect(logic.values.startingRun).toBe(false)
            expect(onRunStarted).not.toHaveBeenCalled()
            expect(lemonToast.error).toHaveBeenCalledWith(GENERIC_FAILURE)
        }
    )

    it.each([
        ['submitted', false],
        ['unmounted', false],
        ['unmounted', true],
        ['failed', false],
        ['failed', true],
    ] as const)('protects the submitted warm when %s (warm pending: %s)', async (outcome, warmPending) => {
        let resolveWarm!: () => void
        let resolveRun!: () => void
        let rejectRun!: () => void
        ;(tasksWarmResumeCreate as jest.Mock).mockReturnValueOnce(
            new Promise((resolve) => {
                resolveWarm = () => resolve({ task_id: TASK_ID, run_id: 'warm-run' })
            })
        )
        ;(tasksRunCreate as jest.Mock).mockReturnValueOnce(
            new Promise((resolve, reject) => {
                resolveRun = () => resolve({ latest_run: { id: 'warm-run' } })
                rejectRun = () => reject(new Error('Connection lost'))
            })
        )
        jest.useFakeTimers()
        try {
            setStatus('cancelled')
            logic.actions.setComposerFormValues({ draft: 'continue from the checkpoint' })
            await jest.advanceTimersByTimeAsync(300)
            if (!warmPending) {
                resolveWarm()
                await jest.advanceTimersByTimeAsync(0)
            }
            expect(tasksWarmResumeCreate).toHaveBeenCalledWith('997', TASK_ID, {
                resume_from_run_id: RUN_ID,
                runtime_adapter: 'claude',
                model: 'claude-sonnet-5-5',
                reasoning_effort: 'high',
                initial_permission_mode: 'auto',
            })

            logic.actions.submitComposerForm()
            expect(tasksRunCreate).toHaveBeenCalledWith(
                '997',
                TASK_ID,
                expect.objectContaining({ resume_from_run_id: RUN_ID }),
                expect.objectContaining({ signal: expect.any(AbortSignal) })
            )
            expect(tasksRunsCancelCreate).not.toHaveBeenCalled()

            if (outcome === 'failed') {
                rejectRun()
                await jest.advanceTimersByTimeAsync(0)
                expect(logic.values.composerForm.draft).toBe('continue from the checkpoint')
            }
            if (outcome !== 'submitted') {
                logic.unmount()
            }
            resolveRun()
            resolveWarm()
            await jest.advanceTimersByTimeAsync(0)

            expect(tasksRunsCancelCreate).not.toHaveBeenCalled()
            if (outcome === 'submitted') {
                expect(onRunStarted).toHaveBeenCalledWith('warm-run', expect.anything())
            } else {
                expect(onRunStarted).not.toHaveBeenCalled()
            }
        } finally {
            resolveRun()
            resolveWarm()
            jest.useRealTimers()
        }
    })

    it('records the boundary instead of starting a run when /clear is sent to a terminal run', async () => {
        setStatus('completed')
        logic.actions.setComposerFormValues({ draft: '/clear' })

        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        // Booting a sandbox would clear a conversation the next run rebuilds from the log anyway.
        expect(tasksRunCreate).not.toHaveBeenCalled()
        expect(tasksRunsClearConversationCreate).toHaveBeenCalledWith('997', TASK_ID, RUN_ID)
        expect(logic.values.composerForm.draft).toBe('')
        // Nothing streams back on a finished run, so the boundary is echoed from here.
        await expectLogic(stream).toDispatchActions([
            (action) => action.type === stream.actionTypes.pushHumanMessage && action.payload.content === '/clear',
            (action) => action.type === stream.actionTypes.pushConversationCleared,
        ])
    })

    it('hands back a warmed successor when /clear succeeds', async () => {
        // The successor booted before the clear boundary was written, so its restored session still
        // holds the conversation /clear promises to remove. Keeping it would let the next message
        // resume the very thing the user just cleared.
        jest.useFakeTimers()
        setStatus('completed')
        logic.actions.setComposerFormValues({ draft: 'keep going' })
        jest.advanceTimersByTime(300)
        jest.useRealTimers()
        await expectLogic(logic).toFinishAllListeners()
        expect(tasksWarmResumeCreate).toHaveBeenCalled()

        logic.actions.setComposerFormValues({ draft: '/clear' })
        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        expect(tasksRunsClearConversationCreate).toHaveBeenCalled()
        expect(tasksRunsCancelCreate).toHaveBeenCalledWith('997', TASK_ID, 'warm-run', {
            only_if_awaiting_first_message: true,
        })
    })

    it('falls back to a new run when the chain agent cannot honour the clear boundary', async () => {
        // An older agent ignores the marker and resumes the conversation it was meant to retire,
        // so a divider here would claim a clear that never happens.
        ;(stream.actions as unknown as { setStubClearSupported: (s: boolean) => void }).setStubClearSupported(false)
        setStatus('completed')
        logic.actions.setComposerFormValues({ draft: '/clear' })

        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        expect(tasksRunsClearConversationCreate).not.toHaveBeenCalled()
        expect(tasksRunCreate).toHaveBeenCalled()
    })

    test.each([
        [new Error('boom'), GENERIC_FAILURE],
        [
            new ApiError('starting', 503, undefined, { code: 'warm_run_activation_unavailable' }),
            "Couldn't start this run yet. Please try again.",
        ],
        [
            new ApiError('starting', 400, undefined, {
                detail: 'A resumed run must use its previous base branch. Omit branch to resume.',
            }),
            'A resumed run must use its previous base branch. Omit branch to resume.',
        ],
        [
            new ApiError('starting', 402, undefined, { error: 'Your organization is over its usage limit.' }),
            'Your organization is over its usage limit.',
        ],
        [new ApiError('starting', 500, undefined, { detail: 'A server error occurred.' }), GENERIC_FAILURE],
        [new ApiError('starting', 503, undefined, null), GENERIC_FAILURE],
    ])('keeps the draft and unsent context when starting a run fails with %s', async (error, message) => {
        let rejectSend!: (error: unknown) => void
        ;(tasksRunCreate as jest.Mock).mockReturnValueOnce(
            new Promise((_, reject) => {
                rejectSend = reject
            })
        )
        attachedContextLogic().actions.registerContext('scene', [
            { type: 'insight', key: 'sig', label: 'Signups', hidden: true },
        ])
        setStatus('completed')
        logic.actions.setComposerFormValues({ draft: 'continue from here' })
        logic.actions.submitComposerForm()

        expect(logic.values.startingRun).toBe(true)
        expect(logic.values.composerForm.draft).toBe('')
        expect(attachedContextLogic().values.sentContextKeysByTask[TASK_ID]).toBeUndefined()

        await expectLogic(logic, () => {
            rejectSend(error)
        }).toFinishAllListeners()

        expect(lemonToast.error).toHaveBeenCalledWith(message)
        expect(onRunStarted).not.toHaveBeenCalled()
        expect(logic.values.startingRun).toBe(false)
        expect(logic.values.composerForm.draft).toBe('continue from here')
        expect(logic.values.pendingContextItems).toEqual([
            { type: 'insight', key: 'sig', label: 'Signups', hidden: true },
        ])
        expect(toolEvents.values.applyBackTargetClaims[RUN_ID]).toBeUndefined()

        await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()

        expect(tasksRunCreate).toHaveBeenCalledTimes(2)
        expect((tasksRunCreate as jest.Mock).mock.calls[1].slice(0, 3)).toEqual(
            (tasksRunCreate as jest.Mock).mock.calls[0].slice(0, 3)
        )
        expect(onRunStarted).toHaveBeenCalledWith('run-2', expect.objectContaining({ streamKey: RUN_ID, draft: '' }))
        expect(logic.values.composerForm.draft).toBe('')
        expect(logic.values.startingRun).toBe(false)
        expect(attachedContextLogic().values.sentContextKeysByTask[TASK_ID]).toEqual(['insight:sig'])
    })

    test.each(['recovered', 'exhausted', 'timeout', 'unmounted'])(
        'keeps a resumed submission pending through bounded frontend retries: %s',
        async (outcome) => {
            jest.useFakeTimers()
            const error = new ApiError('starting', 503, undefined, {
                code: 'warm_run_activation_unavailable',
                retry_token: 'synthetic-retry-token',
            })
            let rejectFirst!: (error: unknown) => void
            let resolveRetry!: (value: unknown) => void
            let rejectRetry!: (error: unknown) => void
            ;(tasksRunCreate as jest.Mock)
                .mockReturnValueOnce(new Promise((_, reject) => (rejectFirst = reject)))
                .mockRejectedValueOnce(error)
                .mockRejectedValueOnce(error)
                .mockReturnValueOnce(
                    new Promise((resolve, reject) => {
                        resolveRetry = resolve
                        rejectRetry = reject
                    })
                )
            try {
                attachedContextLogic().actions.registerContext('scene', [
                    { type: 'insight', key: 'sig', label: 'Signups', hidden: true },
                ])
                setStatus('completed')
                logic.actions.setComposerFormValues({ draft: 'continue from here' })
                logic.actions.submitComposerForm()
                await jest.advanceTimersByTimeAsync(10_000)
                rejectFirst(error)
                await jest.advanceTimersByTimeAsync(1750)
                expect(tasksRunCreate).toHaveBeenCalledTimes(4)
                const calls = (tasksRunCreate as jest.Mock).mock.calls
                for (const call of calls.slice(1)) {
                    expect(call.slice(0, 3)).toEqual(calls[0].slice(0, 3))
                    expect(call[3].headers).toEqual({ 'X-PostHog-Warm-Retry': 'synthetic-retry-token' })
                }
                expect(logic.values.startingRun).toBe(true)
                expect(logic.values.composerForm.draft).toBe('')
                expect(attachedContextLogic().values.sentContextKeysByTask[TASK_ID]).toBeUndefined()
                logic.actions.submitComposerForm()
                expect(tasksRunCreate).toHaveBeenCalledTimes(4)
                if (outcome === 'unmounted') {
                    logic.unmount()
                    resolveRetry({ latest_run: { id: 'warm-run' } })
                    await jest.advanceTimersByTimeAsync(10_000)
                    expect(calls[1][3].signal.aborted).toBe(true)
                    expect(onRunStarted).not.toHaveBeenCalled()
                    return
                }
                await jest.advanceTimersByTimeAsync(8_249)
                expect(logic.values.startingRun).toBe(true)
                await expectLogic(logic, async () => {
                    if (outcome === 'recovered') {
                        resolveRetry({ latest_run: { id: 'warm-run' } })
                    } else if (outcome === 'exhausted') {
                        rejectRetry(
                            new ApiError('starting', 503, undefined, { code: 'warm_run_activation_unavailable' })
                        )
                    } else {
                        await jest.advanceTimersByTimeAsync(1)
                    }
                }).toFinishAllListeners()
                expect(tasksRunCreate).toHaveBeenCalledTimes(4)
                expect(logic.values.startingRun).toBe(false)
                if (outcome === 'recovered') {
                    expect(onRunStarted).toHaveBeenCalledWith(
                        'warm-run',
                        expect.objectContaining({ streamKey: RUN_ID, draft: '' })
                    )
                    expect(logic.values.composerForm.draft).toBe('')
                } else {
                    expect(onRunStarted).not.toHaveBeenCalled()
                    expect(logic.values.composerForm.draft).toBe('continue from here')
                    expect(logic.values.pendingContextItems).toEqual([
                        { type: 'insight', key: 'sig', label: 'Signups', hidden: true },
                    ])
                    expect(lemonToast.error).toHaveBeenCalledWith("Couldn't start this run yet. Please try again.")
                    resolveRetry({ latest_run: { id: 'late-run' } })
                    await jest.advanceTimersByTimeAsync(0)
                    expect(onRunStarted).not.toHaveBeenCalled()
                }
            } finally {
                jest.useRealTimers()
            }
        }
    )

    it.each(['global', 'runner'])('wraps and deduplicates %s context while echoing raw text', async (scope) => {
        const contextItems = [
            { type: 'insight', key: 'sig', label: 'Signups', hidden: true },
            { type: 'text', value: 'always resend me', hidden: true },
        ]
        attachedContextLogic().actions.registerContext(
            'scene',
            scope === 'global' ? contextItems : [{ type: 'text', value: 'unrelated scene context', hidden: true }]
        )
        if (scope === 'runner') {
            logic.unmount()
            logic = runInteractionLogic({ taskId: TASK_ID, runId: RUN_ID, onRunStarted, contextItems })
            logic.mount()
        }
        setThinking(false)

        logic.actions.setComposerFormValues({ draft: 'why the drop?' })
        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        const firstSend = (tasksRunsCommandCreate as jest.Mock).mock.calls[0][3] as {
            params: { content: string }
        }
        // The wire content carries the invisible context block; the echoed human message stays raw.
        expect(firstSend.params.content).toContain('<posthog_untrusted_context>')
        expect(firstSend.params.content).toContain('- insight sig ("Signups")')
        expect(firstSend.params.content).not.toContain('unrelated scene context')
        expect(firstSend.params.content.endsWith('why the drop?')).toBe(true)
        await expectLogic(stream).toDispatchActions([
            (action) =>
                action.type === stream.actionTypes.pushHumanMessage && action.payload.content === 'why the drop?',
        ])

        // A second send on the same task must not re-inflate already-sent entity refs — but `text`
        // items are never deduped (repeated text is intentional, mirroring the backend).
        ;(tasksRunsCommandCreate as jest.Mock).mockClear()
        logic.actions.setComposerFormValues({ draft: 'follow up' })
        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        const secondSend = (tasksRunsCommandCreate as jest.Mock).mock.calls[0][3] as {
            params: { content: string }
        }
        expect(secondSend.params.content).not.toContain('- insight sig')
        expect(secondSend.params.content).toContain('- text: "always resend me"')
        expect(secondSend.params.content.endsWith('follow up')).toBe(true)
    })

    it('sends a pick but not the visible context of the current page, and keeps the pick on a failed send', async () => {
        const pick = { type: 'dashboard', key: 7, label: 'Weekly' }
        attachedContextLogic().actions.registerContext('scene', [{ type: 'insight', key: 'nav', label: 'Other page' }])
        attachedContextLogic().actions.pickItem(pick, TASK_ID)
        setThinking(false)
        ;(tasksRunsCommandCreate as jest.Mock).mockRejectedValueOnce(new Error('Connection lost'))

        logic.actions.setComposerFormValues({ draft: 'follow up' })
        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        expect(attachedContextLogic().values.pickedByChat[TASK_ID]).toEqual([pick])
        expect(attachedContextLogic().values.chatChipsByTask[TASK_ID]).toBeUndefined()
        ;(tasksRunsCommandCreate as jest.Mock).mockClear()

        logic.actions.setComposerFormValues({ draft: 'follow up' })
        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        const send = (tasksRunsCommandCreate as jest.Mock).mock.calls[0][3] as { params: { content: string } }
        expect(send.params.content).toContain('- dashboard 7 ("Weekly")')
        expect(send.params.content).not.toContain('- insight nav')
        expect(attachedContextLogic().values.chatChipsByTask[TASK_ID].map((chip) => chip.id)).toEqual(['dashboard:7'])
        expect(attachedContextLogic().values.pickedByChat[TASK_ID]).toEqual([])
    })

    it('leaves a pick made in another chat out of this chat', async () => {
        attachedContextLogic().actions.pickItem({ type: 'dashboard', key: 7, label: 'Weekly' }, 'another-task')
        setThinking(false)

        logic.actions.setComposerFormValues({ draft: 'follow up' })
        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        const send = (tasksRunsCommandCreate as jest.Mock).mock.calls[0][3] as { params: { content: string } }
        expect(send.params.content).not.toContain('- dashboard 7')
    })

    it('prunes context whose rendered line the run log already carries, even with no sent-key bookkeeping', async () => {
        // The reload scenario: `sentContextKeysByTask` is empty (fresh session), but `runStreamLogic`
        // recorded the block lines it found replaying the resume-chain history — the same ref must not
        // be re-wrapped into the next send.
        const seenItem = { type: 'insight', key: 'sig', label: 'Signups', hidden: true }
        attachedContextLogic().actions.registerContext('scene', [seenItem])
        attachedContextLogic().actions.markContextLinesSeen(TASK_ID, [contextItemLine(seenItem)])
        setThinking(false)

        logic.actions.setComposerFormValues({ draft: 'follow up' })
        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        const send = (tasksRunsCommandCreate as jest.Mock).mock.calls[0][3] as { params: { content: string } }
        // The only attached item is already in the chain history, so no context block is prepended.
        expect(send.params.content).toBe('follow up')
    })

    it('sends /clear unwrapped so the agent still sees the command at the front, and keeps the context pending', async () => {
        const item = { type: 'insight', key: 'sig', label: 'Signups', hidden: true }
        attachedContextLogic().actions.registerContext('scene', [item])
        setThinking(false)

        logic.actions.setComposerFormValues({ draft: '/clear' })
        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        const send = (tasksRunsCommandCreate as jest.Mock).mock.calls[0][3] as { params: { content: string } }
        expect(send.params.content).toBe('/clear')

        // The agent drops the message rather than reading it, so the ref was never really delivered:
        // the next real send must still carry it.
        ;(tasksRunsCommandCreate as jest.Mock).mockClear()
        logic.actions.setComposerFormValues({ draft: 'why the drop?' })
        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        const next = (tasksRunsCommandCreate as jest.Mock).mock.calls[0][3] as { params: { content: string } }
        expect(next.params.content).toContain('- insight sig ("Signups")')
    })

    it('keeps pruning context sent by a terminal-run send after re-pointing to the fresh run', async () => {
        attachedContextLogic().actions.registerContext('scene', [
            { type: 'insight', key: 'sig', label: 'Signups', hidden: true },
        ])

        // A send on a finished run starts a fresh run, wrapping the pending context into its seed message.
        setStatus('completed')
        logic.actions.setComposerFormValues({ draft: 'continue from here' })
        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        const createRequest = (tasksRunCreate as jest.Mock).mock.calls[0][2] as { pending_user_message: string }
        expect(createRequest.pending_user_message).toContain('- insight sig ("Signups")')
        expect(onRunStarted).toHaveBeenCalledWith('run-2', expect.objectContaining({ streamKey: RUN_ID, draft: '' }))

        // The consumer re-points to the new run: a fresh logic instance keyed by the new runId, same task.
        // Sent-context bookkeeping is task-scoped, so the first follow-up must not re-wrap the same ref.
        const nextStream = runStreamLogic({ streamKey: 'run-2' })
        nextStream.mount()
        const nextLogic = runInteractionLogic({ taskId: TASK_ID, runId: 'run-2', onRunStarted })
        nextLogic.mount()
        try {
            nextLogic.actions.setComposerFormValues({ draft: 'follow up' })
            await expectLogic(nextLogic, () => {
                nextLogic.actions.submitComposerForm()
            }).toFinishAllListeners()

            const followUp = (tasksRunsCommandCreate as jest.Mock).mock.calls[0][3] as {
                params: { content: string }
            }
            // The only attached item was already sent this task, so no context block is prepended at all.
            expect(followUp.params.content).toBe('follow up')
        } finally {
            nextLogic.unmount()
            nextStream.unmount()
        }
    })

    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.setComposerFormValues({ draft: 'ship it' })

        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        // Nothing can be sent without a project — the draft is preserved rather than dropped.
        expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
        expect(logic.values.composerForm.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.setComposerFormValues({ draft: 'follow up' })

        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).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.composerForm.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 () => {
        logic.actions.enableTaskDraftPersistence('user-1', 997)
        const key = taskDraftStorageKey('user-1', 997, TASK_ID)
        let resolveSend: () => void = () => {}
        ;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(
            new Promise((resolve) => {
                resolveSend = () => resolve({ jsonrpc: '2.0', result: { queued: true } })
            })
        )

        // Idle send straight from the draft: the draft is cleared up-front, before the await.
        setThinking(false)
        logic.actions.setComposerFormValues({ draft: 'ship it' })
        logic.actions.submitComposerForm()
        expect(logic.values.sending).toBe(true)
        expect(logic.values.composerForm.draft).toBe('')

        // The user keeps typing while the send is in flight.
        logic.actions.setComposerFormValues({ draft: 'next thought' })

        expect(new TaskDraftPersistence(key).restore()).toEqual({
            draft: 'ship it\n\nnext thought',
            recovery: 'unconfirmed',
        })

        await expectLogic(logic, () => {
            resolveSend()
        }).toFinishAllListeners()

        // Success leaves the composer alone — the newly typed text survives rather than being wiped.
        expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('ship it'))
        expect(logic.values.composerForm.draft).toBe('next thought')
        expect(new TaskDraftPersistence(key).restore()).toEqual({ draft: 'next thought', recovery: 'restored' })
    })

    it('restores a failed draft send ahead of text typed during the send, preserving order', async () => {
        let rejectSend: () => void = () => {}
        ;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(
            new Promise<void>((_, reject) => {
                rejectSend = () => reject(new Error('boom'))
            })
        )

        setThinking(false)
        logic.actions.setComposerFormValues({ draft: 'ship it' })
        logic.actions.submitComposerForm()
        expect(logic.values.composerForm.draft).toBe('')

        logic.actions.setComposerFormValues({ draft: '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.composerForm.draft).toBe('ship it\n\nnext thought')
    })

    it('flushes a keystroke still buffered in the composer before restoring a failed draft send', async () => {
        // The composer debounces its writes to kea, so text typed in the last moments of an in-flight send
        // is still local. Restoring the failed message cancels that pending sync, so it has to be landed
        // first or it is dropped instead of merged behind the retry.
        let pendingKeystroke = ''
        const attached = runInteractionLogic({
            taskId: TASK_ID,
            runId: 'flush-run',
            onRunStarted,
            flushDraft: () => {
                if (pendingKeystroke) {
                    attached.actions.setComposerFormValues({ draft: pendingKeystroke })
                    pendingKeystroke = ''
                }
            },
        })
        const unmount = attached.mount()
        try {
            let rejectSend: () => void = () => {}
            ;(tasksRunsCommandCreate as jest.Mock).mockReturnValue(
                new Promise<void>((_, reject) => {
                    rejectSend = () => reject(new Error('boom'))
                })
            )

            attached.actions.setComposerFormValues({ draft: 'ship it' })
            attached.actions.submitComposerForm()
            expect(attached.values.composerForm.draft).toBe('')

            pendingKeystroke = 'next thought'

            await expectLogic(attached, () => {
                rejectSend()
            }).toFinishAllListeners()

            expect(attached.values.composerForm.draft).toBe('ship it\n\nnext thought')
        } finally {
            unmount()
        }
    })

    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((resolve) => {
                resolveSend = () => resolve({ jsonrpc: '2.0', result: { queued: true } })
            })
        )

        // Stage a message while busy, then complete the turn to start flushing it.
        setThinking(true)
        logic.actions.setComposerFormValues({ draft: 'first' })
        logic.actions.submitComposerForm()

        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.setComposerFormValues({ draft: 'second' })
        logic.actions.submitComposerForm()
        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.setComposerFormValues({ draft: 'first' })
        logic.actions.submitComposerForm()

        setThinking(false)
        stream.actions.markTurnComplete()
        expect(logic.values.queuedMessages).toEqual([])

        // A follow-up staged while the flush is in flight.
        logic.actions.setComposerFormValues({ draft: 'second' })
        logic.actions.submitComposerForm()

        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' },
            { id: expect.any(String), content: 'second' },
        ])
    })

    // The tasks run backend has no server-side consent check, so a follow-up (or a fresh-run send on a
    // terminal run) must be blocked client-side before it reaches `tasksRunsCommandCreate` /
    // `tasksRunCreate`. Uses a distinct `runId` key so the logic is built (and connects to
    // `aiConsentLogic`) after the selector is stubbed.
    it.each(['draft', 'steer'])(
        'blocks %s without consent and never substitutes the unsent draft for steering',
        async (source) => {
            const consent = aiConsentLogic()
            consent.mount()
            const consentAccepted = jest.spyOn(consent.selectors, 'dataProcessingAccepted').mockReturnValue(false)

            const blockedRunId = 'run-blocked'
            const blockedStream = runStreamLogic({ streamKey: blockedRunId })
            blockedStream.mount()
            const blockedLogic = runInteractionLogic({ taskId: TASK_ID, runId: blockedRunId, onRunStarted })
            blockedLogic.mount()

            // Terminal, so typing would otherwise warm a successor — which boots a cloud sandbox and
            // restores the repository snapshot, before the organization has accepted anything.
            ;(blockedStream.actions as unknown as { setStubStatus: (status: string | null) => void }).setStubStatus(
                source === 'draft' ? 'completed' : 'in_progress'
            )
            jest.useFakeTimers()
            blockedLogic.actions.setComposerFormValues({ draft: 'ship it' })
            jest.advanceTimersByTime(300)
            jest.useRealTimers()
            await expectLogic(blockedLogic, () => {
                if (source === 'draft') {
                    blockedLogic.actions.submitComposerForm()
                } else {
                    blockedLogic.actions.enqueueMessage('saved follow up')
                    blockedLogic.actions.steerQueue()
                }
            }).toFinishAllListeners()

            expect(tasksWarmResumeCreate).not.toHaveBeenCalled()
            expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
            expect(tasksRunCreate).not.toHaveBeenCalled()
            expect(blockedLogic.values.consentBlocked).toBe(true)

            if (source === 'steer') {
                consentAccepted.mockReturnValue(true)
                await expectLogic(blockedLogic, () => blockedLogic.actions.submitAfterConsent()).toFinishAllListeners()
                expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', TASK_ID, blockedRunId, {
                    jsonrpc: '2.0',
                    method: 'user_message',
                    params: { content: 'saved follow up', steer: true },
                })
                expect(blockedLogic.values.composerForm.draft).toBe('ship it')
            }

            blockedLogic.unmount()
            blockedStream.unmount()
            consent.unmount()
            jest.restoreAllMocks()
        }
    )

    it('no-ops on submit with an empty draft', async () => {
        await expectLogic(logic, () => {
            logic.actions.submitComposerForm()
        }).toFinishAllListeners()

        expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
        expect(logic.values.queuedMessages).toEqual([])
    })
    it('changing mode after a lost response preserves the first submitted warm', async () => {
        let finishWarm!: () => void
        ;(tasksWarmResumeCreate as jest.Mock).mockReturnValueOnce(
            new Promise((resolve) => {
                finishWarm = () => resolve({ task_id: TASK_ID, run_id: 'warm-run' })
            })
        )
        ;(tasksRunCreate as jest.Mock)
            .mockRejectedValueOnce(new Error('Connection lost'))
            .mockResolvedValueOnce({ latest_run: { id: 'retry-run' } })
        jest.useFakeTimers()
        try {
            setStatus('completed')
            logic.actions.setComposerFormValues({ draft: 'continue from the checkpoint' })
            await jest.advanceTimersByTimeAsync(300)
            expect(tasksWarmResumeCreate).toHaveBeenCalledTimes(1)
            logic.actions.submitComposerForm()
            await jest.advanceTimersByTimeAsync(0)
            expect(logic.values.startingRun).toBe(false)
            expect(logic.values.composerForm.draft).toBe('continue from the checkpoint')
            logic.actions.setMode('plan')
            logic.actions.submitComposerForm()
            await jest.advanceTimersByTimeAsync(0)
            expect(tasksRunCreate).toHaveBeenCalledTimes(2)
            expect(tasksRunCreate).toHaveBeenLastCalledWith(
                '997',
                TASK_ID,
                expect.objectContaining({ initial_permission_mode: 'plan' }),
                expect.anything()
            )
            expect(onRunStarted).toHaveBeenCalledWith('retry-run', expect.anything())
            finishWarm()
            await jest.advanceTimersByTimeAsync(0)
            expect(tasksRunsCancelCreate).not.toHaveBeenCalled()
        } finally {
            finishWarm()
            jest.useRealTimers()
        }
    })

    it.each([false, true])(
        'preserves a submitted warm across composers (warm response ready: %s)',
        async (warmReady) => {
            let finishWarm!: () => void
            let finishFirstRun!: () => void
            let finishSecondRun!: () => void
            ;(tasksWarmResumeCreate as jest.Mock).mockReturnValueOnce(
                new Promise((resolve) => {
                    finishWarm = () => resolve({ task_id: TASK_ID, run_id: 'warm-run' })
                })
            )
            ;(tasksRunCreate as jest.Mock)
                .mockReturnValueOnce(
                    new Promise((resolve) => {
                        finishFirstRun = () => resolve({ latest_run: { id: 'warm-run' } })
                    })
                )
                .mockReturnValueOnce(
                    new Promise((resolve) => {
                        finishSecondRun = () => resolve({ latest_run: { id: 'cold-run' } })
                    })
                )
            logic.unmount()
            logic = runInteractionLogic({
                taskId: TASK_ID,
                runId: RUN_ID,
                interactionKey: 'optimistic-panel',
                streamKey: 'panel-stream',
            })
            logic.mount()
            const panelStream = runStreamLogic({ streamKey: 'panel-stream' })
            ;(panelStream.actions as any).setStubStatus('cancelled')
            const second = runInteractionLogic({ taskId: TASK_ID, runId: RUN_ID })
            second.mount()
            jest.useFakeTimers()
            try {
                setStatus('cancelled')
                logic.actions.setComposerFormValues({ draft: 'first composer' })
                await jest.advanceTimersByTimeAsync(300)
                expect(tasksWarmResumeCreate).toHaveBeenCalledTimes(1)
                if (warmReady) {
                    finishWarm()
                    await jest.advanceTimersByTimeAsync(0)
                }
                logic.actions.submitComposerForm()
                second.actions.setMode('plan')
                second.actions.setComposerFormValues({ draft: 'second composer' })
                second.actions.submitComposerForm()
                expect(tasksRunCreate).toHaveBeenCalledTimes(2)
                finishSecondRun()
                await jest.advanceTimersByTimeAsync(0)
                expect(logic.values.startingRun).toBe(true)
                finishWarm()
                await jest.advanceTimersByTimeAsync(0)
                expect(tasksRunsCancelCreate).not.toHaveBeenCalled()
            } finally {
                finishFirstRun()
                finishSecondRun()
                finishWarm()
                await jest.advanceTimersByTimeAsync(0)
                second.unmount()
                jest.useRealTimers()
            }
        }
    )
})