Skip to content

The agent that grows with you

43.3 KB
Raw Blame
import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
import { type Dispatch, type PropsWithChildren, type SetStateAction, useLayoutEffect, useState } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import * as sessionOwnerUtils from '@/app/session/hooks/use-session-actions/utils'
import { PaneVisibleContext } from '@/components/pane-shell/pane-visibility'
import { $clarifyRequests } from '@/store/clarify'
import {
  clearComposerTerminalSelections,
  type ComposerAttachment,
  setComposerTerminalSelection
} from '@/store/composer'
import { $queuedPromptsBySession, clearQueuedPrompts, getQueuedPrompts } from '@/store/composer-queue'
import { $connectionRequests, type ConnectionRequest } from '@/store/connection-request'
import { $gateway } from '@/store/gateway'
import { $notifications } from '@/store/notifications'
import { $onboardingPhase } from '@/store/onboarding-phase'
import { $onboardingSession } from '@/store/onboarding-session'
import {
  clearAllPrompts,
  hasBlockingPromptRequest,
  setApprovalRequest,
  setSecretRequest,
  setSudoRequest
} from '@/store/prompts'
import { hasOpenServerRequest, rememberServerRequest, resetServerRequestsForTests } from '@/store/server-requests'
import { $connection } from '@/store/session'
import { $setupBeatRequests, parkSetupBeat } from '@/store/setup-beat'

import { type ComposerTarget, requestComposerSubmit } from '../focus'
import { ComposerScopeProvider, ComposerSurfaceProvider, MAIN_COMPOSER_SCOPE } from '../scope'

import { useComposerSubmit } from './use-composer-submit'

interface SubmitHarnessOptions {
  attachments?: ComposerAttachment[]
  busy?: boolean
  busyInputMode?: 'interrupt' | 'queue' | 'steer' | null
  inputDisabled?: boolean
  scopeTarget?: ComposerTarget
  sessionKey?: string | null
  submitOnHide?: boolean
  surfaceId?: string | null
  text?: string
  visible?: boolean
}

let surfaceSequence = 0

function renderSubmitHook({
  attachments = [],
  busy = false,
  busyInputMode = 'interrupt',
  inputDisabled = false,
  scopeTarget = 'main',
  sessionKey = 'stored-session',
  submitOnHide = false,
  surfaceId,
  text = '',
  visible = true
}: SubmitHarnessOptions = {}) {
  const resolvedSurfaceId = surfaceId === undefined ? `test-surface-${++surfaceSequence}` : surfaceId
  const draftRef = { current: text }
  const draftScopeRef = { current: sessionKey }
  const editor = window.document.createElement('div')
  editor.dataset.slot = 'composer-rich-input'
  editor.textContent = text
  const editorRef = { current: editor }
  const focusInput = vi.fn()
  const loadIntoComposer = vi.fn()
  const stashAt = vi.fn()
  const onCancel = vi.fn()
  const onSteer = vi.fn(async () => true)
  const onSteerHidden = vi.fn(async () => true)
  const onSubmit = vi.fn(async () => true)
  const queueCurrentDraft = vi.fn(() => true)
  let updatePaneVisible: Dispatch<SetStateAction<boolean>> | undefined

  const clearDraft = vi.fn(() => {
    draftRef.current = ''
    editorRef.current!.textContent = ''
  })

  const Wrapper = ({ children }: PropsWithChildren) => {
    const [paneVisible, setPaneVisible] = useState(visible)
    updatePaneVisible = setPaneVisible

    useLayoutEffect(() => {
      if (submitOnHide && !paneVisible) {
        requestComposerSubmit('ship while hiding', { target: scopeTarget })
      }
    }, [paneVisible])

    return (
      <ComposerScopeProvider value={{ ...MAIN_COMPOSER_SCOPE, target: scopeTarget }}>
        <ComposerSurfaceProvider value={resolvedSurfaceId}>
          <PaneVisibleContext.Provider value={paneVisible}>
            <div
              data-composer-surface-id={resolvedSurfaceId ?? undefined}
              data-composer-target={scopeTarget}
              data-pane-hidden={paneVisible ? undefined : ''}
            >
              {children}
            </div>
          </PaneVisibleContext.Provider>
        </ComposerSurfaceProvider>
      </ComposerScopeProvider>
    )
  }

  const hook = renderHook(
    () =>
      useComposerSubmit({
        activeQueueSessionKey: sessionKey,
        activeQueueSessionKeyRef: { current: sessionKey },
        attachments,
        busy,
        busyInputMode,
        clearDraft,
        disabled: false,
        draftScopeRef,
        draftRef,
        drainNextQueued: vi.fn(async () => false),
        editorRef,
        exitQueuedEdit: vi.fn(() => false),
        focusInput,
        inputDisabled,
        loadIntoComposer,
        onCancel,
        onSteer,
        onSteerHidden,
        onSubmit,
        queueCurrentDraft,
        queueEdit: null,
        queuedPrompts: [],
        sessionId: 'runtime-session',
        setComposerText: vi.fn(),
        stashAt
      }),
    { wrapper: Wrapper }
  )

  return {
    loadIntoComposer,
    stashAt,
    clearDraft,
    editor,
    focusInput,
    hook,
    onCancel,
    onSteer,
    onSteerHidden,
    onSubmit,
    queueCurrentDraft,
    composerSurfaceId: resolvedSurfaceId,
    setPaneVisible(nextVisible: boolean) {
      if (!updatePaneVisible) {
        throw new Error('Pane visibility setter was not initialized')
      }

      updatePaneVisible(nextVisible)
    }
  }
}

