Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript
86.6 KB
Raw Blame
// @vitest-environment jsdom
/**
 * ⚠️ CHARACTERIZATION TESTS — D.0.
 *
 * These tests capture the OBSERVABLE behavior of `useAgentChatController`
 * PRE-D.3. Do NOT modify them when refactoring in D.3 — only adapt the setup
 * (e.g. wrap with AgentTaskTrackerProvider). If an assertion stops passing
 * after D.3, that means the refactor changed user-visible behavior and must be
 * discussed before merging.
 *
 * Plan: .specs/feat-feedback-fire-forget-comeback/implementation-plans/D0-characterization-tests.md
 */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { makeTaskKey } from '@contexts/AgentTaskTrackerContext/types'
import { act, cleanup, waitFor as rtlWaitFor } from '@testing-library/react'
import { classifyBytes } from '@clerum/gfs-interaction-policy'
import { base64Length, composerNonImageShareBytes } from '@lib/composerFileAdmission'
import { buildComposerFileReferences } from '@lib/composerFileReferences'
import { buildComposerRequestContent } from '@lib/composerReferencesPrompt'
import { loadHostModels, resetHostModelSelectionStore } from '@lib/hostModelSelectionStore'
import type { HostModelsResult } from '../../../../../src/types'
import type {
  ComposerGlobalFileReference,
  ComposerImageAttachment,
  ReadyComposerFileAttachment,
} from '../../../uiTypes'
import { renderController } from './__fixtures__/controllerHarness'
import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'

let clerum: MockClerum
let uuidCounter = 0
const ASYNC_WAIT_TIMEOUT_MS = 5_000

// React 18/19 needs this flag for act() to flush effects in the test env.
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true

beforeEach(() => {
  uuidCounter = 0
  // Deterministic UUIDs so userMessageId / chatId are stable across asserts.
  vi.spyOn(globalThis.crypto, 'randomUUID').mockImplementation(
    () => `uuid-${++uuidCounter}` as `${string}-${string}-${string}-${string}-${string}`
  )
  clerum = installMockClerum()
})

afterEach(() => {
  cleanup()
  vi.restoreAllMocks()
  vi.useRealTimers()
  uninstallMockClerum()
  expect(document.body.childElementCount).toBe(0)
})

/** Wait until the controller's mount effect (loadChatList) has settled. */
async function settleMount() {
  await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())
}

/** Real ChatStore-backed effects can exceed Testing Library's 1s default on CI runners. */
function waitFor<T>(callback: () => T | Promise<T>, options?: Parameters<typeof rtlWaitFor>[1]) {
  return rtlWaitFor(callback, { timeout: ASYNC_WAIT_TIMEOUT_MS, ...options })
}

function deferred<T>() {
  let resolve!: (value: T) => void
  let reject!: (reason?: unknown) => void
  const promise = new Promise<T>((resolvePromise, rejectPromise) => {
    resolve = resolvePromise
    reject = rejectPromise
  })
  return { promise, resolve, reject }
}

// A send writes the user turn to the real ChatStore (disk I/O) before it wires
// the progress subscription. On a loaded CI runner that write can take longer
// than the 1000 ms waitFor default (#958), so the wiring waits get this bound.
const WIRING_TIMEOUT_MS = 10_000
// Captured at module load, before any test installs fake timers.
const realSetTimeout = globalThis.setTimeout

async function waitForProgressHandler(taskId: string) {
  await waitFor(() => expect(clerum.hasProgressHandler(taskId)).toBe(true), {
    timeout: WIRING_TIMEOUT_MS,
  })
}

/**
 * Fake-timer variant. `vi.waitFor` advances the fake clock by its interval on
 * every check, which would move it toward the watchdog and connection timeouts
 * the test advances to explicitly. This polls in real time and only runs the
 * timers that are already due, so the fake clock does not move.
 */
async function waitForProgressHandlerUnderFakeTimers(taskId: string) {
  const intervalMs = 50
  for (let waitedMs = 0; waitedMs < WIRING_TIMEOUT_MS; waitedMs += intervalMs) {
    await vi.advanceTimersByTimeAsync(0)
    if (clerum.hasProgressHandler(taskId)) return
    await new Promise(resolve => realSetTimeout(resolve, intervalMs))
  }
  expect(clerum.hasProgressHandler(taskId)).toBe(true)
}

function waitForWithFakeTimers<T>(assertion: () => T | Promise<T>) {
  return vi.waitFor(assertion, { timeout: WIRING_TIMEOUT_MS })
}

