Skip to content

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

TypeScript
13.2 KB
Raw Blame
// @vitest-environment jsdom
/**
 * Characterization tests for `sendAgentMessage` paths that the existing suites
 * (D.0 / SR-*) did not cover: the synchronous (non-async) response branch, the
 * POST-error branch (banner + failedAgentSend + late user-message persist +
 * retry), and the send-time auto-title (B10 fix).
 *
 * Pinned against the PUBLIC hook API via the shared harness so they survive the
 * refactor. See .specs/refactor-useAgentChatController/plan.md Fase 0.
 */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, waitFor } from '@testing-library/react'
import { renderController } from './__fixtures__/controllerHarness'
import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'

let clerum: MockClerum
let uuidCounter = 0

;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true

beforeEach(() => {
  uuidCounter = 0
  vi.spyOn(globalThis.crypto, 'randomUUID').mockImplementation(
    () => `uuid-${++uuidCounter}` as `${string}-${string}-${string}-${string}-${string}`
  )
  clerum = installMockClerum()
})

afterEach(() => {
  vi.restoreAllMocks()
  vi.useRealTimers()
  uninstallMockClerum()
})

async function settleMount() {
  await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())
}

describe('sendAgentMessage — synchronous (non-async) response', () => {
  it('appends a direct reply, persists the user message, and never opens a stream', async () => {
    // No taskId in the response → the synchronous branch (a direct reply).
    clerum.rpc.invokeHostMessage.mockResolvedValue({ response: 'direct answer' })
    const { result, spies } = renderController()
    await settleMount()

    await act(async () => {
      await result.current.handleSendAgentMessage('quick question')
    })

    // No async task → no progress subscription was ever opened.
    expect(clerum.rpc.subscribeTaskProgress).not.toHaveBeenCalled()
    // user message (upserted before the POST) + assistant reply (appended) are
    // both in the store.
    const chatId = result.current.activeChatId!
    expect(
      (await clerum.persistedMessages('agent-x', chatId)).map(m => [m.role, m.content])
    ).toEqual([
      ['user', 'quick question'],
      ['assistant', 'direct answer'],
    ])
    expect(clerum.chat.appendMessages).toHaveBeenCalledTimes(1)
    const assistant = clerum.chat.appendMessages.mock.calls.at(-1)?.[2] as
      | Array<{ role?: string; content?: string; isError?: boolean }>
      | undefined
    expect(assistant?.[0]?.role).toBe('assistant')
    expect(assistant?.[0]?.content).toBe('direct answer')
    expect(assistant?.[0]?.isError).toBeUndefined()
    expect(spies.pushToast).toHaveBeenCalledWith('Message sent to agent-x.', 'success')
  })

  it('renders a structured synchronous error as an isError assistant message', async () => {
    clerum.rpc.invokeHostMessage.mockResolvedValue({
      error: { message: 'bad request', code: 'invalid_input', provider: 'anthropic' },
    })
    const { result, spies } = renderController()
    await settleMount()

    await act(async () => {
      await result.current.handleSendAgentMessage('do the thing')
    })

    const assistant = clerum.chat.appendMessages.mock.calls.at(-1)?.[2] as
      | Array<{ role?: string; content?: string; isError?: boolean; errorCode?: string }>
      | undefined
    expect(assistant?.[0]?.isError).toBe(true)
    expect(assistant?.[0]?.errorCode).toBe('invalid_input')
    expect(assistant?.[0]?.content).toBe('bad request')
    expect(spies.pushToast).toHaveBeenCalledWith('Message to agent-x failed: bad request', 'error')
  })
})