describe('useComposerSubmit external request routing', () => {
  afterEach(() => {
    cleanup()
    clearQueuedPrompts('stored-session')
    vi.restoreAllMocks()
  })

  it.each(['interrupt', 'steer'] as const)(
    'keeps a rejected %s draft in the local queue without submit admission',
    async mode => {
      const h = renderSubmitHook({ busy: true, busyInputMode: mode, text: 'keep guidance' })
      h.onSteer.mockRejectedValue(new Error('correction unsupported'))
      act(() => h.hook.result.current.submitDraft())
      await waitFor(() => expect(getQueuedPrompts('stored-session').map(({ text }) => text)).toEqual(['keep guidance']))
      expect(h.onSteer).toHaveBeenCalledWith('keep guidance', mode)
      expect(h.onSubmit).not.toHaveBeenCalled()
      expect(h.queueCurrentDraft).not.toHaveBeenCalled()
      clearQueuedPrompts('stored-session')
    }
  )

  it('routes a refused native steer through canonical queue admission', async () => {
    $connection.set({ mode: 'local', wsUrl: 'ws://localhost/api/ws?native_dial=unminted' } as never)
    $queuedPromptsBySession.set({})
    const h = renderSubmitHook({ busy: true, text: 'keep guidance' })
    h.onSteer.mockResolvedValue(false)

    try {
      act(() => h.hook.result.current.steerDraft())
      await waitFor(() =>
        expect(h.onSubmit).toHaveBeenCalledWith(
          'keep guidance',
          expect.objectContaining({ fromQueue: true, sessionId: 'runtime-session', storedSessionId: 'stored-session' })
        )
      )
      expect(getQueuedPrompts('stored-session')).toEqual([])
    } finally {
      $connection.set(null)
      $queuedPromptsBySession.set({})
    }
  })

  it.each([true, false])('steers a busy external visible submit and queues only on rejection (%s)', async accepted => {
    const { onSteer, onSubmit, clearDraft } = renderSubmitHook({ busy: true, text: 'unsent draft' })
    onSteer.mockResolvedValue(accepted)

    await act(async () => {
      expect(requestComposerSubmit('Start without connections.', { target: 'main' })).toBe(true)
    })

    expect(onSteer).toHaveBeenCalledExactlyOnceWith('Start without connections.')
    expect(onSubmit).not.toHaveBeenCalled()
    expect(clearDraft).not.toHaveBeenCalled()
    expect(getQueuedPrompts('stored-session').map(({ text, attachments }) => ({ text, attachments }))).toEqual(
      accepted ? [] : [{ text: 'Start without connections.', attachments: [] }]
    )

    await act(async () => {
      requestComposerSubmit('/status', { target: 'main' })
    })
    expect(getQueuedPrompts('stored-session').at(-1)?.text).toBe('/status')
    expect(onSteer).toHaveBeenCalledTimes(1)
    expect(onSubmit).not.toHaveBeenCalled()
  })

  it.each([true, false])(
    'delivers a busy hidden request as a steer with no user turn and queues it hidden on refusal (%s)',
    async accepted => {
      const { onSteer, onSteerHidden, onSubmit, loadIntoComposer, stashAt } = renderSubmitHook({ busy: true })
      onSteerHidden.mockResolvedValue(accepted)

      await act(async () => {
        requestComposerSubmit('[setup] links opened', { target: 'main', displayKind: 'hidden' })
      })

      expect(onSteerHidden).toHaveBeenCalledExactlyOnceWith('[setup] links opened')
      expect(onSteer).not.toHaveBeenCalled()
      expect(onSubmit).not.toHaveBeenCalled()
      expect(getQueuedPrompts('stored-session').map(({ text, displayKind }) => ({ text, displayKind }))).toEqual(
        accepted ? [] : [{ text: '[setup] links opened', displayKind: 'hidden' }]
      )
      expect(loadIntoComposer).not.toHaveBeenCalled()
      expect(stashAt).not.toHaveBeenCalled()
    }
  )

  it('drops an idle hidden request the gateway rejects instead of restoring it into the draft', async () => {
    const { onSteer, onSubmit, loadIntoComposer, stashAt } = renderSubmitHook({ busy: false })
    onSubmit.mockResolvedValue(false)

    await act(async () => {
      requestComposerSubmit('[setup] links opened', { target: 'main', displayKind: 'hidden' })
    })

    expect(onSubmit).toHaveBeenCalledExactlyOnceWith('[setup] links opened', {
      submission_id: expect.any(String),
      attachments: [],
      composerScope: 'stored-session',
      displayKind: 'hidden'
    })
    expect(onSteer).not.toHaveBeenCalled()
    expect(getQueuedPrompts('stored-session')).toEqual([])
    expect(loadIntoComposer).not.toHaveBeenCalled()
    expect(stashAt).not.toHaveBeenCalled()
  })

  it.each([true, false])(
    'sends an idle external request without the draft files, and queues a rejected one instead of overwriting the draft (%s)',
    async accepted => {
      const draftFile = { id: 'draft-file', kind: 'file', label: 'notes.md' } as never

      const { onSubmit, loadIntoComposer, stashAt, clearDraft } = renderSubmitHook({
        attachments: [draftFile],
        busy: false,
        text: 'half-written draft'
      })

      onSubmit.mockResolvedValue(accepted)

      await act(async () => {
        expect(requestComposerSubmit('continue', { target: 'main' })).toBe(true)
      })

      expect(onSubmit).toHaveBeenCalledExactlyOnceWith('continue', expect.objectContaining({ attachments: [] }))
      expect(clearDraft).not.toHaveBeenCalled()
      expect(loadIntoComposer).not.toHaveBeenCalled()
      expect(stashAt).not.toHaveBeenCalled()
      expect(getQueuedPrompts('stored-session').map(({ text, attachments }) => ({ text, attachments }))).toEqual(
        accepted ? [] : [{ text: 'continue', attachments: [] }]
      )

      if (!accepted) {
        // Same message, same identity: the rejection may follow an uncertain delivery the owner dedupes by id.
        const [, options] = onSubmit.mock.calls[0] as unknown as [string, { submission_id: string }]
        expect(getQueuedPrompts('stored-session')[0]?.id).toBe(options.submission_id)
      }
    }
  )

  it('queues a rejected external request from a new chat under the session it was created in', async () => {
    const { onSubmit } = renderSubmitHook({ busy: false, sessionKey: '__new__:fresh-draft' })

    const submit = onSubmit as unknown as ReturnType<
      typeof vi.fn<(text: string, options?: { onComposerScopeAssigned?: (scope: string) => void }) => Promise<boolean>>
    >

    submit.mockImplementation(async (_text, options) => {
      options?.onComposerScopeAssigned?.('created-session')

      return false
    })

    try {
      await act(async () => {
        expect(requestComposerSubmit('continue', { target: 'main' })).toBe(true)
      })

      await waitFor(() => expect(getQueuedPrompts('created-session').map(({ text }) => text)).toEqual(['continue']))
      expect(getQueuedPrompts('__new__:fresh-draft')).toEqual([])
    } finally {
      clearQueuedPrompts('created-session')
    }
  })

  it('does not fan out a main ship across keep-alives or other projects', async () => {
    const visibleMain = renderSubmitHook({ sessionKey: 'session-a' })
    const hiddenMain = renderSubmitHook({ sessionKey: 'session-b', visible: false })
    const visibleTile = renderSubmitHook({ scopeTarget: 'tile:project-b', sessionKey: 'tile-session' })

    const hiddenTile = renderSubmitHook({
      scopeTarget: 'tile:project-c',
      sessionKey: 'other-tile',
      visible: false
    })

    expect(requestComposerSubmit('ship this branch', { target: 'main' })).toBe(true)

    await waitFor(() =>
      expect(visibleMain.onSubmit).toHaveBeenCalledWith('ship this branch', {
        submission_id: expect.any(String),
        attachments: [],
        composerScope: 'session-a'
      })
    )
    expect(visibleMain.onSubmit).toHaveBeenCalledTimes(1)
    expect(hiddenMain.onSubmit).not.toHaveBeenCalled()
    expect(visibleTile.onSubmit).not.toHaveBeenCalled()
    expect(hiddenTile.onSubmit).not.toHaveBeenCalled()
  })

  it('routes a tile-targeted submit to that tile only', async () => {
    const main = renderSubmitHook({ sessionKey: 'main-session' })
    const tile = renderSubmitHook({ scopeTarget: 'tile:project-b', sessionKey: 'tile-session' })

    expect(requestComposerSubmit('ship project B', { target: 'tile:project-b' })).toBe(true)

    await waitFor(() =>
      expect(tile.onSubmit).toHaveBeenCalledWith('ship project B', {
        submission_id: expect.any(String),
        attachments: [],
        composerScope: 'tile-session'
      })
    )
    expect(main.onSubmit).not.toHaveBeenCalled()
  })

  it('uses the captured surface id when two visible composers share a target', async () => {
    const first = renderSubmitHook({ sessionKey: 'session-first' })
    const second = renderSubmitHook({ sessionKey: 'session-second' })

    requestComposerSubmit('ship exactly one session', { surfaceId: second.composerSurfaceId, target: 'main' })

    await waitFor(() =>
      expect(second.onSubmit).toHaveBeenCalledWith('ship exactly one session', {
        submission_id: expect.any(String),
        attachments: [],
        composerScope: 'session-second'
      })
    )
    expect(first.onSubmit).not.toHaveBeenCalled()
  })

  it('submits to the session visible at click time even when the same click switches tabs', async () => {
    const hiddenA = renderSubmitHook({ sessionKey: 'session-a', visible: false })
    const visibleB = renderSubmitHook({ sessionKey: 'session-b' })

    act(() => {
      requestComposerSubmit('ship session B', { target: 'main' })
      visibleB.setPaneVisible(false)
      hiddenA.setPaneVisible(true)
    })

    await waitFor(() =>
      expect(visibleB.onSubmit).toHaveBeenCalledWith('ship session B', {
        submission_id: expect.any(String),
        attachments: [],
        composerScope: 'session-b'
      })
    )
    expect(hiddenA.onSubmit).not.toHaveBeenCalled()
  })

  it('does not fan out when visible composers do not have queue session keys yet', async () => {
    const firstNewSession = renderSubmitHook({ sessionKey: null })
    const secondNewSession = renderSubmitHook({ sessionKey: null })

    act(() => {
      requestComposerSubmit('ship the visible new session', { target: 'main' })
    })

    await waitFor(() => expect(firstNewSession.onSubmit).toHaveBeenCalledTimes(1))
    expect(secondNewSession.onSubmit).not.toHaveBeenCalled()
  })

  it('fails closed when the visible composer has no surface identity', () => {
    const unidentified = renderSubmitHook({ surfaceId: null })

    expect(requestComposerSubmit('do not broadcast this', { target: 'main' })).toBe(false)
    expect(unidentified.onSubmit).not.toHaveBeenCalled()
  })

  it('fails closed when a pinned origin surface is no longer visible', () => {
    const hidden = renderSubmitHook({ sessionKey: 'hidden-origin', visible: false })
    const visible = renderSubmitHook({ sessionKey: 'other-visible' })

    expect(
      requestComposerSubmit('do not send to a stale origin', {
        surfaceId: hidden.composerSurfaceId,
        target: 'main'
      })
    ).toBe(false)
    expect(hidden.onSubmit).not.toHaveBeenCalled()
    expect(visible.onSubmit).not.toHaveBeenCalled()
  })

  it('does not submit through a composer whose pane is hidden during the request', () => {
    const main = renderSubmitHook({ submitOnHide: true })

    act(() => main.setPaneVisible(false))

    expect(main.onSubmit).not.toHaveBeenCalled()
  })

  it('does not submit through a disabled composer', () => {
    const disabled = renderSubmitHook({ inputDisabled: true })

    requestComposerSubmit('do not send this', { target: 'main' })

    expect(disabled.onSubmit).not.toHaveBeenCalled()
  })
})