describe('useAgentChatController — characterization (D.0)', () => {
  describe('switchToChat', () => {
    // ⚠️ Rewritten for D.4 (plan §5.3): the pre-D.4 `isRemote` dual-path was
    // replaced by a single cache-first → server-reconcile → tracker-rejoin path,
    // so these now characterize the UNIFIED switchToChat. The behavior change is
    // the documented D.4 decision, not a silent regression.
    it('4.1 renders the local cache then reconciles with the server (idle → no rejoin)', async () => {
      clerum.chat.loadMessages.mockResolvedValue([
        { id: 'm1', role: 'user', content: 'hi', timestamp: 1 },
        { id: 'm2', role: 'assistant', content: 'hello', timestamp: 2 },
        { id: 'm3', role: 'user', content: 'again', timestamp: 3 },
      ])
      // Server reconcile returns no extra turns and an idle session.
      clerum.rpc.loadSessionMessages.mockResolvedValue({
        agent: 'agent-x',
        chatId: 'chat-1',
        state: 'idle',
        turns: [],
      })
      const { result } = renderController()
      await settleMount()

      await act(async () => {
        await result.current.switchToChat('agent-x', 'chat-1')
      })

      expect(clerum.chat.setLastActive).toHaveBeenCalledWith('agent-x', 'chat-1')
      // Phase 2 now always reconciles with the server.
      expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(
        'agent-x',
        'agent-x',
        'chat-1',
        undefined,
        { limit: 40 }
      )
      // Cache was up to date → no overwrite, no rejoin.
      expect(clerum.chat.replaceMessages).not.toHaveBeenCalled()
      expect(result.current.chatMessages).toHaveLength(3)
      expect(result.current.activeChatId).toBe('chat-1')
    })

    it('preserves cached history when the same chat is reopened during setLastActive', async () => {
      await clerum.chat.create('agent-x', 'chat-a')
      await clerum.chat.upsertMessages('agent-x', 'chat-a', [
        { id: 'local-turn', role: 'user', content: 'saved locally', timestamp: 1 },
      ])

      const firstSetLastActive = deferred<void>()
      const setLastActive = clerum.chat.setLastActive.getMockImplementation()
      if (!setLastActive) throw new Error('Expected the setLastActive test mock implementation')
      let holdFirstCall = true
      clerum.chat.setLastActive.mockImplementation(async (agentRef, chatId) => {
        if (agentRef === 'agent-x' && chatId === 'chat-a' && holdFirstCall) {
          holdFirstCall = false
          await firstSetLastActive.promise
        }
        await setLastActive(agentRef, chatId)
      })
      clerum.rpc.loadSessionMessages.mockRejectedValue(new Error('offline'))

      const { result } = renderController()
      await settleMount()
      await waitFor(() => expect(result.current.chatListLoading).toBe(false))

      let initialSelection!: Promise<void>
      await act(async () => {
        initialSelection = result.current.switchToChat('agent-x', 'chat-a')
        await Promise.resolve()
      })
      await waitFor(() =>
        expect(clerum.chat.setLastActive).toHaveBeenCalledWith('agent-x', 'chat-a')
      )
      expect(result.current.activeChatId).toBe('chat-a')
      expect(result.current.chatMessagesLoading).toBe(true)

      await act(async () => {
        await result.current.switchToChat('agent-x', 'chat-a')
      })

      await act(async () => {
        firstSetLastActive.resolve()
        await initialSelection
      })

      expect(result.current.activeChatId).toBe('chat-a')
      expect(result.current.chatMessages).toEqual([
        expect.objectContaining({ id: 'local-turn', content: 'saved locally' }),
      ])
    })

    it('4.2 hydrates a server-only chat (created on another device) and persists via replace', async () => {
      clerum.chat.loadMessages.mockResolvedValue([]) // nothing cached locally
      clerum.rpc.loadSessionMessages.mockResolvedValue({
        agent: 'agent-x',
        chatId: 'chat-2',
        state: 'idle',
        turns: [
          {
            number: 1,
            user_input: 'remote question',
            response: 'remote answer',
            started_at: '2026-05-28T10:00:00Z',
            completed_at: '2026-05-28T10:00:05Z',
          },
        ],
      })
      const { result } = renderController()
      await settleMount()

      await act(async () => {
        await result.current.switchToChat('agent-x', 'chat-2')
      })

      expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(
        'agent-x',
        'agent-x',
        'chat-2',
        undefined,
        { limit: 40 }
      )
      expect(clerum.chat.create).toHaveBeenCalledWith('agent-x', 'chat-2')
      // Server is source of truth → replace, not append (nor upsert, which the
      // real store keeps apart from append).
      expect(clerum.chat.replaceMessages).toHaveBeenCalled()
      expect(clerum.chat.appendMessages).not.toHaveBeenCalled()
      expect(clerum.chat.upsertMessages).not.toHaveBeenCalled()
      // spec 15 §2.2/A19: the first-turn auto-title is shown EPHEMERALLY in the
      // sidebar (observable output, T4) but is NOT persisted via rename — the
      // server title is authoritative and a persisted client-derived title would
      // linger as a stale case-D fallback.
      expect(clerum.chat.rename).not.toHaveBeenCalled()
      expect(result.current.chatList.find(c => c.id === 'chat-2')?.title).toBe('remote question')
      expect(result.current.chatMessages).toHaveLength(2)
      expect(result.current.activeChatId).toBe('chat-2')
    })

    it('opens a remote chat at the bottom after its empty cache hydrates', async () => {
      vi.useFakeTimers()
      const hydration = deferred<{
        agent: string
        chatId: string
        state: 'idle'
        turns: Array<{
          number: number
          user_input: string
          response: string
          started_at: string
          completed_at: string
        }>
      }>()
      clerum.chat.loadMessages.mockResolvedValue([])
      clerum.rpc.loadSessionMessages.mockReturnValue(hydration.promise)

      const { result } = renderController()
      await act(async () => {
        await vi.advanceTimersByTimeAsync(0)
      })

      const scrollContainer = document.createElement('div')
      const anchor = document.createElement('div')
      let scrollTop = 0
      Object.defineProperties(scrollContainer, {
        clientHeight: { configurable: true, value: 100 },
        scrollHeight: { configurable: true, value: 800 },
        scrollTop: {
          configurable: true,
          get: () => scrollTop,
          set: (value: number) => {
            scrollTop = value
          },
        },
      })
      Object.defineProperty(anchor, 'scrollIntoView', { configurable: true, value: vi.fn() })
      scrollContainer.append(anchor)
      document.body.append(scrollContainer)
      result.current.chatEndRef.current = anchor

      let switching!: Promise<void>
      await act(async () => {
        switching = result.current.switchToChat('agent-x', 'chat-remote')
        await vi.advanceTimersByTimeAsync(200)
      })
      expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledTimes(1)

      // The initial cache scroll ran while the cache was empty. Model a reader
      // at the top when the remote transcript subsequently renders.
      scrollTop = 0
      await act(async () => {
        hydration.resolve({
          agent: 'agent-x',
          chatId: 'chat-remote',
          state: 'idle',
          turns: [
            {
              number: 1,
              user_input: 'remote question',
              response: 'remote answer',
              started_at: '2026-05-28T10:00:00Z',
              completed_at: '2026-05-28T10:00:05Z',
            },
          ],
        })
        await switching
      })
      await act(async () => {
        await vi.advanceTimersByTimeAsync(100)
      })

      expect(scrollTop).toBe(800)
      scrollContainer.remove()
    })

    it('stops delta pagination when the active chat changes during the first page', async () => {
      clerum.chat.loadMessages.mockImplementation(async (_agentRef: string, chatId: string) =>
        chatId === 'chat-a'
          ? [
              {
                id: 'turn-1-user',
                role: 'user',
                content: 'cached',
                timestamp: 1,
                serverTurnNumber: 1,
              },
            ]
          : []
      )
      const firstPage = deferred<{
        agent: string
        chatId: string
        turns: Array<{ number: number; user_input: string }>
        latestTurnNumber: number
        hasMoreAfter: boolean
      }>()
      let chatACalls = 0
      clerum.rpc.loadSessionMessages.mockImplementation(
        async (_hostRef: string, _agentRef: string, chatId: string) => {
          if (chatId !== 'chat-a') return { agent: 'agent-x', chatId, turns: [] }
          chatACalls += 1
          if (chatACalls === 1) return firstPage.promise
          return {
            agent: 'agent-x',
            chatId,
            turns: [{ number: 3, user_input: 'stale page' }],
            latestTurnNumber: 3,
            hasMoreAfter: false,
          }
        }
      )
      const { result } = renderController()
      await settleMount()

      let staleSwitch!: Promise<void>
      await act(async () => {
        staleSwitch = result.current.switchToChat('agent-x', 'chat-a')
        await Promise.resolve()
      })
      await waitFor(() => expect(chatACalls).toBe(1))
      await act(async () => {
        await result.current.switchToChat('agent-x', 'chat-b')
      })
      await act(async () => {
        firstPage.resolve({
          agent: 'agent-x',
          chatId: 'chat-a',
          turns: [{ number: 2, user_input: 'first delta' }],
          latestTurnNumber: 2,
          hasMoreAfter: true,
        })
        await staleSwitch
      })

      expect(chatACalls).toBe(1)
    })

    it('4.3 stays on the local cache and flags offline mode when the reconcile network-fails', async () => {
      clerum.chat.loadMessages.mockResolvedValue([])
      clerum.rpc.loadSessionMessages.mockRejectedValue(new Error('network unreachable'))
      const { result } = renderController()
      await settleMount()

      await act(async () => {
        await result.current.switchToChat('agent-x', 'chat-2')
      })

      // No crash; Phase 1 cache stays rendered, chat stays active (not evicted).
      expect(result.current.activeChatId).toBe('chat-2')
      expect(result.current.chatMessages).toEqual([])
      expect(clerum.chat.replaceMessages).not.toHaveBeenCalled()
      const key = 'agent-x::chat-2'
      expect(result.current.sessionStateByChatKey[key]).toMatchObject({
        syncing: false,
        offlineMode: true,
      })
    })
  })

  describe('sendAgentMessage', () => {
    it('4.4 completes a task end-to-end and persists the assistant reply', async () => {
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      clerum.rpc.getTaskResult.mockResolvedValue({ response: 'done!' })
      const { result, spies } = renderController()
      await settleMount()

      let sendResolved = false
      const sendPromise = result.current.handleSendAgentMessage('hola').then(() => {
        sendResolved = true
      })

      await waitForProgressHandler('task-abc')
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'open',
          taskId: 'task-abc',
          hostRef: 'agent-x',
        })
        clerum.emitTaskProgress('task-abc', {
          type: 'terminal',
          data: { taskId: 'task-abc', status: 'completed' },
        })
      })
      await act(async () => {
        await sendPromise
      })

      expect(sendResolved).toBe(true)
      // The user message is upserted before the POST and the assistant reply is
      // appended after the terminal; the store holds both, in order.
      const chatId = result.current.activeChatId!
      await waitFor(async () =>
        expect(
          (await clerum.persistedMessages('agent-x', chatId)).map(m => [m.role, m.content])
        ).toEqual([
          ['user', 'hola'],
          ['assistant', 'done!'],
        ])
      )
      expect(clerum.chat.appendMessages).toHaveBeenCalledTimes(1)
      expect(clerum.rpc.getTaskResult).toHaveBeenCalledWith('agent-x', 'task-abc', ['agent-x'])
      expect(spies.pushToast).toHaveBeenCalledWith('Message sent to agent-x.', 'success')
    })

    it('4.4b auto-creates a chat when none is active before invoking the host', async () => {
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      clerum.rpc.getTaskResult.mockResolvedValue({ response: 'ok' })
      const { result } = renderController()
      await settleMount()
      expect(result.current.activeChatId).toBeNull()

      const sendPromise = result.current.handleSendAgentMessage('first message')
      await waitForProgressHandler('task-abc')
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'terminal',
          data: { taskId: 'task-abc', status: 'completed' },
        })
      })
      await act(async () => {
        await sendPromise
      })

      expect(clerum.chat.create).toHaveBeenCalled()
      const createOrder = clerum.chat.create.mock.invocationCallOrder[0]!
      const invokeOrder = clerum.rpc.invokeHostMessage.mock.invocationCallOrder[0]!
      expect(createOrder).toBeLessThan(invokeOrder)
      expect(result.current.activeChatId).not.toBeNull()
    })

    it('4.4b-err aborts the send when chat creation fails', async () => {
      clerum.chat.create.mockRejectedValue(new Error('disk full'))
      const { result, spies } = renderController()
      await settleMount()

      await act(async () => {
        await result.current.handleSendAgentMessage('doomed message')
      })

      expect(clerum.rpc.invokeHostMessage).not.toHaveBeenCalled()
      expect(spies.pushToast).toHaveBeenCalledWith(
        expect.stringContaining('Could not create a chat session'),
        'error'
      )
      expect(result.current.agentSending).toBe(false)
    })

    it('4.4c rejects a concurrent send while one is in flight', async () => {
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      clerum.rpc.getTaskResult.mockResolvedValue({ response: 'ok' })
      const { result } = renderController()
      await settleMount()

      // First send — leave it in flight (no terminal emitted yet).
      const firstSend = result.current.handleSendAgentMessage('m1')
      await waitForProgressHandler('task-abc')

      // Second send while first is in flight — should be silently rejected.
      await act(async () => {
        await result.current.handleSendAgentMessage('m2')
      })
      expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1)

      // Clean up: terminate the first task.
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'terminal',
          data: { taskId: 'task-abc', status: 'completed' },
        })
      })
      await act(async () => {
        await firstSend
      })
    })

    it('4.5 surfaces a failed terminal as an error assistant message', async () => {
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      const { result, spies } = renderController()
      await settleMount()

      const sendPromise = result.current.handleSendAgentMessage('hola')
      await waitForProgressHandler('task-abc')
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'terminal',
          data: {
            taskId: 'task-abc',
            status: 'failed',
            error: { message: 'LLM down', code: 'provider_error', provider: 'anthropic' },
          },
        })
      })
      await act(async () => {
        await sendPromise
      })

      // The failure toast follows the store write of the error reply.
      await waitFor(() =>
        expect(spies.pushToast).toHaveBeenCalledWith('Message to agent-x failed: LLM down', 'error')
      )
      const appended = clerum.chat.appendMessages.mock.calls.at(-1)?.[2] as
        | Array<{ isError?: boolean; errorCode?: string }>
        | undefined
      expect(appended?.[0]?.isError).toBe(true)
      expect(appended?.[0]?.errorCode).toBe('provider_error')
    })

    it('does not toast or repaint a terminal error after its append crosses a team switch', async () => {
      const pendingAppend = deferred<void>()
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-old-team' })
      clerum.chat.appendMessages.mockImplementation(
        async (_agentRef: string, _chatId: string, messages: Array<{ role?: string }>) => {
          if (messages[0]?.role === 'assistant') await pendingAppend.promise
        }
      )
      const controller = renderController({ currentTeamId: 'team-before' })
      await settleMount()
      await act(async () => {
        await controller.result.current.handleSendAgentMessage('question')
      })
      await waitForProgressHandler('task-old-team')

      clerum.emitTaskProgress('task-old-team', {
        type: 'terminal',
        data: {
          taskId: 'task-old-team',
          status: 'failed',
          error: { message: 'protected old-team failure', code: 'provider_error' },
        },
      })
      await waitFor(() =>
        expect(
          clerum.chat.appendMessages.mock.calls.some(
            call => (call[2] as Array<{ role?: string }>)[0]?.role === 'assistant'
          )
        ).toBe(true)
      )
      controller.rerender({ currentTeamId: 'team-after' })
      const toastCount = controller.spies.pushToast.mock.calls.length
      const notificationCount = controller.spies.pushNotification.mock.calls.length
      const progressAfterSwitch = controller.result.current.progressByMessageId

      await act(async () => {
        pendingAppend.resolve()
        await pendingAppend.promise
      })
      expect(controller.spies.pushToast.mock.calls.length).toBe(toastCount)
      expect(controller.spies.pushNotification.mock.calls.length).toBe(notificationCount)
      expect(controller.result.current.progressByMessageId).toEqual(progressAfterSwitch)
    })

    it('4.6 marks the task cancelled without fetching a result', async () => {
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      const { result } = renderController()
      await settleMount()

      const sendPromise = result.current.handleSendAgentMessage('hola')
      await waitForProgressHandler('task-abc')
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'terminal',
          data: { taskId: 'task-abc', status: 'cancelled', reason: 'user_cancelled' },
        })
      })
      await act(async () => {
        await sendPromise
      })

      expect(clerum.rpc.getTaskResult).not.toHaveBeenCalled()
      const progress = result.current.progressByAgentMessage['agent-x']
      const entry = progress && Object.values(progress)[0]
      expect(entry?.status).toBe('cancelled')
    })

    it('4.7 surfaces a suspended approval and pushes an approval notification', async () => {
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      const { result, spies } = renderController()
      await settleMount()

      // Start the send bare (it stays in flight until terminal); read state
      // after the suspended event flushes, before resolving.
      const sendPromise = result.current.handleSendAgentMessage('hola').catch(() => undefined)
      await waitForProgressHandler('task-abc')
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'open',
          taskId: 'task-abc',
          hostRef: 'agent-x',
        })
        clerum.emitTaskProgress('task-abc', {
          type: 'suspended',
          data: {
            taskId: 'task-abc',
            requestId: 'req-1',
            displayName: 'Shell Execute',
            reason: 'approval',
          },
        })
      })

      await waitFor(() => {
        const progress = result.current.progressByAgentMessage['agent-x']
        const entry = progress && Object.values(progress)[0]
        expect(entry?.status).toBe('suspended')
      })
      const entry = Object.values(result.current.progressByAgentMessage['agent-x']!)[0]
      expect(entry?.suspendedInfo?.requestId).toBe('req-1')
      expect(spies.pushNotification).toHaveBeenCalledWith(
        expect.objectContaining({ kind: 'approval_required' })
      )

      // Clean up: resolve the suspended task with a terminal so the send promise settles.
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'terminal',
          data: { taskId: 'task-abc', status: 'cancelled', reason: 'cleanup' },
        })
      })
      await sendPromise
    })

    it('4.8 trips the 30s watchdog when no terminal arrives', async () => {
      vi.useFakeTimers()
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      // A genuinely stalled task has no durable per-task result, so the Fix B
      // durable-result fallback can't recover it and the watchdog error stands.
      clerum.rpc.getTaskResult.mockRejectedValue(new Error('404 not found'))
      const { result, spies } = renderController()
      // Flush mount effect (getIndex) under fake timers.
      await act(async () => {
        await vi.advanceTimersByTimeAsync(0)
      })

      let sendError: unknown = null
      const sendPromise = result.current.handleSendAgentMessage('hola').catch((e: unknown) => {
        sendError = e
      })

      // Flush the async send setup until the progress subscription is wired. The
      // send persists the user turn to the real ChatStore first, which is disk
      // I/O that fake timers do not advance: poll for the subscription instead.
      await act(async () => {
        await waitForProgressHandlerUnderFakeTimers('task-abc')
      })

      await act(async () => {
        // Open the stream, then go silent and advance past the 30s watchdog.
        // The idle check is strict (> 30_000) and fires on a 5s interval, so the
        // first tick that trips it lands at ~35s — advance 40s to be safe.
        clerum.emitTaskProgress('task-abc', {
          type: 'open',
          taskId: 'task-abc',
          hostRef: 'agent-x',
        })
        await vi.advanceTimersByTimeAsync(40_000)
      })
      await sendPromise

      // The failure toast follows the store write of the error reply.
      await act(async () => {
        await waitForWithFakeTimers(() =>
          expect(spies.pushToast).toHaveBeenCalledWith(expect.stringContaining('failed'), 'error')
        )
      })
      expect(result.current.agentSending).toBe(false)
      expect(sendError).toBeNull() // controller catches internally, does not reject
    })

    it('4.10 surfaces a result-fetch failure after a completed terminal (GAP-2)', async () => {
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      clerum.rpc.getTaskResult.mockRejectedValue(new Error('fetch failed'))
      const { result, spies } = renderController()
      await settleMount()

      const sendPromise = result.current.handleSendAgentMessage('hola').catch(() => undefined)
      await waitForProgressHandler('task-abc')
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'open',
          taskId: 'task-abc',
          hostRef: 'agent-x',
        })
        clerum.emitTaskProgress('task-abc', {
          type: 'terminal',
          data: { taskId: 'task-abc', status: 'completed' },
        })
      })
      await sendPromise

      const appended = clerum.chat.appendMessages.mock.calls.at(-1)?.[2] as
        | Array<{ isError?: boolean; content?: string }>
        | undefined
      expect(appended?.[0]?.isError).toBe(true)
      expect(appended?.[0]?.content).toContain('Failed to retrieve task result')
      // The failure toast follows the store write of the error reply.
      await waitFor(() =>
        expect(spies.pushToast).toHaveBeenCalledWith(
          expect.stringContaining('Failed to retrieve result'),
          'error'
        )
      )
    })

    it('4.9 trips the 5s connection timeout when the stream never opens', async () => {
      vi.useFakeTimers()
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      // No durable per-task result exists for a task whose stream never opened,
      // so the Fix B fallback can't recover it and the timeout error stands.
      clerum.rpc.getTaskResult.mockRejectedValue(new Error('404 not found'))
      const { result } = renderController()
      await act(async () => {
        await vi.advanceTimersByTimeAsync(0)
      })

      const sendPromise = result.current.handleSendAgentMessage('hola').catch(() => undefined)
      // The user turn is persisted to the real ChatStore (disk I/O fake timers do
      // not advance) before the subscription is wired: poll for it.
      await act(async () => {
        await waitForProgressHandlerUnderFakeTimers('task-abc')
      })

      await act(async () => {
        // Never emit 'open'. Advance past the 5s connection timeout.
        await vi.advanceTimersByTimeAsync(6_000)
      })
      await sendPromise

      // The timeout's recovery reads the store (disk I/O) before it settles the
      // entry as an error: poll for the settled state.
      await act(async () => {
        await waitForWithFakeTimers(() => {
          const progress = result.current.progressByAgentMessage['agent-x']
          const entry = progress && Object.values(progress)[0]
          expect(entry?.status).toBe('error')
        })
      })
    })

    // ── stream-recovery spec: a lost stream reconciles instead of failing ──

    it('SR-1 rejoins a still-running task on stream loss instead of failing', async () => {
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      clerum.rpc.loadSessionMessages.mockResolvedValue({
        agent: 'agent-x',
        chatId: 'c',
        turns: [],
        state: 'processing',
        activeTaskId: 'task-abc',
      })
      const { result, spies } = renderController()
      await settleMount()

      const sendPromise = result.current.handleSendAgentMessage('hola').catch(() => undefined)
      await waitForProgressHandler('task-abc')
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'open',
          taskId: 'task-abc',
          hostRef: 'agent-x',
        })
        clerum.emitTaskProgress('task-abc', {
          type: 'error',
          message: 'Progress stream disconnected',
        })
      })

      // The reconcile re-subscribes (rejoin) and surfaces no failure.
      await waitFor(() => expect(clerum.rpc.subscribeTaskProgress).toHaveBeenCalledTimes(2))
      expect(spies.pushToast).not.toHaveBeenCalledWith(expect.stringContaining('failed'), 'error')
      expect(result.current.failedAgentSend).toBeNull()

      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'terminal',
          data: { taskId: 'task-abc', status: 'cancelled', reason: 'cleanup' },
        })
      })
      await sendPromise
    })

    it('SR-2 renders the durable server reply on stream loss after completion', async () => {
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      clerum.rpc.loadSessionMessages.mockResolvedValue({
        agent: 'agent-x',
        chatId: 'c',
        turns: [
          {
            number: 1,
            user_input: 'hola',
            response: 'here is your report',
            started_at: new Date().toISOString(),
            completed_at: new Date().toISOString(),
          },
        ],
        state: 'idle',
      })
      const { result, spies } = renderController()
      await settleMount()

      const sendPromise = result.current.handleSendAgentMessage('hola').catch(() => undefined)
      await waitForProgressHandler('task-abc')
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'open',
          taskId: 'task-abc',
          hostRef: 'agent-x',
        })
        clerum.emitTaskProgress('task-abc', {
          type: 'error',
          message: 'Progress stream disconnected',
        })
      })

      // The durable reply is pulled from the server; no error/resend.
      await waitFor(() => expect(clerum.chat.replaceMessages).toHaveBeenCalled())
      expect(spies.pushToast).not.toHaveBeenCalledWith(expect.stringContaining('failed'), 'error')
      expect(result.current.failedAgentSend).toBeNull()
      await sendPromise
    })

    it('SR-3 re-establishes the approval gate on stream loss during awaiting_approval WITHOUT re-notifying (§4.7.3)', async () => {
      // Fase 5c (spec-v2 §4.7.3 / §8-R2): the stream-loss recovery now routes
      // through `reconcileChat` → `attachLiveTask`, whose `SERVER_SNAPSHOT`
      // (state awaiting_approval + pendingApproval + activeTaskId) settles the
      // badge, re-establishes the in-chat approve/deny affordance from the FSM
      // projection (`seedSuspended` is gone — §8-R2 optimistic paint), and
      // PRE-ARMS the (taskId,requestId) notification dedupe: "SERVER_SNAPSHOT
      // asienta estado/badge pero NO re-emite la notificación" (§4.7.3). The
      // rejoined SSE's replayed sticky `suspended` (V2) is the definitive gate.
      // Only a genuinely-live suspended (no prior snapshot) notifies. This
      // supersedes the old pin that re-notified.
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      clerum.rpc.loadSessionMessages.mockResolvedValue({
        agent: 'agent-x',
        chatId: 'c',
        turns: [],
        state: 'awaiting_approval',
        activeTaskId: 'task-abc',
        pendingApproval: { requestId: 'req-1', displayName: 'Run shell' },
      })
      const { result, spies } = renderController()
      await settleMount()

      const sendPromise = result.current.handleSendAgentMessage('hola').catch(() => undefined)
      await waitForProgressHandler('task-abc')
      const chatId = result.current.activeChatId!
      const key = makeTaskKey('agent-x', chatId)
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'open',
          taskId: 'task-abc',
          hostRef: 'agent-x',
        })
        clerum.emitTaskProgress('task-abc', { type: 'error', message: 'disconnected' })
      })

      // The reconcile rejoins (re-subscribes) and re-establishes the approval gate
      // from the snapshot: the badge is awaiting_approval and the in-chat
      // affordance (pendingApproval) is back — but no notification is re-emitted.
      await waitFor(() =>
        expect(result.current.sessionStateByChatKey[key]?.state).toBe('awaiting_approval')
      )
      expect(result.current.sessionStateByChatKey[key]?.pendingApproval).toMatchObject({
        requestId: 'req-1',
      })
      expect(clerum.rpc.subscribeTaskProgress).toHaveBeenCalledTimes(2)
      expect(spies.pushNotification).not.toHaveBeenCalledWith(
        expect.objectContaining({ kind: 'approval_required' })
      )
      expect(spies.pushToast).not.toHaveBeenCalledWith(expect.stringContaining('failed'), 'error')

      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'terminal',
          data: { taskId: 'task-abc', status: 'cancelled', reason: 'cleanup' },
        })
      })
      await sendPromise
    })

    it('SR-4 falls through to error + resend when the server has nothing recoverable', async () => {
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      // default loadSessionMessages → { turns: [] }, no state/activeTaskId.
      // A genuinely lost task has NO durable per-task result either (the Fix B
      // durable-result fallback must not recover it): make getTaskResult 404.
      clerum.rpc.getTaskResult.mockRejectedValue(new Error('404 not found'))
      const { result, spies } = renderController()
      await settleMount()

      const sendPromise = result.current.handleSendAgentMessage('hola').catch(() => undefined)
      await waitForProgressHandler('task-abc')
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'open',
          taskId: 'task-abc',
          hostRef: 'agent-x',
        })
        clerum.emitTaskProgress('task-abc', { type: 'error', message: 'disconnected' })
      })

      await waitFor(() =>
        expect(spies.pushToast).toHaveBeenCalledWith(expect.stringContaining('failed'), 'error')
      )
      expect(result.current.failedAgentSend).not.toBeNull()
      await sendPromise
    })

    it('SR-5 does not flash a Progress stream error before the reconcile lands', async () => {
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      // Defer the reconcile so we can observe the window between the stream error
      // and the durable reply landing — that's where the flash used to appear.
      let resolveLoad!: (value: unknown) => void
      clerum.rpc.loadSessionMessages.mockImplementation(
        () => new Promise(resolve => (resolveLoad = resolve))
      )
      const { result } = renderController()
      await settleMount()

      const sendPromise = result.current.handleSendAgentMessage('hola').catch(() => undefined)
      await waitForProgressHandler('task-abc')
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'open',
          taskId: 'task-abc',
          hostRef: 'agent-x',
        })
        clerum.emitTaskProgress('task-abc', {
          type: 'error',
          message: 'Progress stream disconnected',
        })
      })

      // The reconcile reads the local store (IPC; here the real ChatStore's disk
      // read) before it fetches the server turns, so wait for that fetch.
      await waitFor(() => expect(clerum.rpc.loadSessionMessages).toHaveBeenCalled())
      // The live subscription has fired for the `failed` state, but the reconcile
      // is still pending → no message may be painted as an error (no flash).
      const midProgress = result.current.progressByAgentMessage['agent-x'] ?? {}
      expect(Object.values(midProgress).some(p => p.status === 'error')).toBe(false)

      // Let the reconcile complete with the durable reply.
      await act(async () => {
        resolveLoad({
          agent: 'agent-x',
          chatId: 'c',
          state: 'idle',
          turns: [
            {
              number: 1,
              user_input: 'hola',
              response: 'done',
              started_at: new Date().toISOString(),
              completed_at: new Date().toISOString(),
            },
          ],
        })
        await Promise.resolve()
      })
      await waitFor(() => expect(clerum.chat.replaceMessages).toHaveBeenCalled())
      await sendPromise
    })

    it('SR-6 renders the durable reply after a rejoin whose stream also dies (no zombie block)', async () => {
      // Repro of bug-report Problema 2 through the `onTrackerTerminal` path: the
      // first stream loss reconciles to a STILL-running task → rejoin (re-adds a
      // tracker entry + re-subscribes). That rejoined stream also dies, but by
      // then the server has completed and persisted the durable reply. The reply
      // must render — a residual (zombie) tracker entry must not block the replace.
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      // Cache after send = the user message persisted with its task_id (1 msg).
      clerum.chat.loadMessages.mockResolvedValue([
        { id: 'turn-1-user', role: 'user', content: 'q1', timestamp: 1 },
      ])
      // First reconcile: task still processing → rejoin.
      clerum.rpc.loadSessionMessages.mockResolvedValueOnce({
        agent: 'agent-x',
        chatId: 'c',
        state: 'processing',
        activeTaskId: 'task-abc',
        turns: [{ number: 1, user_input: 'q1', started_at: new Date().toISOString() }],
      })
      const { result, spies } = renderController()
      await settleMount()

      const sendPromise = result.current.handleSendAgentMessage('q1').catch(() => undefined)
      await waitForProgressHandler('task-abc')

      // First stream loss → reconcile → rejoin (re-subscribes the SSE).
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'open',
          taskId: 'task-abc',
          hostRef: 'agent-x',
        })
        clerum.emitTaskProgress('task-abc', {
          type: 'error',
          message: 'Progress stream disconnected',
        })
      })
      await waitFor(() =>
        expect(
          clerum.rpc.subscribeTaskProgress.mock.calls.filter((c: unknown[]) => c[1] === 'task-abc')
        ).toHaveLength(2)
      )
      expect(clerum.chat.replaceMessages).not.toHaveBeenCalled()

      // Second reconcile (rejoined stream also dies): server now idle + completed.
      clerum.rpc.loadSessionMessages.mockResolvedValue({
        agent: 'agent-x',
        chatId: 'c',
        state: 'idle',
        turns: [
          {
            number: 1,
            user_input: 'q1',
            response: 'here is your report',
            started_at: new Date().toISOString(),
            completed_at: new Date().toISOString(),
          },
        ],
      })
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'error',
          message: 'Progress stream disconnected',
        })
      })

      // The durable reply lands in the reconciled transcript the controller writes
      // back with `replaceMessages`; no error/resend and no zombie block. (The old
      // wait on `appendMessages` was met by the user turn the fake store forwarded
      // there, never by the reply.)
      await waitFor(() =>
        expect(
          clerum.chat.replaceMessages.mock.calls.some(call =>
            (call[2] as Array<{ role?: string; content?: string }>).some(
              message => message.role === 'assistant' && message.content === 'here is your report'
            )
          )
        ).toBe(true)
      )
      expect(result.current.chatMessages).toContainEqual(
        expect.objectContaining({ role: 'assistant', content: 'here is your report' })
      )
      expect(spies.pushToast).not.toHaveBeenCalledWith(expect.stringContaining('failed'), 'error')
      expect(result.current.failedAgentSend).toBeNull()
      await sendPromise
    })

    it('SR-7 renders the durable failed task result (budget deny) on stream loss with no session turn', async () => {
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      // A pre-executor budget deny writes a durable PER-TASK result (with an
      // error) but NEVER a session TURN (turns are written by the executor,
      // which never runs on a deny). So the reconcile sees an idle session with
      // no new turns — pre-fix that fell through to the scary "Resend" UX.
      clerum.rpc.loadSessionMessages.mockResolvedValue({
        agent: 'agent-x',
        chatId: 'c',
        turns: [],
        state: 'idle',
      })
      // mcp-host ALWAYS stores `status:'completed'` for a durable result (even a
      // failure); the deny is signalled solely by the `error` field.
      clerum.rpc.getTaskResult.mockResolvedValue({
        success: false,
        status: 'completed',
        error: {
          code: 'BUDGET_EXCEEDED',
          message: 'Token budget exceeded for this workspace.',
          provider: 'anthropic',
        },
      })
      const { result, spies } = renderController()
      await settleMount()

      const sendPromise = result.current.handleSendAgentMessage('hola').catch(() => undefined)
      await waitForProgressHandler('task-abc')
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'open',
          taskId: 'task-abc',
          hostRef: 'agent-x',
        })
        clerum.emitTaskProgress('task-abc', {
          type: 'error',
          message: 'Progress stream disconnected',
        })
      })

      // The durable error is rendered as a failed assistant message. Wait for the
      // ASSISTANT append specifically: the recovery's append lands after the
      // `getTaskResult` await — read the last call only once its message is the
      // error bubble.
      await waitFor(() => {
        const last = clerum.chat.appendMessages.mock.calls.at(-1)?.[2]?.[0] as
          | { isError?: boolean }
          | undefined
        expect(last?.isError).toBe(true)
      })
      const appended = clerum.chat.appendMessages.mock.calls.at(-1)?.[2] as
        | Array<{ isError?: boolean; errorCode?: string; content?: string }>
        | undefined
      expect(appended?.[0]?.isError).toBe(true)
      expect(appended?.[0]?.errorCode).toBe('BUDGET_EXCEEDED')
      expect(appended?.[0]?.content).toContain('Token budget exceeded')
      // The failure toast follows the store write of the error reply.
      await waitFor(() =>
        expect(spies.pushToast).toHaveBeenCalledWith(
          'Message to agent-x failed: Token budget exceeded for this workspace.',
          'error'
        )
      )
      // #654 deliberately retains failed input, while preserving the real
      // budget error instead of presenting a misleading lost-connection error.
      expect(result.current.failedAgentSend).toMatchObject({ content: 'hola', kind: 'upstream' })
      expect(result.current.agentError).toContain('budget exceeded')
      // The session must settle back to idle (no residual "processing" spinner) —
      // the recovery path always calls setIdle, not just the fallback path.
      expect(
        Object.values(result.current.sessionStateByChatKey).some(s => s.state === 'processing')
      ).toBe(false)
      await sendPromise
    })

    it('SR-8 renders a durable success reply with no session turn on stream loss', async () => {
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      // Idle session, no new turns …
      clerum.rpc.loadSessionMessages.mockResolvedValue({
        agent: 'agent-x',
        chatId: 'c',
        turns: [],
        state: 'idle',
      })
      // … but a durable per-task result carries the reply the stream never
      // delivered (mcp-host stores `status:'completed'` for every durable result).
      clerum.rpc.getTaskResult.mockResolvedValue({
        success: true,
        status: 'completed',
        response: 'here is your report',
      })
      const { result, spies } = renderController()
      await settleMount()

      const sendPromise = result.current.handleSendAgentMessage('hola').catch(() => undefined)
      await waitForProgressHandler('task-abc')
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'open',
          taskId: 'task-abc',
          hostRef: 'agent-x',
        })
        clerum.emitTaskProgress('task-abc', {
          type: 'error',
          message: 'Progress stream disconnected',
        })
      })

      // Wait for the ASSISTANT append specifically (the recovery's reply lands
      // after the `getTaskResult` await).
      await waitFor(() => {
        const last = clerum.chat.appendMessages.mock.calls.at(-1)?.[2]?.[0] as
          | { role?: string }
          | undefined
        expect(last?.role).toBe('assistant')
      })
      const appended = clerum.chat.appendMessages.mock.calls.at(-1)?.[2] as
        | Array<{ role?: string; content?: string; isError?: boolean }>
        | undefined
      expect(appended?.[0]?.role).toBe('assistant')
      expect(appended?.[0]?.content).toBe('here is your report')
      expect(appended?.[0]?.isError).toBeUndefined()
      expect(result.current.failedAgentSend).toBeNull()
      expect(spies.pushToast).not.toHaveBeenCalledWith(expect.stringContaining('failed'), 'error')
      await sendPromise
    })
  })

  describe('activity stream (GAP-1)', () => {
    it('drives message activity status: open→streaming, activity event, error', async () => {
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })
      const { result } = renderController()
      await settleMount()

      const sendPromise = result.current.handleSendAgentMessage('hola').catch(() => undefined)
      await waitFor(() => expect(clerum.hasActivityHandler('agent-x')).toBe(true), {
        timeout: WIRING_TIMEOUT_MS,
      })

      // Read via the production-consumed selected-agent slice (`activityByMessageId`)
      // instead of the removed cross-agent `activityByAgentMessage` map (B18 dead
      // contract). For selectedAgent 'agent-x' the two hold identical entries.
      const currentEntry = () => Object.values(result.current.activityByMessageId ?? {})[0]

      // open → in-flight message transitions to 'streaming'
      await act(async () => {
        clerum.emitActivity('agent-x', {
          type: 'open',
          hostRef: 'agent-x',
          observedAt: '2026-05-28T10:00:00Z',
        })
      })
      expect(currentEntry()?.status).toBe('streaming')

      // activity event is appended to the message's event list
      await waitForProgressHandler('task-abc')
      await act(async () => {
        clerum.emitActivity('agent-x', {
          type: 'activity',
          activity: {
            version: '1.0',
            eventId: 'evt-1',
            hostRef: 'agent-x',
            ts: '2026-05-28T10:00:01Z',
            taskId: 'task-abc',
            type: 'tool.start',
            title: 'Running a tool',
            severity: 'info',
            meta: {},
            redactions: [],
          },
        })
      })
      expect(currentEntry()?.events.length).toBeGreaterThan(0)

      // error event flips status to 'error'
      await act(async () => {
        clerum.emitActivity('agent-x', { type: 'error', message: 'stream boom' })
      })
      expect(currentEntry()?.status).toBe('error')

      // Clean up the in-flight task.
      await act(async () => {
        clerum.emitTaskProgress('task-abc', {
          type: 'terminal',
          data: { taskId: 'task-abc', status: 'cancelled', reason: 'cleanup' },
        })
      })
      await sendPromise
    })
  })

  /**
   * Dev-behavior characterization (added for the D.3 re-application).
   *
   * The dev refactor (commit bd8ecec1 / post-merge) added `latestChatSessions`
   * (the cross-agent sidebar list), eager user-message persistence and
   * auto-title — all INSIDE the functions D.3 reweaves. The original D.0 suite
   * (feature-base) did not cover them, so they could be silently dropped during
   * the option-1 reweave (base 506cf826 + re-apply dev deltas). These tests pin
   * them so a dropped dev behavior fails loudly. They must keep passing AFTER
   * the D.3 reweave (the behaviors survive; only the lifecycle plumbing moves).
   */
  describe('dev behaviors (must survive the D.3 reweave)', () => {
    it('defers cross-agent menu sessions until the first screen has painted', async () => {
      const { rerender } = renderController({
        selectedAgent: null,
        loadMenuData: false,
      })
      await act(async () => {
        await Promise.resolve()
      })

      expect(clerum.chat.getIndex).not.toHaveBeenCalled()
      expect(clerum.rpc.listSessions).not.toHaveBeenCalled()

      rerender({ selectedAgent: null, loadMenuData: true })

      await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())
    })

    it('GAP-D populates latestChatSessions from chat.getIndex on mount', async () => {
      clerum.chat.getIndex.mockResolvedValue({
        version: 1,
        lastActiveChatId: null,
        onboardingDismissed: false,
        chats: [
          {
            id: 'c1',
            title: 'Chat 1',
            createdAt: '2026-05-01T00:00:00Z',
            updatedAt: '2026-05-01T00:00:00Z',
            messageCount: 2,
          },
        ],
      })
      const { result } = renderController()
      await waitFor(() => expect(result.current.latestChatSessions.length).toBeGreaterThan(0))
      const entry = result.current.latestChatSessions.find(e => e.id === 'c1')
      expect(entry?.agentRef).toBe('agent-x')
    })

    it('does not let a stale agent index replace the selected agent sidebar', async () => {
      type Index = {
        version: number
        lastActiveChatId: null
        onboardingDismissed: boolean
        chats: Array<{
          id: string
          title: string
          createdAt: string
          updatedAt: string
          messageCount: number
        }>
      }
      const agentXIndex = deferred<Index>()
      const agentYIndex = deferred<Index>()
      clerum.chat.getIndex.mockImplementation((agentRef: string) =>
        agentRef === 'agent-x' ? agentXIndex.promise : agentYIndex.promise
      )
      const { result, rerender } = renderController({
        agentNames: ['agent-x', 'agent-y'],
        loadMenuData: false,
      })
      await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalledWith('agent-x'))

      rerender({
        selectedAgent: 'agent-y',
        agentNames: ['agent-x', 'agent-y'],
        loadMenuData: false,
      })
      await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalledWith('agent-y'))
      await act(async () => {
        agentYIndex.resolve({
          version: 2,
          lastActiveChatId: null,
          onboardingDismissed: false,
          chats: [
            {
              id: 'agent-y-chat',
              title: 'Agent Y chat',
              createdAt: '2026-05-02T00:00:00Z',
              updatedAt: '2026-05-02T00:00:00Z',
              messageCount: 1,
            },
          ],
        })
      })
      await waitFor(() => expect(result.current.chatList[0]?.id).toBe('agent-y-chat'))

      await act(async () => {
        agentXIndex.resolve({
          version: 2,
          lastActiveChatId: null,
          onboardingDismissed: false,
          chats: [
            {
              id: 'agent-x-chat',
              title: 'Stale agent X chat',
              createdAt: '2026-05-03T00:00:00Z',
              updatedAt: '2026-05-03T00:00:00Z',
              messageCount: 1,
            },
          ],
        })
        await Promise.resolve()
      })

      expect(result.current.chatList.map(chat => chat.id)).toEqual(['agent-y-chat'])
    })

    it('does not let an older same-agent index replace a newer A-B-A load', async () => {
      type Index = Awaited<ReturnType<typeof clerum.chat.getIndex>>
      const firstAgentX = deferred<Index>()
      const agentY = deferred<Index>()
      const secondAgentX = deferred<Index>()
      let agentXCalls = 0
      clerum.chat.getIndex.mockImplementation((agentRef: string) => {
        if (agentRef === 'agent-y') return agentY.promise
        agentXCalls += 1
        return agentXCalls === 1 ? firstAgentX.promise : secondAgentX.promise
      })
      const { result, rerender } = renderController({
        agentNames: ['agent-x', 'agent-y'],
        loadMenuData: false,
      })
      await waitFor(() => expect(agentXCalls).toBe(1))

      rerender({
        selectedAgent: 'agent-y',
        agentNames: ['agent-x', 'agent-y'],
        loadMenuData: false,
      })
      await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalledWith('agent-y'))
      rerender({
        selectedAgent: 'agent-x',
        agentNames: ['agent-x', 'agent-y'],
        loadMenuData: false,
      })
      await waitFor(() => expect(agentXCalls).toBe(2))

      await act(async () => {
        secondAgentX.resolve({
          version: 2,
          lastActiveChatId: null,
          onboardingDismissed: false,
          chats: [
            {
              id: 'fresh-agent-x-chat',
              title: 'Fresh',
              createdAt: '2026-05-04T00:00:00Z',
              updatedAt: '2026-05-04T00:00:00Z',
              messageCount: 1,
            },
          ],
        })
      })
      await waitFor(() => expect(result.current.chatList[0]?.id).toBe('fresh-agent-x-chat'))

      await act(async () => {
        firstAgentX.resolve({
          version: 2,
          lastActiveChatId: null,
          onboardingDismissed: false,
          chats: [
            {
              id: 'stale-agent-x-chat',
              title: 'Stale',
              createdAt: '2026-05-01T00:00:00Z',
              updatedAt: '2026-05-01T00:00:00Z',
              messageCount: 1,
            },
          ],
        })
        agentY.resolve({
          version: 2,
          lastActiveChatId: null,
          onboardingDismissed: false,
          chats: [],
        })
        await Promise.resolve()
      })

      expect(result.current.chatList.map(chat => chat.id)).toEqual(['fresh-agent-x-chat'])
    })

    it('does not let a stale load retry failure clear a freshly loaded sidebar', async () => {
      type Index = Awaited<ReturnType<typeof clerum.chat.getIndex>>
      const firstLoad = deferred<Index>()
      let calls = 0
      clerum.chat.getIndex.mockImplementation(() => {
        calls += 1
        if (calls === 1) return firstLoad.promise
        if (calls === 2) {
          return Promise.resolve({
            version: 2,
            lastActiveChatId: null,
            onboardingDismissed: false,
            chats: [
              {
                id: 'fresh-chat',
                title: 'Fresh chat',
                createdAt: '2026-05-04T00:00:00Z',
                updatedAt: '2026-05-04T00:00:00Z',
                messageCount: 1,
              },
            ],
          })
        }
        return Promise.reject(new Error('stale retry failed'))
      })
      const { result, rerender } = renderController({
        currentTeamId: 'team-1',
        loadMenuData: false,
      })
      await waitFor(() => expect(calls).toBe(1))

      await act(async () => {
        firstLoad.reject(new Error('initial transient'))
        await Promise.resolve()
      })
      rerender({ currentTeamId: 'team-2', loadMenuData: false })
      await waitFor(() =>
        expect(result.current.chatList.map(chat => chat.id)).toEqual(['fresh-chat'])
      )

      await act(async () => {
        await new Promise(resolve => setTimeout(resolve, 350))
      })
      expect(calls).toBe(2)
      expect(result.current.chatList.map(chat => chat.id)).toEqual(['fresh-chat'])
    })

    it('does not append a created chat after the selected agent changes', async () => {
      type ChatMeta = Awaited<ReturnType<typeof clerum.chat.create>>
      const created = deferred<ChatMeta>()
      clerum.chat.getIndex.mockImplementation(async (agentRef: string) => ({
        version: 2,
        lastActiveChatId: null,
        onboardingDismissed: false,
        chats:
          agentRef === 'agent-y'
            ? [
                {
                  id: 'agent-y-chat',
                  title: 'Agent Y chat',
                  createdAt: '2026-05-04T00:00:00Z',
                  updatedAt: '2026-05-04T00:00:00Z',
                  messageCount: 1,
                },
              ]
            : [],
      }))
      clerum.chat.create.mockImplementation(() => created.promise)
      const { result, rerender } = renderController({
        agentNames: ['agent-x', 'agent-y'],
        loadMenuData: false,
      })
      await settleMount()

      let createPromise!: Promise<void>
      act(() => {
        createPromise = result.current.handleCreateChat()
      })
      await waitFor(() => expect(clerum.chat.create).toHaveBeenCalledWith('agent-x', 'uuid-1'))

      rerender({
        selectedAgent: 'agent-y',
        agentNames: ['agent-x', 'agent-y'],
        loadMenuData: false,
      })
      await waitFor(() =>
        expect(result.current.chatList.map(chat => chat.id)).toEqual(['agent-y-chat'])
      )

      await act(async () => {
        created.resolve({
          id: 'uuid-1',
          title: 'New Chat',
          createdAt: '2026-05-05T00:00:00Z',
          updatedAt: '2026-05-05T00:00:00Z',
          messageCount: 0,
        })
        await createPromise
      })

      expect(result.current.chatList.map(chat => chat.id)).toEqual(['agent-y-chat'])
      expect(clerum.chat.setLastActive).not.toHaveBeenCalledWith('agent-x', 'uuid-1')
    })

    it('renders local sessions without waiting for remote listSessions', async () => {
      clerum.chat.getIndex.mockResolvedValue({
        version: 1,
        lastActiveChatId: null,
        onboardingDismissed: false,
        chats: [
          {
            id: 'local-chat',
            title: 'Local chat',
            createdAt: '2026-05-01T00:00:00Z',
            updatedAt: '2026-05-01T00:00:00Z',
            messageCount: 2,
          },
        ],
      })
      clerum.rpc.listSessions.mockImplementation(() => new Promise(() => undefined))

      const { result } = renderController()

      await waitFor(() =>
        expect(result.current.chatList.some(chat => chat.id === 'local-chat')).toBe(true)
      )
      expect(result.current.chatListLoading).toBe(false)

      await waitFor(() =>
        expect(result.current.latestChatSessions.some(chat => chat.id === 'local-chat')).toBe(true)
      )
      expect(result.current.latestChatSessionsLoading).toBe(false)
    })

    it('does not replace a newer local auto-selection with an older server session', async () => {
      clerum.chat.getIndex.mockResolvedValue({
        version: 1,
        lastActiveChatId: null,
        onboardingDismissed: false,
        chats: [
          {
            id: 'newer-local',
            title: 'Newer local chat',
            createdAt: '2026-05-03T00:00:00Z',
            updatedAt: '2026-05-03T00:00:00Z',
            messageCount: 2,
          },
        ],
      })
      clerum.rpc.listSessions.mockResolvedValue({
        items: [
          {
            agent: 'agent-x',
            chatId: 'older-server',
            turnCount: 1,
            lastActivityAt: '2026-05-02T00:00:00Z',
          },
        ],
      })

      const { result } = renderController({ navItem: 'chat' })

      await waitFor(() => expect(result.current.activeChatId).toBe('newer-local'))
      await waitFor(() => expect(clerum.rpc.listSessions).toHaveBeenCalled())
      expect(result.current.activeChatId).toBe('newer-local')
      expect(clerum.chat.setLastActive).not.toHaveBeenCalledWith('agent-x', 'older-server')
    })

    it('auto-selects the newest server session from an unsorted catalog response', async () => {
      clerum.chat.getIndex.mockResolvedValue({
        version: 3,
        lastActiveChatId: null,
        onboardingDismissed: false,
        chats: [],
      })
      clerum.rpc.listSessions.mockResolvedValue({
        items: [
          {
            agent: 'agent-x',
            chatId: 'older-server',
            turnCount: 1,
            lastActivityAt: '2026-05-01T00:00:00Z',
          },
          {
            agent: 'agent-x',
            chatId: 'newest-server',
            turnCount: 1,
            lastActivityAt: '2026-05-03T00:00:00Z',
          },
        ],
      })

      const { result } = renderController({ navItem: 'chat' })

      await waitFor(() => expect(result.current.activeChatId).toBe('newest-server'))
      expect(clerum.chat.setLastActive).not.toHaveBeenCalledWith('agent-x', 'older-server')
    })

    it('loads the next remote session page only when requested', async () => {
      clerum.rpc.listSessions.mockImplementation(
        async (_hostRef: string, _teamId: string | undefined, query?: { cursor?: string }) => {
          if (query?.cursor === 'cursor-2') {
            return {
              items: [
                {
                  agent: 'agent-x',
                  chatId: 'remote-page-2',
                  turnCount: 3,
                  lastActivityAt: '2026-05-02T00:00:00Z',
                },
              ],
            }
          }
          return {
            items: [
              {
                agent: 'agent-x',
                chatId: 'remote-page-1',
                turnCount: 2,
                lastActivityAt: '2026-05-03T00:00:00Z',
              },
            ],
            nextCursor: 'cursor-2',
          }
        }
      )

      const { result } = renderController()

      await waitFor(() =>
        expect(result.current.chatList.some(chat => chat.id === 'remote-page-1')).toBe(true)
      )
      expect(result.current.chatListHasMoreRemoteSessions).toBe(true)
      expect(
        clerum.rpc.listSessions.mock.calls.some(
          call => (call[2] as { cursor?: string } | undefined)?.cursor === 'cursor-2'
        )
      ).toBe(false)

      await act(async () => {
        await result.current.loadMoreChatSessions()
      })

      await waitFor(() =>
        expect(result.current.chatList.some(chat => chat.id === 'remote-page-2')).toBe(true)
      )
      expect(result.current.chatListHasMoreRemoteSessions).toBe(false)
      expect(
        clerum.rpc.listSessions.mock.calls.some(
          call => (call[2] as { cursor?: string } | undefined)?.cursor === 'cursor-2'
        )
      ).toBe(true)
    })

    it('keeps the remote session cursor after a transient load-more failure', async () => {
      let cursorTwoCalls = 0
      clerum.rpc.listSessions.mockImplementation(
        async (_hostRef: string, _teamId: string | undefined, query?: { cursor?: string }) => {
          if (query?.cursor === 'cursor-2') {
            cursorTwoCalls += 1
            if (cursorTwoCalls === 1) throw new Error('fetch failed')
            return {
              items: [
                {
                  agent: 'agent-x',
                  chatId: 'remote-page-2-after-retry',
                  turnCount: 3,
                  lastActivityAt: '2026-05-02T00:00:00Z',
                },
              ],
            }
          }
          return {
            items: [
              {
                agent: 'agent-x',
                chatId: 'remote-page-1',
                turnCount: 2,
                lastActivityAt: '2026-05-03T00:00:00Z',
              },
            ],
            nextCursor: 'cursor-2',
          }
        }
      )

      const { result } = renderController()

      await waitFor(() =>
        expect(result.current.chatList.some(chat => chat.id === 'remote-page-1')).toBe(true)
      )
      expect(result.current.chatListHasMoreRemoteSessions).toBe(true)

      await act(async () => {
        await result.current.loadMoreChatSessions()
      })

      expect(result.current.chatListHasMoreRemoteSessions).toBe(true)

      await act(async () => {
        await result.current.loadMoreChatSessions()
      })

      await waitFor(() =>
        expect(result.current.chatList.some(chat => chat.id === 'remote-page-2-after-retry')).toBe(
          true
        )
      )
      expect(cursorTwoCalls).toBe(2)
      expect(result.current.chatListHasMoreRemoteSessions).toBe(false)
    })

    it('does not advance a session cursor from a stale load-more result', async () => {
      let resolveStalePage:
        | ((value: {
            items: Array<{
              agent: string
              chatId: string
              turnCount: number
              lastActivityAt: string
            }>
            nextCursor?: string
          }) => void)
        | undefined
      const stalePage = new Promise<{
        items: Array<{
          agent: string
          chatId: string
          turnCount: number
          lastActivityAt: string
        }>
        nextCursor?: string
      }>(resolve => {
        resolveStalePage = resolve
      })
      let cursorTwoCalls = 0
      clerum.rpc.listSessions.mockImplementation(
        async (hostRef: string, _teamId: string | undefined, query?: { cursor?: string }) => {
          if (hostRef === 'agent-y') return { items: [] }
          if (query?.cursor === 'cursor-2') {
            cursorTwoCalls += 1
            if (cursorTwoCalls === 1) return stalePage
            return {
              items: [
                {
                  agent: 'agent-x',
                  chatId: 'remote-page-2-retry',
                  turnCount: 3,
                  lastActivityAt: '2026-05-02T00:00:00Z',
                },
              ],
            }
          }
          return {
            items: [
              {
                agent: 'agent-x',
                chatId: 'remote-page-1',
                turnCount: 2,
                lastActivityAt: '2026-05-03T00:00:00Z',
              },
            ],
            nextCursor: 'cursor-2',
          }
        }
      )

      const { result, rerender } = renderController({ agentNames: ['agent-x', 'agent-y'] })
      await waitFor(() =>
        expect(result.current.chatList.some(chat => chat.id === 'remote-page-1')).toBe(true)
      )

      let pendingLoad: Promise<void> | undefined
      await act(async () => {
        pendingLoad = result.current.loadMoreChatSessions()
        await Promise.resolve()
      })
      rerender({ selectedAgent: 'agent-y', agentNames: ['agent-x', 'agent-y'] })
      rerender({ selectedAgent: 'agent-x', agentNames: ['agent-x', 'agent-y'] })
      await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalledWith('agent-x'))
      expect(result.current.chatListMoreLoading).toBe(true)

      resolveStalePage?.({
        items: [
          {
            agent: 'agent-x',
            chatId: 'stale-remote-page',
            turnCount: 4,
            lastActivityAt: '2026-05-04T00:00:00Z',
          },
        ],
        nextCursor: 'cursor-3',
      })
      await act(async () => {
        await pendingLoad
      })

      expect(cursorTwoCalls).toBe(1)
      expect(
        clerum.rpc.listSessions.mock.calls.some(
          call => (call[2] as { cursor?: string } | undefined)?.cursor === 'cursor-3'
        )
      ).toBe(false)
      expect(result.current.chatList.some(chat => chat.id === 'stale-remote-page')).toBe(false)
    })

    it('GAP-A persists the outgoing user message to the chat store on send', async () => {
      // Eager user-message persistence (dev) → D.3 must keep persisting it
      // (post-D.3 it carries task_id; here we only pin that it IS persisted).
      clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-ga' })
      clerum.rpc.getTaskResult.mockResolvedValue({ response: 'ok' })
      const { result } = renderController()
      await settleMount()

      const sendPromise = result.current.handleSendAgentMessage('persist me')
      await waitForProgressHandler('task-ga')
      await act(async () => {
        clerum.emitTaskProgress('task-ga', { type: 'open', taskId: 'task-ga', hostRef: 'agent-x' })
        clerum.emitTaskProgress('task-ga', {
          type: 'terminal',
          data: { taskId: 'task-ga', status: 'completed' },
        })
      })
      await act(async () => {
        await sendPromise
      })

      // The user message was persisted (a chat was auto-created and the typed
      // input written to it) — the input is durable across reload.
      expect(clerum.chat.create).toHaveBeenCalled()
      expect(clerum.chat.upsertMessages).toHaveBeenCalledWith(
        'agent-x',
        expect.any(String),
        expect.arrayContaining([expect.objectContaining({ role: 'user', content: 'persist me' })])
      )
      const persisted = await clerum.persistedMessages('agent-x', result.current.activeChatId!)
      expect(persisted).toContainEqual(
        expect.objectContaining({ role: 'user', content: 'persist me', task_id: 'task-ga' })
      )
    })
  })
})