describe('sendAgentMessage — POST failure', () => {
  it('surfaces the banner + failedAgentSend and persists the user input late', async () => {
    clerum.rpc.invokeHostMessage.mockRejectedValue(new Error('network down'))
    const { result, spies } = renderController()
    await settleMount()

    await act(async () => {
      await result.current.handleSendAgentMessage('please summarize')
    })

    expect(result.current.agentError).toBeTruthy()
    expect(result.current.failedAgentSend?.content).toBe('please summarize')
    expect(result.current.failedAgentSend?.kind).toBe('network')
    // Late persist: the POST threw before the single post-taskId persist, so the
    // user's typed input is still written to the store (best-effort durability).
    expect(clerum.chat.upsertMessages).toHaveBeenCalledWith(
      'agent-x',
      expect.any(String),
      expect.arrayContaining([
        expect.objectContaining({ role: 'user', content: 'please summarize' }),
      ])
    )
    expect(spies.pushToast).toHaveBeenCalledWith(expect.stringContaining('Message failed'), 'error')
    // Fire-and-forget guard released.
    expect(result.current.agentSending).toBe(false)
  })

  it('handleRetryFailedAgentSend re-sends the failed payload once it recovers', async () => {
    clerum.rpc.invokeHostMessage.mockRejectedValueOnce(new Error('network down'))
    const { result } = renderController()
    await settleMount()

    await act(async () => {
      await result.current.handleSendAgentMessage('retry me')
    })
    expect(result.current.failedAgentSend?.content).toBe('retry me')

    // The retry succeeds with an async task.
    clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-retry' })
    const retryPromise = result.current.handleRetryFailedAgentSend().catch(() => undefined)
    await waitFor(() => expect(clerum.hasProgressHandler('task-retry')).toBe(true))

    expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(2)
    const secondReq = clerum.rpc.invokeHostMessage.mock.calls[1]?.[1] as { content?: string }
    expect(secondReq?.content).toContain('retry me')

    // #654 M5 — the retry ran under a new userMessageId, so the failed attempt's
    // retained snapshot has to be released explicitly. `failedAgentSend` is
    // derived from the newest retained snapshot carrying a failure, so it stays
    // non-null for as long as that snapshot survives. Asserted before the
    // terminal event so the terminal handling cannot be what cleared it.
    await act(async () => {
      await retryPromise
    })
    expect(result.current.failedAgentSend).toBeNull()

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

  it('a second retry click while the first retry is in flight does not send twice (#654 M5)', async () => {
    clerum.rpc.invokeHostMessage.mockRejectedValueOnce(new Error('network down'))
    const { result } = renderController()
    await settleMount()

    await act(async () => {
      await result.current.handleSendAgentMessage('retry once')
    })
    expect(result.current.failedAgentSend?.content).toBe('retry once')
    expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1)

    // Hold the retry's POST open so the second click lands while it is in flight.
    let resolvePost: (value: { taskId: string }) => void = () => undefined
    clerum.rpc.invokeHostMessage.mockImplementationOnce(
      () =>
        new Promise<{ taskId: string }>(resolve => {
          resolvePost = resolve
        })
    )
    // Both clicks hit the same rendered callback, as two fast clicks on one
    // button would, before React re-renders with `agentSending: true`.
    const retry = result.current.handleRetryFailedAgentSend
    const first = retry().catch(() => undefined)
    const second = retry().catch(() => undefined)
    // The POST is reached only after the send's own awaits; resolving before it
    // is issued would resolve nothing.
    await waitFor(() => expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(2))
    await act(async () => {
      resolvePost({ taskId: 'task-retry-once' })
      await first
      await second
    })

    // Exactly one original send plus one retry: the witness that the first retry
    // ran and the count that proves the second one did not.
    expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(2)
    expect(result.current.failedAgentSend).toBeNull()

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

describe('sendAgentMessage — auto-title on send (B10)', () => {
  it('titles a chat auto-created by the send from the first message', async () => {
    // No active chat → the send auto-creates one (title "New Chat"). The closure's
    // chatList predates that chat, so pre-B10 the auto-title silently no-op'd.
    clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-title' })
    const { result } = renderController()
    await settleMount()
    expect(result.current.activeChatId).toBeNull()

    const sendPromise = act(async () => {
      await result.current.handleSendAgentMessage('summarize the quarterly report')
    })
    await waitFor(() => expect(clerum.hasProgressHandler('task-title')).toBe(true))
    await act(async () => {
      clerum.emitTaskProgress('task-title', {
        type: 'terminal',
        data: { taskId: 'task-title', status: 'cancelled', reason: 'cleanup' },
      })
    })
    await sendPromise

    const createdChatId = result.current.activeChatId!
    await waitFor(() =>
      expect(clerum.chat.rename).toHaveBeenCalledWith(
        'agent-x',
        createdChatId,
        'summarize the quarterly report',
        1
      )
    )
  })
})

describe('sendAgentMessage — new chat target', () => {
  it('keeps a retained raw send callback off the prior chat after New chat clears it', async () => {
    const priorChatId = 'prior-chat'
    await clerum.chat.create('agent-x', priorChatId)
    await clerum.chat.upsertMessages('agent-x', priorChatId, [
      {
        id: 'prior-message',
        role: 'user',
        content: 'keep this in the previous chat',
        timestamp: Date.now(),
      },
    ])

    clerum.rpc.invokeHostMessage.mockResolvedValue({ response: 'fresh reply' })
    const { result, rerender, unmount } = renderController({ navItem: 'agents' })
    await settleMount()
    await act(async () => {
      result.current.setPendingChatSelection('agent-x', priorChatId)
    })
    expect(result.current.activeChatId).toBe(priorChatId)

    // Retain the raw hook callback before New chat commits. This is deliberately
    // callback-hardening coverage; pendingChatSelection.characterization covers
    // the production stable action after a superseded list load resolves.
    const retainedRawSend = result.current.handleSendAgentMessage
    clerum.chat.getIndex.mockClear()
    clerum.chat.getIndex.mockReturnValue(new Promise(() => undefined))
    await act(async () => {
      result.current.setPendingChatSelection('agent-x', null, { suppressAutoSelect: true })
      result.current.clearActiveChat()
      rerender({ navItem: 'chat' })
    })
    await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalledTimes(1))
    expect(result.current.activeChatId).toBeNull()
    expect(result.current.chatMessages).toEqual([])

    await act(async () => {
      await retainedRawSend('start the next conversation')
    })

    const request = clerum.rpc.invokeHostMessage.mock.calls.at(-1)?.[1] as
      | { threadId?: string }
      | undefined
    expect(request?.threadId).not.toBe(priorChatId)

    const priorMessages = await clerum.persistedMessages('agent-x', priorChatId)
    expect(priorMessages).toEqual([
      expect.objectContaining({ id: 'prior-message', content: 'keep this in the previous chat' }),
    ])
    const newChatId = request?.threadId
    expect(newChatId).toBeTruthy()
    expect(await clerum.persistedMessages('agent-x', newChatId!)).toEqual(
      expect.arrayContaining([
        expect.objectContaining({ role: 'user', content: 'start the next conversation' }),
      ])
    )
    unmount()
  })
})

// R1-M11: the fake store must merge a second write of the same turn the way
// `ChatStore.upsertMessages` does. The send path persists the user turn before
// the POST and again with its task_id once the Host accepts it; a fake that
// drops the second write hides a lost task_id.
describe('sendAgentMessage — outgoing user turn persistence', () => {
  it('keeps the task_id the acknowledgement adds to the persisted user turn', async () => {
    clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-77' })
    const { result } = renderController()
    await settleMount()

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

    // Witness: the same turn was written twice, the second time with its task.
    await waitFor(() => expect(clerum.chat.upsertMessages).toHaveBeenCalledTimes(2))
    const [agentRef, chatId, firstWrite] = clerum.chat.upsertMessages.mock.calls[0] as [
      string,
      string,
      Array<{ id: string }>,
    ]
    const turnId = firstWrite[0]?.id
    expect(clerum.chat.upsertMessages.mock.calls[1]?.[2]?.[0]).toMatchObject({
      id: turnId,
      task_id: 'task-77',
    })

    const persistedUserTurns = (await clerum.persistedMessages(agentRef, chatId)).filter(
      message => message.role === 'user'
    )
    expect(persistedUserTurns).toEqual([
      expect.objectContaining({ id: turnId, content: 'hello', task_id: 'task-77' }),
    ])
  })
})