describe('useComposerSubmit busy-turn routing', () => {
  it('honors configured busy mode while explicit steering and queueing override it on every surface', async () => {
    for (const scopeTarget of ['main', 'tile:stored-session'] as const) {
      for (const mode of ['interrupt', 'queue', 'steer', null] as const) {
        const ordinary = renderSubmitHook({ busy: true, busyInputMode: mode, scopeTarget, text: 'change course' })
        act(() => ordinary.hook.result.current.submitDraft())

        if (mode === 'queue') {
          expect(ordinary.queueCurrentDraft).toHaveBeenCalledOnce()
          expect(ordinary.onSteer).not.toHaveBeenCalled()
        } else if (mode === null) {
          expect(ordinary.clearDraft).not.toHaveBeenCalled()
          expect(ordinary.onSteer).not.toHaveBeenCalled()
          expect(ordinary.queueCurrentDraft).not.toHaveBeenCalled()
        } else {
          await waitFor(() => expect(ordinary.onSteer).toHaveBeenCalledWith('change course', mode))
          expect(ordinary.queueCurrentDraft).not.toHaveBeenCalled()
        }

        ordinary.hook.unmount()
        const explicit = renderSubmitHook({ busy: true, busyInputMode: mode, scopeTarget, text: 'explicit guidance' })
        act(() => explicit.hook.result.current.steerDraft('steer'))
        await waitFor(() => expect(explicit.onSteer).toHaveBeenCalledWith('explicit guidance', 'steer'))
        act(() => explicit.hook.result.current.queueDraft())
        expect(explicit.queueCurrentDraft).toHaveBeenCalledOnce()
        explicit.hook.unmount()
      }
    }
  })

  afterEach(() => {
    cleanup()
    vi.restoreAllMocks()
    clearComposerTerminalSelections()
  })

  it('treats a payload mid-turn as send (steer), not stop', async () => {
    const { hook, onCancel, onSteer, onSubmit, queueCurrentDraft } = renderSubmitHook({
      busy: true,
      text: 'change course'
    })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course', 'interrupt'))
    expect(queueCurrentDraft).not.toHaveBeenCalled()
    expect(onCancel).not.toHaveBeenCalled()
    expect(onSubmit).not.toHaveBeenCalled()
  })

  it('puts a refused steer back in the composer when there is no queue to hold it', async () => {
    // A brand-new chat is busy while its first session.create is in flight but
    // has no queue key yet. The steer clears the draft first, so a refusal must
    // restore the words rather than drop the only copy (#68927).
    const { hook, loadIntoComposer, onSteer } = renderSubmitHook({ busy: true, sessionKey: null, text: 'keep me' })
    onSteer.mockResolvedValueOnce(false)

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() => expect(loadIntoComposer).toHaveBeenCalledWith('keep me', []))
  })

  it('queues a steer whose redirect RPC fails instead of losing it', async () => {
    const { hook, onSteer } = renderSubmitHook({ busy: true, text: 'still here' })
    onSteer.mockRejectedValueOnce(new Error('request timed out: session.redirect'))

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() => expect(getQueuedPrompts('stored-session').map(({ text }) => text)).toEqual(['still here']))
    clearQueuedPrompts('stored-session')
  })

  it('runs slash commands immediately while busy', async () => {
    const { clearDraft, hook, onCancel, onSteer, onSubmit, queueCurrentDraft } = renderSubmitHook({
      busy: true,
      text: '/compress preserve context'
    })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() =>
      expect(onSubmit).toHaveBeenCalledWith('/compress preserve context', {
        submission_id: expect.any(String),
        composerScope: 'stored-session'
      })
    )
    expect(clearDraft).toHaveBeenCalledTimes(1)
    expect(onSteer).not.toHaveBeenCalled()
    expect(queueCurrentDraft).not.toHaveBeenCalled()
    expect(onCancel).not.toHaveBeenCalled()
  })

  it('queues an attachment-bearing follow-up while busy', () => {
    const attachment: ComposerAttachment = { id: 'doc', kind: 'file', label: 'notes.txt' }

    const { hook, onCancel, onSteer, onSubmit, queueCurrentDraft } = renderSubmitHook({
      attachments: [attachment],
      busy: true,
      text: 'read this'
    })

    act(() => {
      hook.result.current.submitDraft()
    })

    expect(queueCurrentDraft).toHaveBeenCalledTimes(1)
    expect(onSteer).not.toHaveBeenCalled()
    expect(onSubmit).not.toHaveBeenCalled()
    expect(onCancel).not.toHaveBeenCalled()
  })

  it('stops an active turn only with an empty composer', () => {
    const { hook, onCancel, onSteer, onSubmit, queueCurrentDraft } = renderSubmitHook({ busy: true })

    act(() => {
      hook.result.current.submitDraft()
    })

    expect(onCancel).toHaveBeenCalledTimes(1)
    expect(onSteer).not.toHaveBeenCalled()
    expect(onSubmit).not.toHaveBeenCalled()
    expect(queueCurrentDraft).not.toHaveBeenCalled()
  })

  it('submits a normal turn while idle', async () => {
    const { hook, onCancel, onSteer, onSubmit, queueCurrentDraft } = renderSubmitHook({ text: 'ordinary question' })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() =>
      expect(onSubmit).toHaveBeenCalledWith('ordinary question', {
        submission_id: expect.any(String),
        attachments: [],
        composerScope: 'stored-session'
      })
    )
    expect(onSteer).not.toHaveBeenCalled()
    expect(queueCurrentDraft).not.toHaveBeenCalled()
    expect(onCancel).not.toHaveBeenCalled()
  })

  it('threads the loaded composer scope through onSubmit for the #59305 submit-time guard', async () => {
    const { hook, onSubmit } = renderSubmitHook({ text: 'hello' })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() =>
      expect(onSubmit).toHaveBeenCalledWith('hello', expect.objectContaining({ composerScope: 'stored-session' }))
    )
  })

  it('leaves idle @terminal chips for the submit transport freeze (does not expand here)', async () => {
    setComposerTerminalSelection('zsh:23-58', 'selected terminal lines')

    const { hook, onSteer, onSubmit, queueCurrentDraft } = renderSubmitHook({
      text: 'look at @terminal:`zsh:23-58`'
    })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() =>
      expect(onSubmit).toHaveBeenCalledWith('look at @terminal:`zsh:23-58`', {
        submission_id: expect.any(String),
        attachments: [],
        composerScope: 'stored-session'
      })
    )
    expect(onSteer).not.toHaveBeenCalled()
    expect(queueCurrentDraft).not.toHaveBeenCalled()
  })

  it('expands @terminal selection chips before steering a busy turn', async () => {
    setComposerTerminalSelection('zsh:23-58', 'selected terminal lines')

    const { hook, onSteer, queueCurrentDraft } = renderSubmitHook({
      busy: true,
      text: 'look at @terminal:`zsh:23-58`'
    })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() =>
      expect(onSteer).toHaveBeenCalledWith('```terminal\nselected terminal lines\n```\n\nlook at', 'interrupt')
    )
    expect(queueCurrentDraft).not.toHaveBeenCalled()
  })

  it('refuses to steer when a restored @terminal chip has no selection payload', () => {
    clearComposerTerminalSelections()

    const { hook, onSteer, queueCurrentDraft } = renderSubmitHook({
      busy: true,
      text: 'look at @terminal:`zsh:23-58`'
    })

    act(() => {
      hook.result.current.submitDraft()
    })

    expect(onSteer).not.toHaveBeenCalled()
    expect(queueCurrentDraft).not.toHaveBeenCalled()
  })
})

