Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

29.3 KB
Raw Blame
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import '@testing-library/jest-dom'

// ---- Module mocks ----------------------------------------------------------

vi.mock('@/i18n/react-i18next-compat', () => ({
  useTranslation: () => ({
    t: (k: string, opts?: Record<string, unknown>) =>
      opts ? `${k} ${Object.values(opts).join(' ')}` : k,
  }),
}))

const selectedModelRef = vi.hoisted(() => ({ current: { id: 'm1' } as any }))
const selectedProviderRef = vi.hoisted(() => ({ current: 'llamacpp' }))

// The failed-load error row links to the provider page's hardware check, so
// the component reaches the router. Only Link is used here.
vi.mock('@tanstack/react-router', () => ({
  Link: ({ children, search, ...rest }: any) => (
    <a data-search={JSON.stringify(search)} {...rest}>
      {children}
    </a>
  ),
}))
vi.mock('@/hooks/useModelProvider', () => ({
  useModelProvider: (selector: any) =>
    selector({
      selectedModel: selectedModelRef.current,
      selectedProvider: selectedProviderRef.current,
    }),
}))

// Stub heavy children: RenderMarkdown
vi.mock('../RenderMarkdown', () => ({
  RenderMarkdown: ({ content }: any) => (
    <div data-testid="render-markdown">{content}</div>
  ),
}))

// Stub streamdown
vi.mock('streamdown', () => ({
  Streamdown: ({ children }: any) => <div data-testid="streamdown">{children}</div>,
}))

// Stub ChainOfThought
vi.mock('@/components/ai-elements/chain-of-thought', () => ({
  ChainOfThought: ({ children }: any) => <div data-testid="cot">{children}</div>,
  ChainOfThoughtContent: ({ children }: any) => <div>{children}</div>,
  ChainOfThoughtHeader: () => <div>CoT Header</div>,
}))

// Stub Tool
vi.mock('@/components/ai-elements/tool', () => ({
  Tool: ({ children }: any) => <div data-testid="tool">{children}</div>,
  ToolContent: ({ children }: any) => <div>{children}</div>,
  ToolHeader: ({ title }: any) => <div data-testid="tool-header">{title}</div>,
  ToolInput: ({ input }: any) => <div data-testid="tool-input">{String(input)}</div>,
  ToolOutput: ({ output, errorText }: any) => (
    <div data-testid="tool-output">{errorText ?? String(output ?? '')}</div>
  ),
  ToolApprovalActions: () => null,
}))

// Stub dialogs
const editOnSaveRef = vi.hoisted(() => ({ current: null as any }))
vi.mock('@/containers/dialogs/EditMessageDialog', () => ({
  EditMessageDialog: ({ onSave, message }: any) => {
    editOnSaveRef.current = onSave
    return (
      <button data-testid="edit-btn" onClick={() => onSave('edited: ' + message)}>
        Edit
      </button>
    )
  },
}))

vi.mock('@/containers/dialogs/DeleteMessageDialog', () => ({
  DeleteMessageDialog: ({ onDelete }: any) => (
    <button data-testid="delete-btn" onClick={onDelete}>
      Delete
    </button>
  ),
}))

vi.mock('@/containers/TokenSpeedIndicator', () => ({
  default: ({ streaming }: any) => (
    <div data-testid="token-speed" data-streaming={String(streaming)} />
  ),
}))

vi.mock('../CopyButton', () => ({
  CopyButton: ({ text }: any) => (
    <button data-testid="copy-btn" data-text={text}>
      Copy
    </button>
  ),
}))

vi.mock('@/utils/formatDate', () => ({
  formatDate: () => '2024-01-01 full',
  formatMessageTime: () => '3:30 PM',
}))

const touchRef = vi.hoisted(() => ({ current: false }))
vi.mock('@/hooks/useMediaQuery', () => ({
  useTouchDevice: () => touchRef.current,
}))