describe('interrupted generated-file contract', () => {
  it('persists a generated-file attachment on the failed assistant message', async () => {
    clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-file' })
    clerum.rpc.getTaskResult.mockResolvedValue({
      success: false,
      error: { message: 'Task interrupted', code: 'TASK_ITERATION_LIMIT' },
      attachments: [
        {
          id: 'report',
          kind: 'file',
          filename: 'report.md',
          mimeType: 'text/markdown',
          encoding: 'base64',
          dataBase64: 'IyByZXBvcnQ=',
        },
      ],
    })
    const { result } = renderController()
    await settleMount()
    const send = result.current.handleSendAgentMessage('Create a report')
    await waitForProgressHandler('task-file')
    await act(async () => {
      clerum.emitTaskProgress('task-file', {
        type: 'terminal',
        data: {
          taskId: 'task-file',
          status: 'failed',
          error: { message: 'Task interrupted', code: 'TASK_ITERATION_LIMIT' },
        },
      })
    })
    await act(async () => {
      await send
    })
    const saved = clerum.chat.appendMessages.mock.calls.at(-1)?.[2]
    expect(saved).toEqual([
      expect.objectContaining({
        isError: true,
        errorCode: 'TASK_ITERATION_LIMIT',
        attachments: [expect.objectContaining({ type: 'response_file', label: 'report.md' })],
      }),
    ])
  })
})