describe('useComposerSubmit keyboard after send', () => {
  beforeEach(() => {
    // Touch handling is the browser-hosted Desktop's.
    window.document.documentElement.dataset.hermesDesktopHost = 'browser'
  })

  afterEach(() => {
    cleanup()
    window.document.body.replaceChildren()
    delete window.document.documentElement.dataset.hermesDesktopHost
    vi.unstubAllGlobals()
  })

  // iOS raises the keyboard for a focus() inside the Send tap, covering the
  // reply just as it starts streaming.
  it.each([
    ['desktop', false, false, 1],
    ['touch with the keyboard up', true, true, 1],
    ['touch with the keyboard put away', true, false, 0]
  ])('refocuses the composer after a send on %s', async (_case, touch, editorFocused, focusCalls) => {
    vi.stubGlobal(
      'matchMedia',
      vi.fn().mockReturnValue({ addEventListener: vi.fn(), matches: touch, removeEventListener: vi.fn() })
    )
    const { editor, focusInput, hook, onSubmit } = renderSubmitHook({ text: 'hello' })
    editor.tabIndex = 0
    window.document.body.append(editor)

    if (editorFocused) {
      editor.focus()
    }

    await act(async () => hook.result.current.submitDraft())

    expect(onSubmit).toHaveBeenCalledOnce()
    expect(focusInput).toHaveBeenCalledTimes(focusCalls)
  })
})