vi.mock('@/lib/fileMetadata', () => ({
  extractFilesFromPrompt: (text: string) => {
    if (text?.startsWith('[FILE:')) {
      return {
        cleanPrompt: text.replace(/\[FILE:[^\]]+\]/g, '').trim(),
        files: [{ id: 'f1', name: 'doc.txt', injectionMode: 'inline' }],
      }
    }
    return { cleanPrompt: text ?? '', files: [] }
  },
}))

vi.mock('@/components/ui/button', () => ({
  Button: ({ children, onClick, ...rest }: any) => (
    <button onClick={onClick} {...rest}>
      {children}
    </button>
  ),
}))

vi.mock('@/components/PromptProgress', () => ({
  // `hideIdle` is what suppresses the generic "Working…" fallback, and the real
  // component renders nothing when it is set with no model load in flight, so
  // the stand-in has to honour it or every caller looks like it shows a card.
  PromptProgress: ({ hideIdle }: { hideIdle?: boolean }) =>
    hideIdle ? null : <div data-testid="prompt-progress" />,
}))

const pendingApprovalsRef = vi.hoisted(() => ({ current: {} as any }))
vi.mock('@/hooks/useToolApprovalRequests', () => ({
  useToolApprovalRequests: (selector: any) =>
    selector({ pending: pendingApprovalsRef.current }),
}))

// Import after mocks
import { MessageItem } from '../MessageItem'
import { useMessageErrors } from '@/stores/message-errors'

const makeMsg = (overrides: any = {}) => ({
  id: 'msg-1',
  role: 'assistant',
  parts: [{ type: 'text', text: 'Hello assistant' }],
  metadata: { createdAt: new Date() },
  ...overrides,
})