/**
 * #678 — the send-time blockers for documents. Files enter through the public
 * restore action (the path a retried send uses), which skips the picker's
 * admission, so each blocker is reached exactly as the controller sees it at
 * send time. Every refusal is paired, in the same test, with a twin one step
 * inside the limit that reaches the Host once.
 */
describe('sendAgentMessage — per-message limits for documents (#678)', () => {
  const MIB = 1024 * 1024
  const TEXT_SHARE_BLOCKER =
    'The message text and attachment details take more than 6.0 MiB once encoded. Shorten the message or remove an attachment.'
  const FILE_QUOTA_BLOCKER =
    'The attached files take more than 16.0 MiB once encoded. Remove a file.'
  const REQUEST_BODY_BLOCKER =
    'The attachments and text take more than 24.0 MiB once encoded. Remove an attachment or shorten the message.'
  const COUNT_BLOCKER = 'A message can carry at most 20 attachments.'

  const catalog: HostModelsResult = {
    provider: 'zai',
    hostDefault: 'glm-5.3-flash',
    sessionModel: null,
    degraded: false,
    modelSelectionRevision: 0,
    models: [{ name: 'glm-5.3-flash', imageInput: { state: 'supported', reason: 'supported' } }],
  }
  const modelTransport = {
    getHostModels: vi.fn(async () => catalog),
    setHostModel: vi.fn(),
  }

  afterEach(() => {
    resetHostModelSelectionStore()
  })

  /** A read and hashed text document of `sizeBytes`, as `readComposerFile` returns it. */
  function readyTextFile(
    id: string,
    filename: string,
    sizeBytes: number
  ): ReadyComposerFileAttachment {
    return {
      id,
      type: 'file',
      filename,
      sizeBytes,
      declaredMediaType: 'text/plain',
      status: 'ready',
      classification: classifyBytes({
        // Built with this environment's Uint8Array, as readComposerFile does:
        // TextEncoder and Buffer return one from another realm under jsdom.
        bytes: new Uint8Array(Buffer.from('plain text')),
        totalByteLength: sizeBytes,
        declaredMediaType: 'text/plain',
        filename,
      }),
      dataBase64: 'Y'.repeat(base64Length(sizeBytes)),
      digestHex: 'ab'.repeat(32),
    }
  }

  async function mountedWithFiles(files: ReadyComposerFileAttachment[]) {
    clerum.rpc.invokeHostMessage.mockResolvedValue({ response: 'done' })
    const rendered = renderController()
    await settleMount()
    act(() => rendered.result.current.handleRestoreComposerFiles(files))
    return rendered
  }

  function sentAttachmentIds(): unknown[] {
    const request = clerum.rpc.invokeHostMessage.mock.calls[0]?.[1] as {
      attachments?: Array<{ id: unknown }>
    }
    expect(request).toBeDefined()
    return (request.attachments ?? []).map(attachment => attachment.id)
  }

  function expectBlocked(rendered: ReturnType<typeof renderController>, blocker: string) {
    expect(rendered.result.current.agentError).toBe(blocker)
    expect(rendered.spies.pushToast).toHaveBeenCalledWith(blocker, 'error')
    expect(clerum.chat.create).not.toHaveBeenCalled()
    expect(clerum.rpc.invokeHostMessage).not.toHaveBeenCalled()
  }

  it('refuses text that overflows the 6 MiB share beside an 11 MiB file, and sends one byte less', async () => {
    const big = readyTextFile('file-big', 'big.txt', 11 * MIB)
    const rendered = await mountedWithFiles([big])
    // Envelope (4096) + the fields rpc-proxy adds (2048) + the text as a JSON
    // string (+2 quotes) + the agent twice as a JSON string (2 × 9) + the file's
    // JSON name and fixed fields; the file's base64 is credited to the file quota.
    const fullShareText = 6 * MIB - 4096 - 2048 - 2 - 18 - JSON.stringify('big.txt').length - 640

    await act(async () => {
      await rendered.result.current.handleSendAgentMessage('x'.repeat(fullShareText + 1))
    })
    expectBlocked(rendered, TEXT_SHARE_BLOCKER)
    expect(rendered.result.current.composerFileAttachments).toHaveLength(1)

    await act(async () => {
      await rendered.result.current.handleSendAgentMessage('x'.repeat(fullShareText))
    })
    expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1)
    expect(sentAttachmentIds()).toEqual(['file-big'])
  })

  it('refuses files one byte past the 16 MiB quota, and sends the pair that fills it exactly', async () => {
    const big = readyTextFile('file-big', 'big.txt', 11 * MIB)
    const rendered = await mountedWithFiles([
      big,
      readyTextFile('file-over', 'tail.txt', 1_048_576),
    ])

    await act(async () => {
      await rendered.result.current.handleSendAgentMessage('read both')
    })
    expectBlocked(rendered, FILE_QUOTA_BLOCKER)

    act(() =>
      rendered.result.current.handleRestoreComposerFiles([
        big,
        readyTextFile('file-fits', 'tail.txt', 1_048_575),
      ])
    )
    await act(async () => {
      await rendered.result.current.handleSendAgentMessage('read both')
    })
    expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1)
    expect(sentAttachmentIds()).toEqual(['file-big', 'file-fits'])
  })

  it('refuses images and files that together pass the 24 MiB body, and sends without one file', async () => {
    const big = readyTextFile('file-big', 'big.txt', 11 * MIB)
    const rendered = await mountedWithFiles([
      big,
      readyTextFile('file-tail', 'tail.txt', 1_048_575),
    ])
    await act(async () => {
      await loadHostModels(modelTransport, 'agent-x', null)
    })
    const image: ComposerImageAttachment = {
      id: 'image-8mib',
      name: 'scan.png',
      mimeType: 'image/png',
      dataBase64: 'A'.repeat(8 * MIB),
      sizeBytes: 6 * MIB,
      previewDataUrl: 'data:image/png;base64,AAAA',
    }
    act(() => rendered.result.current.handleAddComposerImageAttachments([image]))
    // Precondition: the files sit exactly on their quota and the text is short,
    // so only the whole-body limit can refuse this send.
    expect(base64Length(11 * MIB) + base64Length(1_048_575)).toBe(16 * MIB)

    await act(async () => {
      await rendered.result.current.handleSendAgentMessage('describe')
    })
    expectBlocked(rendered, REQUEST_BODY_BLOCKER)

    act(() => rendered.result.current.handleRestoreComposerFiles([big]))
    await act(async () => {
      await rendered.result.current.handleSendAgentMessage('describe')
    })
    expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1)
    expect(sentAttachmentIds()).toEqual(expect.arrayContaining(['file-big', 'image-8mib']))
  })

  it('refuses Codex images and text that pass the 24 MiB body without any file, and sends the text that fills it', async () => {
    clerum.rpc.invokeHostMessage.mockResolvedValue({ response: 'done' })
    const rendered = renderController()
    await settleMount()
    const codexCatalog: HostModelsResult = {
      provider: 'codex-subscription',
      hostDefault: 'gpt-5.5',
      // A broker-backed provider has no silent default: the session names its model.
      sessionModel: 'gpt-5.5',
      degraded: false,
      modelSelectionRevision: 0,
      models: [{ name: 'gpt-5.5', imageInput: { state: 'supported', reason: 'supported' } }],
    }
    await act(async () => {
      await loadHostModels(
        { getHostModels: vi.fn(async () => codexCatalog), setHostModel: vi.fn() },
        'agent-x',
        null
      )
    })
    // Four bytes under the 16 MiB decoded quota Codex admits, as canonical
    // base64 without padding.
    const decodedBytes = 16 * MIB - 4
    const imageBase64Length = base64Length(decodedBytes)
    expect(imageBase64Length % 4).toBe(0)
    const image: ComposerImageAttachment = {
      id: 'image-codex',
      name: 'scan.png',
      mimeType: 'image/png',
      dataBase64: 'A'.repeat(imageBase64Length),
      sizeBytes: decodedBytes,
      previewDataUrl: 'data:image/png;base64,AAAA',
    }
    act(() => rendered.result.current.handleAddComposerImageAttachments([image]))
    expect(rendered.result.current.composerFileAttachments).toHaveLength(0)
    expect(rendered.result.current.composerImageAttachments).toHaveLength(1)
    // Envelope (4096) + the fields rpc-proxy adds (2048) + the text as a JSON
    // string (+2 quotes) + the agent twice as a JSON string (2 × 9) + the
    // image's JSON name and fixed fields + the image's base64.
    const fullBodyText =
      24 * MIB - 4096 - 2048 - 2 - 18 - JSON.stringify('scan.png').length - 640 - imageBase64Length
    // Precondition: the text share stays far inside its 6 MiB, so only the
    // whole-body limit can refuse this send.
    expect(fullBodyText + 1).toBeLessThan(3 * MIB)

    await act(async () => {
      await rendered.result.current.handleSendAgentMessage('x'.repeat(fullBodyText + 1))
    })
    expectBlocked(rendered, REQUEST_BODY_BLOCKER)
    expect(rendered.result.current.composerImageAttachments).toHaveLength(1)

    await act(async () => {
      await rendered.result.current.handleSendAgentMessage('x'.repeat(fullBodyText))
    })
    expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1)
    expect(sentAttachmentIds()).toEqual(['image-codex'])
    const request = clerum.rpc.invokeHostMessage.mock.calls[0]?.[1] as { content: string }
    expect(request.content).toHaveLength(fullBodyText)
  })

  it('refuses a twenty-first attachment and sends twenty', async () => {
    const files = Array.from({ length: 21 }, (_, index) =>
      readyTextFile(`file-${index}`, `part-${index}.txt`, 10)
    )
    const rendered = await mountedWithFiles(files)

    await act(async () => {
      await rendered.result.current.handleSendAgentMessage('read all')
    })
    expectBlocked(rendered, COUNT_BLOCKER)

    act(() => rendered.result.current.handleRestoreComposerFiles(files.slice(0, 20)))
    await act(async () => {
      await rendered.result.current.handleSendAgentMessage('read all')
    })
    expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1)
    expect(sentAttachmentIds()).toHaveLength(20)
  })

  const utf8Bytes = (value: string) => new TextEncoder().encode(value).length

  /** Four Global Files references whose names take three UTF-8 bytes per character. */
  function wideNameReferences(): ComposerGlobalFileReference[] {
    return Array.from({ length: 4 }, (_, index) => {
      const resourceId = String(index).repeat(32)
      return {
        id: `global-file:main:${resourceId}`,
        type: 'global_file' as const,
        resourceId,
        drive: 'main',
        gfsUri: `gfs://main/${resourceId}`,
        label: `${'文'.repeat(251)}.txt`,
        version: 1,
        bytes: 2048,
      }
    })
  }

  it('counts the serialized references and the agent in the 6 MiB share, and sends the draft that fills it', async () => {
    const references = wideNameReferences()
    const rendered = await mountedWithFiles([readyTextFile('file-doc', 'doc.txt', 1024)])
    act(() => rendered.result.current.handleAddComposerReferenceAttachments(references))
    const jsonBytes = (value: unknown) => utf8Bytes(JSON.stringify(value))
    const contentBytes = (draft: string) =>
      jsonBytes(buildComposerRequestContent(draft, references))
    // Everything the share holds besides the draft, each part as the request
    // body carries it: envelope, fields rpc-proxy adds, the text with its
    // references section, the serialized references, the agent twice and the
    // file details.
    const referencesBytes = jsonBytes(buildComposerFileReferences(references))
    const fixedBytes =
      4096 +
      2048 +
      (contentBytes('x') - 1) +
      referencesBytes +
      2 * jsonBytes('agent-x') +
      jsonBytes('doc.txt') +
      640
    const boundary = 6 * MIB - fixedBytes
    // The text grows one byte per draft character: the arithmetic above holds.
    expect(contentBytes('x'.repeat(boundary))).toBe(contentBytes('x') - 1 + boundary)
    // Leaving the references out would let the blocked draft below through.
    expect(referencesBytes).toBeGreaterThan(1)

    await act(async () => {
      await rendered.result.current.handleSendAgentMessage('x'.repeat(boundary + 1))
    })
    expectBlocked(rendered, TEXT_SHARE_BLOCKER)
    expect(rendered.result.current.composerFileAttachments).toHaveLength(1)
    expect(rendered.result.current.composerReferenceAttachments).toHaveLength(4)

    await act(async () => {
      await rendered.result.current.handleSendAgentMessage('x'.repeat(boundary))
    })
    expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1)
    const request = clerum.rpc.invokeHostMessage.mock.calls[0]?.[1] as {
      content: string
      fileReferences: Parameters<typeof composerNonImageShareBytes>[0]['fileReferences']
      attachments: Array<Record<string, unknown>>
    }
    // The request carries the text and references the boundary was computed from.
    expect(request.content).toBe(buildComposerRequestContent('x'.repeat(boundary), references))
    expect(request.fileReferences).toEqual(buildComposerFileReferences(references))
    // The estimate bounds what is posted: the request as serialized without the
    // base64 the file quota credits, plus 1 KiB for the fields rpc-proxy adds.
    const postedShareBytes = utf8Bytes(
      JSON.stringify({
        ...request,
        attachments: request.attachments.map(attachment => ({ ...attachment, dataBase64: '' })),
      })
    )
    expect(
      composerNonImageShareBytes({
        content: request.content,
        fileReferences: request.fileReferences,
        hostRef: 'agent-x',
        files: [{ filename: 'doc.txt' }],
        images: [],
      })
    ).toBeGreaterThanOrEqual(postedShareBytes + 1024)
  })

  it('counts the JSON escaping of the text in the share, and sends fewer escaped characters', async () => {
    const rendered = await mountedWithFiles([readyTextFile('file-doc', 'doc.txt', 1024)])
    // A newline is one byte typed and two once escaped in the JSON body.
    await act(async () => {
      await rendered.result.current.handleSendAgentMessage(`a${'\n'.repeat(3.5 * MIB)}b`)
    })
    expectBlocked(rendered, TEXT_SHARE_BLOCKER)

    await act(async () => {
      await rendered.result.current.handleSendAgentMessage(`a${'\n'.repeat(2 * MIB)}b`)
    })
    expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1)
    expect(sentAttachmentIds()).toEqual(['file-doc'])
  })

  it('checks the share on a send without attachments, and sends shorter text', async () => {
    clerum.rpc.invokeHostMessage.mockResolvedValue({ response: 'done' })
    const rendered = renderController()
    await settleMount()
    // A double quote is one byte typed and two once escaped in the JSON body.
    await act(async () => {
      await rendered.result.current.handleSendAgentMessage('"'.repeat(Math.floor(3.2 * MIB)))
    })
    expectBlocked(rendered, TEXT_SHARE_BLOCKER)

    await act(async () => {
      await rendered.result.current.handleSendAgentMessage('"'.repeat(Math.floor(2.9 * MIB)))
    })
    expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1)
    const request = clerum.rpc.invokeHostMessage.mock.calls[0]?.[1] as { content: string }
    expect(request.content).toHaveLength(Math.floor(2.9 * MIB))
  })
})