describe('useComposerSubmit with a clarify parked on the session', () => {
  // The clarify is a live server→client request: skipping it answers that
  // request frame (`{}`), not a `clarify.respond` RPC.
  const respond = vi.fn()

  const parkClarify = (sessionId: string) => {
    const requestId = `req-${sessionId}`

    rememberServerRequest({ fail: vi.fn(), id: requestId, method: 'clarify', params: {}, respond })
    $clarifyRequests.set({
      [sessionId]: {
        requestId,
        questions: [{ choices: ['a', 'b'], multiSelect: false, qid: 'q0', question: 'which one?' }],
        sessionId
      }
    })
  }

  // SAFETY: the clarify lock path reads only `request` from the gateway.
  const setGateway = (request: ReturnType<typeof vi.fn>) => $gateway.set({ request } as never)

  afterEach(() => {
    cleanup()
    respond.mockClear()
    resetServerRequestsForTests()
    $clarifyRequests.set({})
    $gateway.set(null)
    vi.restoreAllMocks()
  })

  it.each([
    '/btw what is the task?',
    '/BTW what is the task?',
    '/btw',
    '/bg summarize the logs',
    '/background run the tests'
  ])('keeps a pending clarify answerable while dispatching %s', async text => {
    parkClarify('runtime-session')
    const { hook, onSubmit, onSteer } = renderSubmitHook({ busy: true, text })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(text, expect.anything()))
    expect(onSteer).not.toHaveBeenCalled()
    expect(respond).not.toHaveBeenCalled()
    expect(hasOpenServerRequest('req-runtime-session')).toBe(true)
    expect($clarifyRequests.get()['runtime-session']).toBeDefined()
  })

  it('still skips clarify for a different slash command', async () => {
    parkClarify('runtime-session')
    const { hook, onSubmit } = renderSubmitHook({ busy: true, text: '/status' })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() => expect(onSubmit).toHaveBeenCalledWith('/status', expect.anything()))
    expect(respond).toHaveBeenCalledWith({})
    expect(hasOpenServerRequest('req-runtime-session')).toBe(false)
  })

  it('answers the question with the typed text and does not send it on an idle session', async () => {
    parkClarify('runtime-session')
    const request = vi.fn(async () => ({ status: 'ok', remaining: [] }))
    setGateway(request)
    const { hook, onSubmit, onSteer } = renderSubmitHook({ text: 'actually do this instead' })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() =>
      expect(request).toHaveBeenCalledWith('clarify.lock', {
        answer: 'actually do this instead',
        question_id: 'q0',
        request_id: 'req-runtime-session'
      })
    )
    expect(onSubmit).not.toHaveBeenCalled()
    expect(onSteer).not.toHaveBeenCalled()
    expect(respond).not.toHaveBeenCalled()
    expect($clarifyRequests.get()['runtime-session']).toBeUndefined()
  })

  it('answers one question per submit while a busy turn waits, matching a choice label', async () => {
    const request = vi.fn(async () => ({ status: 'ok', remaining: ['q1'] }))
    setGateway(request)
    rememberServerRequest({ fail: vi.fn(), id: 'req-two', method: 'clarify', params: {}, respond })
    $clarifyRequests.set({
      'runtime-session': {
        requestId: 'req-two',
        questions: [
          { choices: ['Staging', 'Prod'], multiSelect: false, qid: 'q0', question: 'where?' },
          { choices: null, multiSelect: false, qid: 'q1', question: 'why?' }
        ],
        sessionId: 'runtime-session'
      }
    })
    const { hook, onSteer } = renderSubmitHook({ busy: true, text: 'prod' })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() =>
      expect(request).toHaveBeenCalledWith('clarify.lock', { answer: 'Prod', question_id: 'q0', request_id: 'req-two' })
    )
    expect(onSteer).not.toHaveBeenCalled()
    expect($clarifyRequests.get()['runtime-session']?.lockedAnswers).toEqual({ q0: 'Prod' })
    expect(hasOpenServerRequest('req-two')).toBe(true)
  })

  it('brings the card back when an earlier lock fails after the last answer cleared it', async () => {
    let failFirst: (error: Error) => void = () => {}

    const request = vi
      .fn()
      .mockImplementationOnce(() => new Promise((_resolve, reject) => (failFirst = reject)))
      .mockResolvedValue({ status: 'ok', remaining: [] })

    setGateway(request)
    rememberServerRequest({ fail: vi.fn(), id: 'req-pair', method: 'clarify', params: {}, respond })
    $clarifyRequests.set({
      'runtime-session': {
        requestId: 'req-pair',
        questions: ['q0', 'q1'].map(qid => ({ choices: null, multiSelect: false, qid, question: `${qid}?` })),
        sessionId: 'runtime-session'
      }
    })

    for (const text of ['first', 'second']) {
      const { hook } = renderSubmitHook({ busy: true, text })
      act(() => hook.result.current.submitDraft())
    }

    expect($clarifyRequests.get()['runtime-session']).toBeUndefined()
    await waitFor(() => expect(request).toHaveBeenCalledTimes(1))

    await act(async () => failFirst(new Error('socket closed')))

    await waitFor(() => expect($clarifyRequests.get()['runtime-session']?.lockedAnswers).toEqual({}))
    // The second answer waits on the first, so it never reaches the server without it.
    expect(request).toHaveBeenCalledTimes(1)
    expect(hasOpenServerRequest('req-pair')).toBe(true)
  })

  it('leaves the question alone for an empty Enter (Stop, not an answer)', () => {
    parkClarify('runtime-session')
    const { hook, onCancel } = renderSubmitHook({ busy: true })

    act(() => {
      hook.result.current.submitDraft()
    })

    expect(respond).not.toHaveBeenCalled()
    expect(hasOpenServerRequest('req-runtime-session')).toBe(true)
    expect($clarifyRequests.get()['runtime-session']).toBeDefined()
    expect(onCancel).toHaveBeenCalledTimes(1)
  })

  it("leaves another session's question alone", async () => {
    parkClarify('other-session')
    const { hook, onSubmit } = renderSubmitHook({ text: 'unrelated message' })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() => expect(onSubmit).toHaveBeenCalled())
    expect(respond).not.toHaveBeenCalled()
    expect(hasOpenServerRequest('req-other-session')).toBe(true)
    expect($clarifyRequests.get()['other-session']).toBeDefined()
  })
})