describe('MessageItem', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    selectedModelRef.current = { id: 'm1' }
    selectedProviderRef.current = 'llamacpp'
    pendingApprovalsRef.current = {}
    touchRef.current = false
  })

  it('renders assistant text via RenderMarkdown', () => {
    render(
      <MessageItem
        message={makeMsg() as any}
        isFirstMessage
        isLastMessage
        status={'ready' as any}
      />
    )
    expect(screen.getByTestId('render-markdown')).toHaveTextContent('Hello assistant')
  })

  it('renders user message in a bubble (no markdown renderer)', () => {
    render(
      <MessageItem
        message={makeMsg({ role: 'user', parts: [{ type: 'text', text: 'Hi there' }] }) as any}
        highlightedPrefix={null}
        isFirstMessage
        isLastMessage
        status={'ready' as any}
      />
    )
    expect(screen.getByText('Hi there')).toBeInTheDocument()
    expect(screen.queryByTestId('render-markdown')).not.toBeInTheDocument()
  })
  it('highlights a recognized skill prefix in a submitted user message', () => {
    render(
      <MessageItem
        message={
          makeMsg({
            role: 'user',
            parts: [{ type: 'text', text: '/code-review inspect this change' }],
          }) as any
        }
        highlightedPrefix="/code-review"
        isFirstMessage
        isLastMessage
        status={'ready' as any}
      />
    )

    expect(screen.getByTestId('skill-command-prefix')).toHaveTextContent(
      '/code-review'
    )
    expect(screen.getByText(/inspect this change/)).toBeInTheDocument()
  })

  it('renders attached files from user text metadata', () => {
    render(
      <MessageItem
        message={
          makeMsg({
            role: 'user',
            parts: [{ type: 'text', text: '[FILE:doc.txt] Please summarize' }],
          }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
      />
    )
    expect(screen.getByText('doc.txt')).toBeInTheDocument()
    expect(screen.getByText('(inline)')).toBeInTheDocument()
  })

  it('fires onRegenerate when regenerate button clicked (assistant, last)', () => {
    const onRegenerate = vi.fn()
    render(
      <MessageItem
        message={makeMsg() as any}
        isFirstMessage
        isLastMessage
        status={'ready' as any}
        onRegenerate={onRegenerate}
      />
    )
    const regenBtn = screen.getByTitle('chat:actions.regenerate')
    fireEvent.click(regenBtn)
    expect(onRegenerate).toHaveBeenCalledWith('msg-1')
  })

  it('does not render regenerate button when not last message', () => {
    const onRegenerate = vi.fn()
    render(
      <MessageItem
        message={makeMsg() as any}
        isFirstMessage
        isLastMessage={false}
        status={'ready' as any}
        onRegenerate={onRegenerate}
      />
    )
    expect(screen.queryByTitle('chat:actions.regenerate')).not.toBeInTheDocument()
  })

  it('shows Continue button on a stopped last assistant message', () => {
    const onContinue = vi.fn()
    render(
      <MessageItem
        message={
          makeMsg({ metadata: { createdAt: new Date(), stopped: true } }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
        onContinue={onContinue}
      />
    )
    const btn = screen.getByTitle('chat:actions.continue')
    fireEvent.click(btn)
    expect(onContinue).toHaveBeenCalledWith('msg-1')
  })

  // Continue extends partial text; with none there is nothing to resume.
  it('hides Continue on a stopped turn that never wrote any text', () => {
    render(
      <MessageItem
        message={
          makeMsg({
            metadata: { createdAt: new Date(), stopped: true },
            parts: [
              {
                type: 'tool-slow_wait',
                toolCallId: 'c1',
                state: 'output-error',
                input: {},
                errorText: 'Stopped before the tool finished.',
              },
            ],
          }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
        onContinue={vi.fn()}
      />
    )
    expect(screen.queryByTitle('chat:actions.continue')).not.toBeInTheDocument()
  })

  it('hides Continue button when the turn finished normally', () => {
    render(
      <MessageItem
        message={makeMsg() as any}
        isFirstMessage
        isLastMessage
        status={'ready' as any}
        onContinue={vi.fn()}
      />
    )
    expect(screen.queryByTitle('chat:actions.continue')).not.toBeInTheDocument()
  })

  it('hides Continue button on a stopped message that is not last', () => {
    render(
      <MessageItem
        message={
          makeMsg({ metadata: { createdAt: new Date(), stopped: true } }) as any
        }
        isFirstMessage
        isLastMessage={false}
        status={'ready' as any}
        onContinue={vi.fn()}
      />
    )
    expect(screen.queryByTitle('chat:actions.continue')).not.toBeInTheDocument()
  })

  it('fires onEdit when edit dialog saves', () => {
    const onEdit = vi.fn()
    render(
      <MessageItem
        message={
          makeMsg({ role: 'user', parts: [{ type: 'text', text: 'original' }] }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
        onEdit={onEdit}
      />
    )
    fireEvent.click(screen.getByTestId('edit-btn'))
    expect(onEdit).toHaveBeenCalledWith('msg-1', expect.stringContaining('original'))
  })

  it('fires onDelete when delete dialog button clicked', () => {
    const onDelete = vi.fn()
    render(
      <MessageItem
        message={
          makeMsg({ role: 'user', parts: [{ type: 'text', text: 'x' }] }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
        onDelete={onDelete}
      />
    )
    fireEvent.click(screen.getByTestId('delete-btn'))
    expect(onDelete).toHaveBeenCalledWith('msg-1')
  })

  /// One click to ask the same question again, from partway up the transcript
  /// -- an agent turn is a chain of tool calls, so "regenerate" only ever
  /// applied to the last one.
  it('fires onRetry with the question text', () => {
    const onRetry = vi.fn()
    render(
      <MessageItem
        message={
          makeMsg({
            role: 'user',
            parts: [{ type: 'text', text: 'ask me again' }],
          }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
        onRetry={onRetry}
      />
    )
    fireEvent.click(screen.getByTitle('chat:actions.askAgain'))
    expect(onRetry).toHaveBeenCalledWith(
      'msg-1',
      expect.stringContaining('ask me again')
    )
  })

  /// Offered only where a caller opts in: an ordinary chat has `onRegenerate`
  /// on the answer and no use for a second way to re-ask.
  it('offers no retry without a handler', () => {
    render(
      <MessageItem
        message={
          makeMsg({ role: 'user', parts: [{ type: 'text', text: 'x' }] }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
      />
    )
    expect(screen.queryByTitle('chat:actions.askAgain')).not.toBeInTheDocument()
  })

  it('hides actions when hideActions is set', () => {
    render(
      <MessageItem
        message={
          makeMsg({ role: 'user', parts: [{ type: 'text', text: 'x' }] }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
        onEdit={vi.fn()}
        onDelete={vi.fn()}
        hideActions
      />
    )
    expect(screen.queryByTestId('edit-btn')).not.toBeInTheDocument()
    expect(screen.queryByTestId('delete-btn')).not.toBeInTheDocument()
  })

  it('hideActions drops the whole assistant row, timestamp included', () => {
    render(
      <MessageItem
        message={makeMsg() as any}
        isFirstMessage
        isLastMessage={false}
        status={'ready' as any}
        hideActions
      />
    )
    expect(screen.queryByText('2024-01-01')).not.toBeInTheDocument()
    expect(screen.queryByTestId('token-speed')).not.toBeInTheDocument()
  })

  it('streaming state hides edit/delete and marks token speed streaming', () => {
    render(
      <MessageItem
        message={makeMsg() as any}
        isFirstMessage
        isLastMessage
        status={'streaming' as any}
        onEdit={vi.fn()}
        onDelete={vi.fn()}
      />
    )
    expect(screen.queryByTestId('edit-btn')).not.toBeInTheDocument()
    expect(screen.queryByTestId('delete-btn')).not.toBeInTheDocument()
    expect(screen.getByTestId('token-speed').getAttribute('data-streaming')).toBe('true')
  })

  it('renders user image attachment', () => {
    render(
      <MessageItem
        message={
          makeMsg({
            role: 'user',
            parts: [
              {
                type: 'file',
                mediaType: 'image/png',
                url: 'blob:foo',
                filename: 'pic.png',
              },
            ],
          }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
      />
    )
    const img = screen.getByAltText('pic.png') as HTMLImageElement
    expect(img.src).toContain('blob:foo')
  })

  it('renders a CoT block containing reasoning', () => {
    render(
      <MessageItem
        message={
          makeMsg({
            parts: [
              { type: 'reasoning', text: 'thinking...' },
              { type: 'text', text: 'final' },
            ],
          }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
      />
    )
    expect(screen.getByTestId('cot')).toBeInTheDocument()
    // Reasoning renders as plain text (not markdown) for performance.
    expect(screen.getByText('thinking...')).toBeInTheDocument()
  })

  it('folds a tool part into the CoT working trace', () => {
    render(
      <MessageItem
        message={
          makeMsg({
            parts: [
              { type: 'tool-search', state: 'output-available', input: { q: 'x' }, output: 'ok' },
              { type: 'text', text: 'done' },
            ],
          }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
      />
    )
    expect(screen.getByTestId('tool')).toBeInTheDocument()
    expect(screen.getByTestId('tool-header')).toHaveTextContent('search')
    expect(screen.getByTestId('cot')).toBeInTheDocument()
  })

  describe('interim reasoning text', () => {
    const interstitialMsg = () =>
      makeMsg({
        parts: [
          { type: 'reasoning', text: 'first thought' },
          { type: 'text', text: 'interim answer' },
          { type: 'reasoning', text: 'second thought' },
          { type: 'text', text: 'final answer' },
        ],
      }) as any

    it('renders interim text as a normal message and splits the trace', () => {
      render(
        <MessageItem
          message={interstitialMsg()}
          isFirstMessage
          isLastMessage
          status={'ready' as any}
        />
      )
      // Trace splits into two groups around the interim answer.
      expect(screen.getAllByTestId('cot')).toHaveLength(2)
      // Both interim and final render in the message body.
      const bodies = screen.getAllByTestId('render-markdown')
      expect(bodies).toHaveLength(2)
      expect(bodies[0]).toHaveTextContent('interim answer')
      expect(bodies[1]).toHaveTextContent('final answer')
    })

    it('skips empty interim text parts', () => {
      render(
        <MessageItem
          message={
            makeMsg({
              parts: [
                { type: 'reasoning', text: 'thinking' },
                { type: 'text', text: '   ' },
                { type: 'text', text: 'final' },
              ],
            }) as any
          }
          isFirstMessage
          isLastMessage
          status={'ready' as any}
        />
      )
      // Blank interim text does not flush the trace into a second group.
      expect(screen.getAllByTestId('cot')).toHaveLength(1)
      const bodies = screen.getAllByTestId('render-markdown')
      expect(bodies).toHaveLength(1)
      expect(bodies[0]).toHaveTextContent('final')
    })
  })

  it('renders tool error when state is output-error', () => {
    render(
      <MessageItem
        message={
          makeMsg({
            parts: [
              {
                type: 'tool-x',
                state: 'output-error',
                errorText: 'boom',
              },
            ],
          }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
      />
    )
    expect(screen.getByTestId('tool-output')).toHaveTextContent('boom')
  })

  /// The tool's own card names the call and ticks its duration one row above,
  /// so a status row repeating it was the same thing twice.
  it('leaves an executing tool call to its own card', () => {
    render(
      <MessageItem
        message={
          makeMsg({
            parts: [
              { type: 'tool-search', state: 'input-available', toolCallId: 'tc1', input: {} },
            ],
          }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
      />
    )
    expect(screen.queryByTestId('prompt-progress')).not.toBeInTheDocument()
    expect(screen.queryByRole('status')).not.toBeInTheDocument()
  })

  it('shows a persistent badge for a successfully loaded skill', () => {
    render(
      <MessageItem
        message={
          makeMsg({
            parts: [
              {
                type: 'tool-skill_read',
                state: 'output-available',
                toolCallId: 'skill-1',
                input: { name: 'pptx' },
                output: 'skill instructions',
              },
              { type: 'text', text: 'Done' },
            ],
          }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
      />
    )

    expect(
      screen.getByText('common:skillsUsed pptx')
    ).toBeInTheDocument()
    expect(screen.getByText('Used pptx')).toBeInTheDocument()
  })

  it('defers the persistent skills badge until generation finishes', () => {
    render(
      <MessageItem
        message={
          makeMsg({
            parts: [
              {
                type: 'tool-skill_read',
                state: 'output-available',
                toolCallId: 'skill-1',
                input: { name: 'pptx' },
                output: 'skill instructions',
              },
            ],
          }) as any
        }
        isFirstMessage
        isLastMessage
        status={'streaming' as any}
      />
    )

    expect(
      screen.queryByLabelText('common:skillsUsedLabel')
    ).not.toBeInTheDocument()
  })

  /// A note the run folded in, not something either party said: the turn after
  /// it is a reply to it, and reads as a non sequitur on its own.
  it('renders a system note as a plain row, with no actions', () => {
    render(
      <MessageItem
        message={
          makeMsg({
            role: 'system',
            parts: [
              { type: 'text', text: "Subagent 'researcher' (c1) finished." },
            ],
          }) as any
        }
        isFirstMessage={false}
        isLastMessage
        status={'ready' as any}
        onEdit={vi.fn()}
        onDelete={vi.fn()}
      />
    )
    expect(
      screen.getByText("Subagent 'researcher' (c1) finished.")
    ).toBeInTheDocument()
    expect(screen.queryByTestId('edit-btn')).not.toBeInTheDocument()
    expect(screen.queryByTestId('delete-btn')).not.toBeInTheDocument()
  })

  it('hides progress while a tool call awaits approval', () => {
    pendingApprovalsRef.current = { tc1: {} }
    render(
      <MessageItem
        message={
          makeMsg({
            parts: [
              { type: 'tool-search', state: 'input-available', toolCallId: 'tc1', input: {} },
            ],
          }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
      />
    )
    expect(screen.queryByTestId('prompt-progress')).not.toBeInTheDocument()
  })

  it('keeps an earlier tool part visible while it awaits approval (multi-tool turn)', () => {
    // Two tool calls in one streaming turn; the first is awaiting approval.
    // Streaming truncation must not hide it, or its approve/deny controls
    // never mount and the run hangs.
    pendingApprovalsRef.current = { 'tc-alpha': {} }
    render(
      <MessageItem
        message={
          makeMsg({
            parts: [
              { type: 'tool-alpha', state: 'input-available', toolCallId: 'tc-alpha', input: {} },
              { type: 'tool-beta', state: 'input-available', toolCallId: 'tc-beta', input: {} },
            ],
          }) as any
        }
        isFirstMessage
        isLastMessage
        status={'streaming' as any}
      />
    )
    const headers = screen.getAllByTestId('tool-header').map((h) => h.textContent)
    expect(headers).toContain('alpha')
    expect(headers).toContain('beta')
  })

  it('still truncates a non-pending earlier tool step outside the frontier while streaming', () => {
    // No pending approval, and reasoning splits the two calls so they are not
    // one trailing batch: streaming truncation keeps only the current step
    // (the trailing tool), dropping the earlier tool that a step has moved past.
    pendingApprovalsRef.current = {}
    render(
      <MessageItem
        message={
          makeMsg({
            parts: [
              { type: 'tool-alpha', state: 'output-available', toolCallId: 'tc-alpha', input: {}, output: 'done' },
              { type: 'reasoning', text: 'now the next thing' },
              { type: 'tool-beta', state: 'input-available', toolCallId: 'tc-beta', input: {} },
            ],
          }) as any
        }
        isFirstMessage
        isLastMessage
        status={'streaming' as any}
      />
    )
    const headers = screen.getAllByTestId('tool-header').map((h) => h.textContent)
    expect(headers).not.toContain('alpha')
    expect(headers).toContain('beta')
  })

  it('passes full text to copy button', () => {
    render(
      <MessageItem
        message={
          makeMsg({
            parts: [
              { type: 'text', text: 'a' },
              { type: 'text', text: 'b' },
            ],
          }) as any
        }
        isFirstMessage
        isLastMessage
        status={'ready' as any}
      />
    )
    const copy = screen.getByTestId('copy-btn')
    expect(copy.getAttribute('data-text')).toBe('a\nb')
  })

  it.each(['user', 'assistant'])(
    'hides edit on a %s message when no selectedModel',
    (role) => {
      selectedModelRef.current = null
      render(
        <MessageItem
          message={makeMsg({ role }) as any}
          isFirstMessage
          isLastMessage
          status={'ready' as any}
          onEdit={vi.fn()}
        />
      )
      expect(screen.queryByTestId('edit-btn')).not.toBeInTheDocument()
    }
  )

  it('does not render regenerate button when no selectedModel', () => {
    selectedModelRef.current = null
    const onRegenerate = vi.fn()
    render(
      <MessageItem
        message={makeMsg() as any}
        isFirstMessage
        isLastMessage
        status={'ready' as any}
        onRegenerate={onRegenerate}
      />
    )
    expect(screen.queryByTitle('chat:actions.regenerate')).not.toBeInTheDocument()
  })

  describe('footer', () => {
    const renderAssistant = () =>
      render(
        <MessageItem
          message={makeMsg() as any}
          isFirstMessage
          isLastMessage
          status={'ready' as any}
          onRegenerate={vi.fn()}
        />
      )

    it('shows the compact time with the full date as its tooltip', () => {
      renderAssistant()
      const time = screen.getByText('3:30 PM')
      expect(time).toHaveAttribute('title', '2024-01-01 full')
      // A real <time> with a machine-readable stamp, not a titled span.
      expect(time.tagName).toBe('TIME')
      expect(time.getAttribute('datetime')).toMatch(/^\d{4}-\d{2}-\d{2}T/)
    })

    it('reveals secondary actions on hover only, with copy always visible', () => {
      renderAssistant()
      const regenerate = screen.getByTestId('regenerate-message')
      // Secondary actions sit in a hover-revealed group; copy does not.
      expect(regenerate.parentElement?.className).toContain('opacity-0')
      expect(regenerate.parentElement?.className).toContain(
        'group-hover/message:opacity-100'
      )
      // Keyboard users reach the same controls: focus inside reveals them.
      expect(regenerate.parentElement?.className).toContain(
        'group-has-[:focus-visible]/message:opacity-100'
      )
      const copy = screen.getByTestId('copy-btn')
      expect(copy.parentElement).not.toBeNull()
      expect(copy.parentElement!.className).not.toContain('opacity-0')
    })

    it('hides copy behind hover on an earlier message', () => {
      render(
        <MessageItem
          message={makeMsg() as any}
          isFirstMessage
          isLastMessage={false}
          status={'ready' as any}
        />
      )
      const copy = screen.getByTestId('copy-btn')
      expect(copy.parentElement?.className).toContain('opacity-0')
      expect(copy.parentElement?.className).toContain(
        'group-hover/message:opacity-100'
      )
    })

    it('keeps copy and the version switcher visible together when there are versions', () => {
      render(
        <MessageItem
          message={makeMsg() as any}
          isFirstMessage
          isLastMessage={false}
          status={'ready' as any}
          versionInfo={{ index: 1, count: 2 }}
          onSwitchVersion={vi.fn()}
        />
      )
      const copy = screen.getByTestId('copy-btn')
      expect(copy.parentElement!.className).not.toContain('opacity-0')
      const prev = screen.getByTestId('message-version-prev')
      expect(prev.closest('[class*="opacity-0"]')).toBeNull()
    })

    it('keeps Continue visible at rest on a stopped reply', () => {
      render(
        <MessageItem
          message={makeMsg({ metadata: { createdAt: new Date(), stopped: true } }) as any}
          isFirstMessage
          isLastMessage
          status={'ready' as any}
          onContinue={vi.fn()}
          onRegenerate={vi.fn()}
        />
      )
      // The only way to resume a stopped reply is not hidden behind hover...
      const cont = screen.getByTestId('continue-message')
      expect(cont.closest('[class*="opacity-0"]')).toBeNull()
      // ...while regenerate stays with the other hover-revealed actions.
      const regen = screen.getByTestId('regenerate-message')
      expect(regen.closest('[class*="opacity-0"]')).not.toBeNull()
    })

    it('shows every action on a touch device', () => {
      touchRef.current = true
      renderAssistant()
      const regenerate = screen.getByTestId('regenerate-message')
      expect(regenerate.parentElement?.className).toContain('opacity-100')
      expect(regenerate.parentElement?.className).not.toContain('opacity-0')
    })
  })

  // #9642: a failed llama.cpp load is the one place the user is holding the
  // question the hardware check answers, so that is where it is offered.
  describe('failed model load', () => {
    const show = (model?: string) => {
      useMessageErrors.getState().setError('msg-1', 'failed to load model')
      useMessageErrors
        .getState()
        .setReport('msg-1', '## Model load failure', model)
      render(
        <MessageItem
          message={makeMsg() as any}
          isFirstMessage
          isLastMessage
          status={'ready' as any}
        />
      )
    }

    beforeEach(() => useMessageErrors.getState().clearAll())

    it('offers the hardware check, carrying the model that failed', () => {
      show('m1')
      const link = screen.getByText('providers:diagnostics.checkThisModel')
      expect(link.getAttribute('data-search')).toBe(
        JSON.stringify({ diagnoseModel: 'm1' })
      )
    })

    // No recorded model means the turn did not run on llama.cpp, so the
    // llama.cpp model selected now has nothing to do with the failure.
    it('offers no check when the failed turn recorded no model', () => {
      show()
      expect(
        screen.queryByText('providers:diagnostics.checkThisModel')
      ).not.toBeInTheDocument()
    })

    // The message is read long after the user moved on, so the link has to
    // name the model that failed rather than whatever is selected now.
    it('checks the model that failed, not the one selected since', () => {
      show('qwen3-8b')
      selectedModelRef.current = { id: 'something-else' }
      const link = screen.getByText('providers:diagnostics.checkThisModel')
      expect(link.getAttribute('data-search')).toBe(
        JSON.stringify({ diagnoseModel: 'qwen3-8b' })
      )
    })
  })
})