describe('useComposerSubmit with a connection card parked on the session', () => {
  afterEach(() => {
    cleanup()
    $connectionRequests.set({})
    $gateway.set(null)
    vi.restoreAllMocks()
  })

  const parkConnection = () => {
    const connection: ConnectionRequest = {
      toolCallId: 'call-connection',
      opId: 'op-connection',
      seq: 1,
      deadlineAt: 1_800_000_000,
      sessionId: 'runtime-session',
      targets: [
        {
          name: 'gmail',
          kind: 'connector',
          action: 'connect',
          state: 'pending',
          detail: '',
          connectUrl: null,
          connectionId: '',
          tools: [],
          requiredEnv: [],
          instructions: null,
          discoveryError: null
        }
      ],
      settled: false,
      settledBy: null
    }

    $connectionRequests.set({ 'runtime-session': connection })
  }

  it.each([
    '/btw what is the task?',
    '/BTW what is the task?',
    '/btw',
    '/bg summarize the logs',
    '/background run the tests'
  ])('keeps the connection card answerable while dispatching %s', async text => {
    parkConnection()
    vi.spyOn(sessionOwnerUtils, 'resolveSessionOwner').mockRejectedValue(new Error('test no owner'))
    const gatewayRequest = vi.fn(async () => ({}))
    $gateway.set({ request: gatewayRequest } as unknown as NonNullable<ReturnType<typeof $gateway.get>>)
    const { hook, onSubmit, onSteer } = renderSubmitHook({ busy: true, text })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(text, expect.anything()))
    expect(onSteer).not.toHaveBeenCalled()
    expect(gatewayRequest).not.toHaveBeenCalledWith('connection.respond', expect.anything())
    expect($connectionRequests.get()['runtime-session']?.settled).toBe(false)
  })

  it('still continues the connection request for an ordinary reply', async () => {
    parkConnection()
    vi.spyOn(sessionOwnerUtils, 'resolveSessionOwner').mockRejectedValue(new Error('test no owner'))
    const gatewayRequest = vi.fn(async () => ({}))
    $gateway.set({ request: gatewayRequest } as unknown as NonNullable<ReturnType<typeof $gateway.get>>)
    const { hook, onSteer } = renderSubmitHook({ busy: true, text: 'continue without connecting' })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() => expect(onSteer).toHaveBeenCalledWith('continue without connecting', 'interrupt'))
    await waitFor(() =>
      expect(gatewayRequest).toHaveBeenCalledWith(
        'connection.respond',
        expect.objectContaining({
          op_id: 'op-connection',
          result: { settled_by: 'continue' }
        })
      )
    )
  })
})

describe('useComposerSubmit with a blocking prompt parked on the session', () => {
  // Typing cannot answer approval/sudo/secret prompts, so the busy submit must
  // route text to the QUEUE — a steer would sit undelivered behind the blocked
  // tool batch, and interrupting to force it through resolves the prompt empty
  // and ends the turn as "Operation interrupted." with the message lost.
  afterEach(() => {
    cleanup()
    clearAllPrompts()
    vi.restoreAllMocks()
  })

  it('queues a busy text follow-up instead of steering while an approval is pending', () => {
    setApprovalRequest({ command: 'rm -rf /tmp/x', description: 'dangerous', sessionId: 'runtime-session' })

    const { hook, onCancel, onSteer, queueCurrentDraft } = renderSubmitHook({
      busy: true,
      text: 'and also fix the padding'
    })

    act(() => {
      hook.result.current.submitDraft()
    })

    expect(queueCurrentDraft).toHaveBeenCalledTimes(1)
    expect(onSteer).not.toHaveBeenCalled()
    expect(onCancel).not.toHaveBeenCalled()
  })

  it('queues while a sudo prompt is pending', () => {
    setSudoRequest({ requestId: 'sudo-1', sessionId: 'runtime-session' })

    const { hook, onSteer, queueCurrentDraft } = renderSubmitHook({ busy: true, text: 'next thing' })

    act(() => {
      hook.result.current.submitDraft()
    })

    expect(queueCurrentDraft).toHaveBeenCalledTimes(1)
    expect(onSteer).not.toHaveBeenCalled()
  })

  it('queues while a secret prompt is pending', () => {
    setSecretRequest({ envVar: 'API_KEY', prompt: 'key?', requestId: 'sec-1', sessionId: 'runtime-session' })

    const { hook, onSteer, queueCurrentDraft } = renderSubmitHook({ busy: true, text: 'next thing' })

    act(() => {
      hook.result.current.submitDraft()
    })

    expect(queueCurrentDraft).toHaveBeenCalledTimes(1)
    expect(onSteer).not.toHaveBeenCalled()
  })

  it('still runs slash commands inline', async () => {
    setApprovalRequest({ command: 'rm -rf /tmp/x', description: 'dangerous', sessionId: 'runtime-session' })

    const { hook, onSteer, onSubmit, queueCurrentDraft } = renderSubmitHook({ busy: true, text: '/status' })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() =>
      expect(onSubmit).toHaveBeenCalledWith('/status', {
        submission_id: expect.any(String),
        composerScope: 'stored-session'
      })
    )
    expect(queueCurrentDraft).not.toHaveBeenCalled()
    expect(onSteer).not.toHaveBeenCalled()
  })

  it("ignores another session's blocking prompt and still steers", async () => {
    setApprovalRequest({ command: 'ls', description: 'other', sessionId: 'other-session' })

    const { hook, onSteer, queueCurrentDraft } = renderSubmitHook({ busy: true, text: 'change course' })

    act(() => {
      hook.result.current.submitDraft()
    })

    await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course', 'interrupt'))
    expect(queueCurrentDraft).not.toHaveBeenCalled()
  })

  it('leaves the prompt pending — queueing must not resolve or dismiss it', () => {
    setApprovalRequest({ command: 'rm -rf /tmp/x', description: 'dangerous', sessionId: 'runtime-session' })

    const { hook } = renderSubmitHook({ busy: true, text: 'follow-up' })

    act(() => {
      hook.result.current.submitDraft()
    })

    // The approval card is still the turn's owner; only its own buttons answer it.
    expect(hasBlockingPromptRequest('runtime-session')).toBe(true)
  })
})

describe('useComposerSubmit with a setup card waiting in the onboarding chat', () => {
  // The card is a live setup_beat server request; its answer is that request's response frame.
  const parkCard = (beat: 'layout' | 'name') => {
    const respond = vi.fn()

    rememberServerRequest({ fail: vi.fn(), id: `srq-${beat}`, method: 'setup_beat', params: {}, respond })
    parkSetupBeat({
      beat,
      card: {},
      question: 'Which layout?',
      requestId: `srq-${beat}`,
      sessionId: 'runtime-session',
      toolCallId: `call-${beat}`
    })

    return respond
  }

  afterEach(() => {
    cleanup()
    resetServerRequestsForTests()
    $setupBeatRequests.set({})
    $onboardingSession.set(null)
    $onboardingPhase.set('idle')
  })

  it('closes the card unanswered and sends the words as the next turn, never into the card turn', () => {
    $onboardingPhase.set('shown')
    $onboardingSession.set({
      connectionId: null,
      runId: 'run-1',
      runtimeId: 'runtime-session',
      storedId: 'stored-session'
    })
    const respond = parkCard('layout')

    const { hook, onSteer, onSubmit, queueCurrentDraft } = renderSubmitHook({
      busy: true,
      text: 'can ya look around and take a wild guess which one id like? :D'
    })

    act(() => {
      hook.result.current.submitDraft()
    })

    expect(respond).toHaveBeenCalledWith({ wrote_instead: true })
    expect($setupBeatRequests.get()['runtime-session']).toBeUndefined()
    // The backend ends the card turn on that result; the queued message runs as the next user turn.
    expect(queueCurrentDraft).toHaveBeenCalledTimes(1)
    expect(onSteer).not.toHaveBeenCalled()
    expect(onSubmit).not.toHaveBeenCalled()
  })

  it('takes words typed on the name card as the name, and sends no message', () => {
    $onboardingPhase.set('shown')
    $onboardingSession.set({
      connectionId: null,
      runId: 'run-1',
      runtimeId: 'runtime-session',
      storedId: 'stored-session'
    })
    const respond = parkCard('name')

    const { clearDraft, hook, onSteer, onSubmit, queueCurrentDraft } = renderSubmitHook({ busy: true, text: 'Sid' })

    act(() => {
      hook.result.current.submitDraft()
    })

    expect(respond).toHaveBeenCalledWith({ said: 'Sid' })
    expect(clearDraft).toHaveBeenCalledTimes(1)
    expect(queueCurrentDraft).not.toHaveBeenCalled()
    expect(onSteer).not.toHaveBeenCalled()
    expect(onSubmit).not.toHaveBeenCalled()
  })

  it('runs no slash command while setup is in progress: the words stay and a note says why', () => {
    $onboardingPhase.set('shown')
    $onboardingSession.set({
      connectionId: null,
      runId: 'run-1',
      runtimeId: 'runtime-session',
      storedId: 'stored-session'
    })
    $notifications.set([])
    const respond = parkCard('name')

    for (const busy of [false, true]) {
      const { clearDraft, hook, onSubmit, queueCurrentDraft } = renderSubmitHook({ busy, text: '/help' })

      act(() => hook.result.current.submitDraft())

      expect(onSubmit).not.toHaveBeenCalled()
      expect(queueCurrentDraft).not.toHaveBeenCalled()
      expect(clearDraft).not.toHaveBeenCalled()
      cleanup()
    }

    expect(respond).not.toHaveBeenCalled()
    // One note, however often Enter is pressed.
    expect($notifications.get().map(note => note.kind)).toEqual(['info'])
  })

  it('queues no slash command while setup is in progress (Cmd/Ctrl+Enter)', () => {
    $onboardingPhase.set('shown')
    $onboardingSession.set({
      connectionId: null,
      runId: 'run-1',
      runtimeId: 'runtime-session',
      storedId: 'stored-session'
    })

    const { clearDraft, hook, onSubmit, queueCurrentDraft } = renderSubmitHook({ busy: true, text: '/help' })

    act(() => hook.result.current.queueDraft())

    expect(queueCurrentDraft).not.toHaveBeenCalled()
    expect(onSubmit).not.toHaveBeenCalled()
    expect(clearDraft).not.toHaveBeenCalled()
  })

  it('runs slash commands as usual in the same chat once setup has ended', () => {
    $onboardingPhase.set('done')
    $onboardingSession.set({
      connectionId: null,
      runId: 'run-1',
      runtimeId: 'runtime-session',
      storedId: 'stored-session'
    })

    const { hook, onSubmit } = renderSubmitHook({ text: '/help' })

    act(() => hook.result.current.submitDraft())

    expect(onSubmit).toHaveBeenCalledWith('/help', expect.anything())
  })
})

describe('useComposerSubmit on an insecure origin (plain-HTTP LAN: no crypto.randomUUID)', () => {
  const V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/

  beforeEach(() => vi.stubGlobal('crypto', { getRandomValues: crypto.getRandomValues.bind(crypto) }))

  afterEach(() => {
    cleanup()
    vi.unstubAllGlobals()
  })

  it('sends a fresh draft with a v4 submission_id', async () => {
    const { hook, onSubmit } = renderSubmitHook({ text: 'hello from the LAN' })

    act(() => hook.result.current.submitDraft())
    await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
    expect(onSubmit.mock.calls[0]).toEqual([
      'hello from the LAN',
      expect.objectContaining({ submission_id: expect.stringMatching(V4) })
    ])
  })

  it('puts the draft back when preparing the send throws', async () => {
    const attachment = { id: 'file-1', kind: 'file', label: 'notes.txt', path: '/work/notes.txt' } as ComposerAttachment

    const { clearDraft, hook, loadIntoComposer, onSubmit, stashAt } = renderSubmitHook({
      attachments: [attachment],
      text: 'keep these words'
    })

    onSubmit.mockImplementation(() => {
      throw new TypeError('preparation failed')
    })

    act(() => hook.result.current.submitDraft())
    expect(clearDraft).toHaveBeenCalledTimes(1)
    await waitFor(() => expect(loadIntoComposer).toHaveBeenCalledWith('keep these words', [attachment]))
    expect(stashAt).toHaveBeenCalledWith('stored-session', 'keep these words', [attachment])
  })
})