Skip to content

The agent that grows with you

32.7 KB
Raw Blame
// Bug #2: the Branch-in-new-chat button used to render unconditionally even
// when its handler was a no-op (session-tile.tsx passed `() => undefined`
// for branched/tiled chats, where nested branching isn't supported). That
// left a visibly clickable button that silently did nothing. The fix makes
// AssistantMessage's action bar hide the button entirely when no handler is
// supplied, matching how onDismissError/onRestoreToMessage already behave.
import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router'
import { afterEach, describe, expect, it, vi } from 'vitest'

import { en } from '@/i18n/en'
import type { ErrorCardCopy } from '@/i18n/types'
import { $touchPointer } from '@/lib/touch-interaction'
import { $displayTimestamps } from '@/store/display-timestamps'
import { $activeSessionId } from '@/store/session'
import { type SessionTileDelegate, setSessionTileDelegate } from '@/store/session-states'

import { stubThreadEnvironment } from '../test-utils'

import { formatTimelineRange, formatTimelineTimestamp } from './timestamp'

import { Thread } from '.'

const requestFreshSession = vi.hoisted(() => vi.fn())
const startManualProviderOAuth = vi.hoisted(() => vi.fn())
const requestModelMenuToggle = vi.hoisted(() => vi.fn<() => boolean>(() => true))
const requestComposerSubmit = vi.hoisted(() => vi.fn<(text: string, options?: unknown) => boolean>(() => true))
const requestComposerInsert = vi.hoisted(() => vi.fn())
const openExternalLink = vi.hoisted(() => vi.fn())

vi.mock('@/lib/external-link', async importOriginal => ({
  ...(await importOriginal<Record<string, unknown>>()),
  openExternalLink: (href: string) => openExternalLink(href)
}))

vi.mock('@/app/chat/composer/focus', async importOriginal => ({
  ...(await importOriginal<Record<string, unknown>>()),
  requestComposerInsert: (text: string, options?: unknown) => requestComposerInsert(text, options),
  requestComposerSubmit: (text: string, options?: unknown) => requestComposerSubmit(text, options),
  requestModelMenuToggle: () => requestModelMenuToggle()
}))

vi.mock('@/store/profile', async importOriginal => ({
  ...(await importOriginal<Record<string, unknown>>()),
  requestFreshSession: () => requestFreshSession()
}))

vi.mock('@/store/onboarding', async importOriginal => ({
  ...(await importOriginal<Record<string, unknown>>()),
  startManualProviderOAuth: (...args: unknown[]) => startManualProviderOAuth(...args)
}))

// Timeline timestamps render only when `display.timestamps` is enabled.
$displayTimestamps.set(true)

// Resolve error-card copy from the catalog so wording edits don't break the behavior assertions.
const copy = (value: ErrorCardCopy['title'], provider = '') =>
  typeof value === 'function' ? value(provider, '') : value

const codes = en.assistant.thread.errorCodes

const createdAt = new Date('2026-05-01T00:00:00.000Z')
const completedAt = createdAt.getTime() / 1000 + 1.25
stubThreadEnvironment()

afterEach(() => {
  cleanup()
  requestFreshSession.mockClear()
  startManualProviderOAuth.mockClear()
  requestModelMenuToggle.mockReset().mockReturnValue(true)
  $displayTimestamps.set(true)
  $touchPointer.set(false)
  vi.unstubAllGlobals()
})

function userMessage(): ThreadMessage {
  return {
    id: 'user-1',
    role: 'user',
    content: [{ type: 'text', text: 'question one' }],
    attachments: [],
    createdAt,
    metadata: { custom: { timelineTimestamp: createdAt.getTime() / 1000 } }
  } as unknown as ThreadMessage
}

function assistantMessage(): ThreadMessage {
  return {
    id: 'assistant-1',
    role: 'assistant',
    content: [
      {
        type: 'reasoning',
        text: 'checked carefully',
        timestamp: createdAt.getTime() / 1000 + 0.05,
        completedAt: createdAt.getTime() / 1000 + 0.1
      },
      {
        type: 'text',
        text: 'done',
        timestamp: createdAt.getTime() / 1000 + 0.125,
        completedAt: createdAt.getTime() / 1000 + 0.5
      }
    ],
    status: { type: 'complete', reason: 'stop' },
    createdAt,
    metadata: {
      unstable_state: null,
      unstable_annotations: [],
      unstable_data: [],
      steps: [],
      custom: { timelineCompletedAt: completedAt, timelineTimestamp: createdAt.getTime() / 1000 }
    }
  } as unknown as ThreadMessage
}

function ownershipRefusalMessage(): ThreadMessage {
  return {
    id: 'assistant-error-1',
    role: 'assistant',
    content: [],
    status: {
      type: 'incomplete',
      reason: 'error',
      error:
        'Session 20260909_095312_6b93f5 already has a live owner (tui, pid 32977, lease age 22m). ' +
        'Attach through a compatible owner, or close the session in its owning surface before resuming here.'
    },
    createdAt,
    metadata: {
      unstable_state: null,
      unstable_annotations: [],
      unstable_data: [],
      steps: [],
      // What submit.ts stamps on a 4090 / SESSION_NOT_OWNED refusal.
      custom: { errorSurface: { layer: 'gateway', code: 'SESSION_NOT_OWNED', retryable: false } }
    }
  } as unknown as ThreadMessage
}

function oauthExpiredMessage(): ThreadMessage {
  return {
    id: 'assistant-error-2',
    role: 'assistant',
    content: [],
    status: { type: 'incomplete', reason: 'error', error: 'HTTP 401: User not found.' },
    createdAt,
    metadata: {
      unstable_state: null,
      unstable_annotations: [],
      unstable_data: [],
      steps: [],
      // What agent/error_surface.py stamps on a rejected OAuth grant.
      custom: {
        errorSurface: {
          authKind: 'oauth',
          code: 'auth',
          layer: 'auth',
          provider: 'nous',
          providerLabel: 'Nous Portal',
          retryable: false
        }
      }
    }
  } as unknown as ThreadMessage
}

/** A failed turn carrying an arbitrary error_surface descriptor. */
function failedMessage(errorSurface: Record<string, unknown>, error = 'HTTP 400: raw provider body'): ThreadMessage {
  return {
    id: 'assistant-error-3',
    role: 'assistant',
    content: [],
    status: { type: 'incomplete', reason: 'error', error },
    createdAt,
    metadata: {
      unstable_state: null,
      unstable_annotations: [],
      unstable_data: [],
      steps: [],
      custom: { errorSurface }
    }
  } as unknown as ThreadMessage
}

/** Renders the router's current URL so a test can assert where a deep link went. */
function LocationProbe() {
  const location = useLocation()

  return <span data-testid="location">{`${location.pathname}${location.search}`}</span>
}

function Harness({
  assistant = assistantMessage(),
  onBranchInNewChat,
  onCancel,
  onDismissError,
  onRestoreToMessage,
  onReload,
  isRunning = false,
  isDisabled = false
}: {
  assistant?: ThreadMessage
  onBranchInNewChat?: (messageId: string) => void
  onCancel?: () => void
  onDismissError?: (messageId: string) => void
  onRestoreToMessage?: (messageId: string) => void
  onReload?: () => Promise<void>
  isRunning?: boolean
  isDisabled?: boolean
}) {
  const runtime = useExternalStoreRuntime<ThreadMessage>({
    messages: [userMessage(), assistant],
    isRunning,
    isDisabled,
    onNew: async () => {},
    ...(onReload ? { onReload } : {})
  })

  return (
    <AssistantRuntimeProvider runtime={runtime}>
      <Thread
        onBranchInNewChat={onBranchInNewChat}
        onCancel={onCancel}
        onDismissError={onDismissError}
        onRestoreToMessage={onRestoreToMessage}
      />
    </AssistantRuntimeProvider>
  )
}

describe('merged hover timestamps and touch actions', () => {
  it('shows both hover times without Stop or Restore and suppresses them with timeline timestamps', async () => {
    $displayTimestamps.set(false)
    const { container } = render(<Harness />)
    await screen.findByText('done')

    const hoverTimes = Array.from(container.querySelectorAll('time'))

    expect(hoverTimes.map(time => time.dateTime)).toEqual([
      createdAt.toISOString(),
      new Date(completedAt * 1000).toISOString()
    ])
    expect(container.querySelector('.aui-message-actions-desktop time')).toBeTruthy()

    act(() => $displayTimestamps.set(true))
    expect(hoverTimes.every(time => !time.isConnected)).toBe(true)
    expect(container.querySelector('[data-slot="timeline-timestamp"]')).toBeTruthy()
  })

  it('mounts the touch More menu only while the pointer is coarse', async () => {
    render(<Harness />)
    await screen.findByText('done')
    expect(screen.queryByRole('button', { name: 'More actions' })).toBeNull()

    act(() => $touchPointer.set(true))
    expect(screen.getByRole('button', { name: 'More actions' })).toBeTruthy()
  })

  it.each([true, false])('keeps the touch Stop/Restore action correct while running=%s', async isRunning => {
    $touchPointer.set(true)
    $displayTimestamps.set(false)
    const onCancel = vi.fn()
    const onRestoreToMessage = vi.fn()
    render(<Harness isRunning={isRunning} onCancel={onCancel} onRestoreToMessage={onRestoreToMessage} />)

    const action = await screen.findByRole('button', {
      name: isRunning ? en.assistant.thread.stop : en.assistant.thread.restoreCheckpoint
    })

    expect(action.parentElement?.querySelector('time')).toBeNull()
    fireEvent.click(action)

    if (isRunning) {
      expect(onCancel).toHaveBeenCalledTimes(1)
      expect(onRestoreToMessage).not.toHaveBeenCalled()
    } else {
      expect(await screen.findByRole('dialog')).toBeTruthy()
      fireEvent.click(screen.getByRole('button', { name: en.assistant.thread.restoreConfirm }))
      expect(onRestoreToMessage).toHaveBeenCalledWith('user-1', expect.objectContaining({ text: 'question one' }))
      expect(onCancel).not.toHaveBeenCalled()
    }
  })
})

describe('AssistantMessage branch button visibility (bug #2 fix)', () => {
  it('reloads once from either desktop or touch Refresh', async () => {
    $touchPointer.set(true)
    const onReload = vi.fn(async () => {})
    render(<Harness onReload={onReload} />)
    fireEvent.click(await screen.findByRole('button', { name: 'Refresh' }))
    await waitFor(() => expect(onReload).toHaveBeenCalledTimes(1))
    onReload.mockClear()
    fireEvent.pointerDown(screen.getByRole('button', { name: 'More actions' }), { button: 0, pointerType: 'touch' })
    fireEvent.click(await screen.findByRole('menuitem', { name: 'Refresh' }))
    await waitFor(() => expect(onReload).toHaveBeenCalledTimes(1))
  })

  it.each([{ isRunning: true }, { isDisabled: true }])('guards both Refresh surfaces with %j', async state => {
    $touchPointer.set(true)
    const onReload = vi.fn(async () => {})
    render(<Harness onReload={onReload} {...state} />)
    expect((await screen.findByRole('button', { name: 'Refresh' })).hasAttribute('disabled')).toBe(true)
    fireEvent.pointerDown(screen.getByRole('button', { name: 'More actions' }), { button: 0, pointerType: 'touch' })
    const refresh = await screen.findByRole('menuitem', { name: 'Refresh' })
    expect(refresh.getAttribute('aria-disabled')).toBe('true')
    fireEvent.click(refresh)
    expect(onReload).not.toHaveBeenCalled()
  })
  it('shows the Branch in new chat button when a handler is provided (open chat)', async () => {
    render(<Harness onBranchInNewChat={() => undefined} />)

    expect(await screen.findByRole('button', { name: 'Branch in new chat' })).toBeTruthy()
  })

  it('hides the Branch in new chat button when no handler is provided (session-tile / branched chat)', async () => {
    render(<Harness />)

    // Wait for the assistant message to actually mount before asserting
    // absence, so a missing button isn't just a false negative from an
    // unrendered message.
    await screen.findByText('done')

    expect(screen.queryByRole('button', { name: 'Branch in new chat' })).toBeNull()
  })

  it('reaches Branch in new chat from the touch More menu', async () => {
    $touchPointer.set(true)
    render(<Harness onBranchInNewChat={() => undefined} />)

    await screen.findByText('done')

    fireEvent.pointerDown(screen.getByRole('button', { name: 'More actions' }), {
      button: 0,
      pointerType: 'touch'
    })

    expect(await screen.findByRole('menuitem', { name: 'Branch in new chat' })).toBeTruthy()
  })
})

describe('stopped reply marker', () => {
  it('marks a reply the user stopped', async () => {
    const base = assistantMessage()
    const stopped = { ...base, metadata: { ...base.metadata, custom: { interrupted: true } } } as ThreadMessage
    render(<Harness assistant={stopped} />)

    expect(await screen.findByText(en.assistant.thread.responseStopped)).toBeTruthy()
  })

  it('leaves a finished reply unmarked', async () => {
    render(<Harness />)
    await screen.findByText('done')

    expect(screen.queryByText(en.assistant.thread.responseStopped)).toBeNull()
  })
})

describe('ownership refusal recovery (#106217)', () => {
  it('offers Start new session and suppresses Retry for live-owner refusals', async () => {
    render(<Harness assistant={ownershipRefusalMessage()} />)

    expect(await screen.findByRole('button', { name: 'Start new session' })).toBeTruthy()
    expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull()

    screen.getByRole('button', { name: 'Start new session' }).click()
    expect(requestFreshSession).toHaveBeenCalledTimes(1)
  })

  it('demotes the raw lease text to the collapsed details', async () => {
    render(<Harness assistant={ownershipRefusalMessage()} />)

    // The raw refusal ("live owner", "pid", "lease") is kept only inside the
    // collapsed details block, never as the headline.
    const raw = await screen.findByText(/already has a live owner/)
    const details = raw.closest<HTMLElement>('[data-slot="aui_error-details"]')
    expect(details).not.toBeNull()
    expect(details!.hidden).toBe(true)
  })
})

describe('code-keyed error card copy and actions', () => {
  it('hides Retry and offers Edit message for a safety refusal', async () => {
    render(
      <Harness
        assistant={failedMessage({
          code: 'content_policy_blocked',
          layer: 'provider',
          provider: 'openai',
          retryable: false
        })}
      />
    )

    expect(await screen.findByText(copy(codes.content_policy_blocked.title, 'openai'))).toBeTruthy()

    // The user bubble itself is also labelled "Edit message"; assert on the
    // card's own action button.
    const editActions = screen
      .getAllByRole('button', { name: 'Edit message' })
      .filter(button => button.classList.contains('aui-error-btn'))

    expect(editActions).toHaveLength(1)
    expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull()
  })

  it('offers Choose a model and no Retry when the model is not available', async () => {
    render(
      <Harness
        assistant={failedMessage({ code: 'model_not_found', layer: 'provider', provider: 'openai', retryable: false })}
      />
    )

    expect(await screen.findByRole('button', { name: 'Choose a model' })).toBeTruthy()
    expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull()
    // The raw HTTP body is not the lead sentence.
    expect(screen.getByText(copy(codes.model_not_found.title))).toBeTruthy()
    expect(screen.getByText(/HTTP 400/).closest('[data-slot="aui_error-details"]')).not.toBeNull()
  })

  it('offers Compress conversation and Start new session for a context overflow', async () => {
    render(<Harness assistant={failedMessage({ code: 'context_overflow', layer: 'provider', retryable: true })} />)

    expect(await screen.findByText(copy(codes.context_overflow.title))).toBeTruthy()
    expect(screen.getByRole('button', { name: 'Compress conversation' })).toBeTruthy()
    expect(screen.getByRole('button', { name: en.assistant.thread.errorStartNewChatLink })).toBeTruthy()
    expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull()
  })

  it('names the provider and keeps Retry for a rate limit', async () => {
    render(
      <Harness
        assistant={failedMessage(
          { code: 'rate_limit', layer: 'provider', provider: 'openai', retryable: true },
          'HTTP 429: {"error":{"message":"Rate limit reached"}}'
        )}
      />
    )

    expect(await screen.findByText(copy(codes.rate_limit.title, 'openai'))).toBeTruthy()
    expect(screen.getByText(copy(codes.rate_limit.body, 'openai'))).toBeTruthy()
    expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy()
  })

  it('falls back to the generic headline when no descriptor was sent (older backend)', async () => {
    const legacy = {
      ...failedMessage({}),
      metadata: { unstable_state: null, unstable_annotations: [], unstable_data: [], steps: [], custom: {} }
    } as unknown as ThreadMessage

    render(<Harness assistant={legacy} />)

    expect(await screen.findByText(en.assistant.thread.errorLayers.generic)).toBeTruthy()
    expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy()
  })
})

describe('error card layout (Error System Overhaul)', () => {
  const rateLimited = () =>
    failedMessage({ code: 'rate_limit', layer: 'provider', provider: 'openai', retryable: true }, 'HTTP 429: slow down')

  it('reveals the raw error from the details toggle and hides it again', async () => {
    render(<Harness assistant={rateLimited()} />)

    const toggle = await screen.findByRole('button', { name: en.assistant.thread.errorDetails })
    const details = screen.getByText('HTTP 429: slow down').closest<HTMLElement>('[data-slot="aui_error-details"]')!

    expect(details.hidden).toBe(true)
    expect(toggle.getAttribute('aria-controls')).toBe(details.id)
    expect(toggle.getAttribute('aria-expanded')).toBe('false')

    fireEvent.click(toggle)
    expect(details.hidden).toBe(false)
    expect(toggle.getAttribute('aria-expanded')).toBe('true')
    expect(toggle.textContent).toBe(en.assistant.thread.errorHideDetails)

    fireEvent.click(toggle)
    expect(details.hidden).toBe(true)
  })

  it('lets the user close a degraded card but not a blocking one', async () => {
    const onDismissError = vi.fn()
    const view = render(<Harness assistant={rateLimited()} onDismissError={onDismissError} />)

    const card = await screen.findByRole('alert')
    expect(card.dataset.severity).toBe('degraded')
    fireEvent.click(screen.getByRole('button', { name: en.assistant.thread.dismissError }))
    expect(onDismissError).toHaveBeenCalledWith('assistant-error-3')
    view.unmount()

    render(
      <Harness
        assistant={failedMessage({ code: 'model_not_found', layer: 'provider', provider: 'openai', retryable: false })}
        onDismissError={onDismissError}
      />
    )

    expect((await screen.findByRole('alert')).dataset.severity).toBe('blocking')
    expect(screen.queryByRole('button', { name: en.assistant.thread.dismissError })).toBeNull()
  })

  it('Continue sends "continue" through this chat\'s composer, or leaves it in the input', async () => {
    const truncated = () => failedMessage({ code: 'truncated', layer: 'provider', provider: 'openai', retryable: true })
    const view = render(<Harness assistant={truncated()} />)

    fireEvent.click(await screen.findByRole('button', { name: en.assistant.thread.errorContinue }))
    expect(requestComposerSubmit).toHaveBeenCalledWith('continue', { target: 'main' })
    expect(requestComposerInsert).not.toHaveBeenCalled()
    view.unmount()

    requestComposerSubmit.mockReturnValueOnce(false)
    render(<Harness assistant={truncated()} />)
    fireEvent.click(await screen.findByRole('button', { name: en.assistant.thread.errorContinue }))
    expect(requestComposerInsert).toHaveBeenCalledWith('continue', { target: 'main' })
  })

  it('names an out-of-credits turn on its card too: the banner may be off screen', async () => {
    render(
      <MemoryRouter>
        <Harness assistant={failedMessage({ code: 'billing', layer: 'billing', provider: 'nous', retryable: false })} />
      </MemoryRouter>
    )

    expect(await screen.findByRole('button', { name: en.assistant.thread.errorOpenBillingSettings })).toBeTruthy()
  })

  it("opens the failing provider's own billing page from this chat's billing wall", async () => {
    const { $activeSessionId } = await import('@/store/session')
    const { clearBillingBlock, setBillingBlock } = await import('@/store/billing-block')
    $activeSessionId.set('wall-session')
    setBillingBlock('wall-session', {
      billing_url: 'https://platform.openai.com/settings/organization/billing',
      is_nous: false,
      message: 'out of credits',
      provider: 'openai',
      provider_label: 'OpenAI'
    } as never)

    try {
      render(
        <MemoryRouter>
          <Harness
            assistant={failedMessage({ code: 'billing', layer: 'billing', provider: 'openai', retryable: false })}
          />
        </MemoryRouter>
      )

      fireEvent.click(await screen.findByRole('button', { name: en.assistant.thread.errorOpenBillingSettings }))
      expect(openExternalLink).toHaveBeenCalledWith('https://platform.openai.com/settings/organization/billing')
    } finally {
      clearBillingBlock()
      $activeSessionId.set(null)
    }
  })

  it('never retargets an older card at a later wall from another provider in the same chat', async () => {
    openExternalLink.mockClear()
    const { $activeSessionId } = await import('@/store/session')
    const { clearBillingBlock, setBillingBlock } = await import('@/store/billing-block')
    $activeSessionId.set('wall-session')
    setBillingBlock('wall-session', {
      billing_url: 'https://platform.openai.com/settings/organization/billing',
      is_nous: false,
      message: 'out of credits',
      model: 'gpt-5',
      provider: 'openai',
      provider_label: 'OpenAI'
    })

    try {
      render(
        <MemoryRouter>
          <Harness
            assistant={failedMessage({ code: 'billing', layer: 'billing', provider: 'nous', retryable: false })}
          />
        </MemoryRouter>
      )

      fireEvent.click(await screen.findByRole('button', { name: en.assistant.thread.errorOpenBillingSettings }))
      expect(openExternalLink).not.toHaveBeenCalled()
    } finally {
      clearBillingBlock()
      $activeSessionId.set(null)
    }
  })

  it("never sends a third-party provider's credit failure to Nous billing without its billing link", async () => {
    render(
      <MemoryRouter>
        <Harness
          assistant={failedMessage({ code: 'billing', layer: 'billing', provider: 'openai', retryable: false })}
        />
      </MemoryRouter>
    )

    expect(await screen.findByRole('button', { name: en.assistant.thread.errorSwitchProvider })).toBeTruthy()
    expect(screen.queryByRole('button', { name: en.assistant.thread.errorOpenBillingSettings })).toBeNull()
  })
})

describe('scheduled retry at the usage-limit reset (#98852)', () => {
  const rateLimited = (resetsAt: number) =>
    failedMessage(
      { code: 'rate_limit', layer: 'provider', provider: 'openai', resetsAt, retryable: true },
      'HTTP 429: {"error":{"message":"Rate limit reached"}}'
    )

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

  it('fires the same reload as Retry exactly once, at resets_at and not before', async () => {
    const onReload = vi.fn(async () => {})
    const resetsAt = Math.floor(Date.now() / 1000) + 600

    render(<Harness assistant={rateLimited(resetsAt)} onReload={onReload} />)

    const arm = await screen.findByRole('button', { name: /^Retry at \d\d:\d\d$/ })

    vi.useFakeTimers()
    fireEvent.click(arm)

    expect(screen.getByTestId('error-retry-scheduled').textContent).toMatch(/Retrying at \d\d:\d\d — in \d+m \d\ds/)
    expect(screen.queryByRole('button', { name: /^Retry at / })).toBeNull()

    await act(async () => vi.advanceTimersByTime(resetsAt * 1000 - Date.now() - 1_000))
    expect(onReload).not.toHaveBeenCalled()

    await act(async () => vi.advanceTimersByTime(1_000))
    expect(onReload).toHaveBeenCalledTimes(1)

    await act(async () => vi.advanceTimersByTime(3_600_000))
    expect(onReload).toHaveBeenCalledTimes(1)
  })

  it('never fires after Cancel or unmount, and hides the button once the reset has passed', async () => {
    const onReload = vi.fn(async () => {})
    const resetsAt = Math.floor(Date.now() / 1000) + 600

    const view = render(<Harness assistant={rateLimited(resetsAt)} onReload={onReload} />)
    const armName = /^Retry at /

    fireEvent.click(await screen.findByRole('button', { name: armName }))
    vi.useFakeTimers()
    fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
    expect(screen.queryByTestId('error-retry-scheduled')).toBeNull()

    fireEvent.click(screen.getByRole('button', { name: armName }))
    view.unmount()

    await act(async () => vi.advanceTimersByTime(3_600_000))
    expect(onReload).not.toHaveBeenCalled()
    vi.useRealTimers()

    render(<Harness assistant={rateLimited(Math.floor(Date.now() / 1000) - 60)} onReload={onReload} />)
    expect(await screen.findByRole('button', { name: 'Retry' })).toBeTruthy()
    expect(screen.queryByRole('button', { name: armName })).toBeNull()
  })
})

describe("a window plan's limit: one-click switch and credits (no silent switch)", () => {
  const limitMessage = (credits: 'add_credits' | 'use_credits', suggestions = true) =>
    failedMessage(
      {
        code: 'usage_window',
        layer: 'billing',
        message: "You've hit your daily limit · resets 15:56",
        provider: 'nous',
        retryable: true,
        // The parsed surface (lib/error-surface.ts parseUsageLimit), as chat-runtime stores it.
        usageLimit: {
          credits,
          suggestions: suggestions
            ? [{ label: 'Model Free', model: 'example/model-free:free', note: 'free', provider: 'nous' }]
            : []
        }
      },
      'HTTP 402: usage window'
    )

  afterEach(() => {
    $activeSessionId.set(null)
  })

  it('switches THIS session to the recommended model, then re-runs the turn', async () => {
    const switchSessionModel = vi.fn(async () => true)
    const onReload = vi.fn(async () => {})
    setSessionTileDelegate({ switchSessionModel } as unknown as SessionTileDelegate)
    $activeSessionId.set('rt-1')

    render(
      <MemoryRouter>
        <Harness assistant={limitMessage('add_credits')} onReload={onReload} />
      </MemoryRouter>
    )

    fireEvent.click(await screen.findByRole('button', { name: 'Switch to Model Free (free)' }))

    await waitFor(() => expect(onReload).toHaveBeenCalledTimes(1))
    expect(switchSessionModel).toHaveBeenCalledWith('rt-1', 'example/model-free:free', 'nous')
    // No balance: the credits way on is Billing, labelled for what it does.
    expect(screen.getByRole('button', { name: 'Open billing settings' })).toBeTruthy()
    expect(screen.queryByRole('button', { name: 'Turn on Keep going on credits' })).toBeNull()
    // The generic provider menu is replaced by the one-click switch.
    expect(screen.queryByRole('button', { name: 'Switch provider' })).toBeNull()
  })

  it('re-runs nothing while the switch is unconfirmed or the user keeps the current model', async () => {
    // The gateway asked to confirm a guarded target and the user kept the current model.
    const switchSessionModel = vi.fn(async () => false)
    const executeSlash = vi.fn(async () => {})
    const onReload = vi.fn(async () => {})
    setSessionTileDelegate({ executeSlash, switchSessionModel } as unknown as SessionTileDelegate)
    $activeSessionId.set('rt-1')

    render(
      <MemoryRouter>
        <Harness assistant={limitMessage('add_credits')} onReload={onReload} />
      </MemoryRouter>
    )

    fireEvent.click(await screen.findByRole('button', { name: 'Switch to Model Free (free)' }))
    await act(async () => {
      await new Promise(resolve => setTimeout(resolve, 0))
    })

    expect(onReload).not.toHaveBeenCalled()
  })

  it('with a balance and Keep going off, offers to turn on Keep going (a lasting setting)', async () => {
    render(
      <MemoryRouter>
        <Harness assistant={limitMessage('use_credits')} />
      </MemoryRouter>
    )

    expect(await screen.findByRole('button', { name: 'Turn on Keep going on credits' })).toBeTruthy()
    expect(screen.getByRole('button', { name: 'Switch to Model Free (free)' })).toBeTruthy()
  })

  it('with no model to offer, still points at choosing one', async () => {
    render(
      <MemoryRouter>
        <Harness assistant={limitMessage('add_credits', false)} />
      </MemoryRouter>
    )

    expect(await screen.findByRole('button', { name: 'Open billing settings' })).toBeTruthy()
    expect(screen.queryByRole('button', { name: /^Switch to / })).toBeNull()
  })
})

describe('rejected API key recovery', () => {
  it('names the key as the problem and deep-links Settings → Keys to that env var', async () => {
    render(
      <MemoryRouter>
        <LocationProbe />
        <Harness
          assistant={failedMessage(
            {
              apiKeyEnv: 'OPENAI_API_KEY',
              authKind: 'api_key',
              code: 'auth',
              layer: 'auth',
              provider: 'openai',
              providerLabel: 'OpenAI',
              retryable: false
            },
            'HTTP 401: {"error":{"message":"Incorrect API key provided: sk-…"}}'
          )}
        />
      </MemoryRouter>
    )

    expect(await screen.findByText(copy(en.assistant.thread.errorAuthKinds.api_key.title, 'OpenAI'))).toBeTruthy()
    // Fixing the key changes the outcome, so Retry stays as the follow-up click.
    expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy()

    screen.getByRole('button', { name: 'Update API key' }).click()
    await waitFor(() =>
      expect(screen.getByTestId('location').textContent).toMatch(/\?tab=providers&pview=keys&key=OPENAI_API_KEY$/)
    )
  })
})

describe('switch provider on a live session (#95066)', () => {
  const billingFailure = () =>
    // Out of credits is banner-only now, so a firewall block stands in for a card whose fix is another provider.
    failedMessage(
      { code: 'upstream_blocked', layer: 'provider', provider: 'openai-codex', retryable: false },
      'HTTP 403: blocked'
    )

  it('opens the live session model menu instead of leaving the chat for Settings', async () => {
    render(
      <MemoryRouter>
        <LocationProbe />
        <Harness assistant={billingFailure()} />
      </MemoryRouter>
    )

    const button = await screen.findByRole('button', { name: 'Switch provider' })
    const before = screen.getByTestId('location').textContent

    button.click()

    expect(requestModelMenuToggle).toHaveBeenCalledTimes(1)
    // Still on the chat: the pick lands on THIS session through model.switch.
    expect(screen.getByTestId('location').textContent).toBe(before)
  })

  it('falls back to Settings → Models only when no chat surface is on screen', async () => {
    requestModelMenuToggle.mockReturnValue(false)
    render(
      <MemoryRouter>
        <LocationProbe />
        <Harness assistant={billingFailure()} />
      </MemoryRouter>
    )

    ;(await screen.findByRole('button', { name: 'Switch provider' })).click()

    expect(requestModelMenuToggle).toHaveBeenCalledTimes(1)
    await waitFor(() => expect(screen.getByTestId('location').textContent).toMatch(/\?tab=config:model$/))
  })
})

describe('expired OAuth grant recovery', () => {
  it('explains the expiry and re-runs that provider sign-in in one click', async () => {
    render(<Harness assistant={oauthExpiredMessage()} />)

    expect(await screen.findByText(/Nous Portal sign-in expired/)).toBeTruthy()
    // Signing in changes the outcome, so Retry stays as the follow-up click.
    expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy()

    screen.getByRole('button', { name: 'Sign in to Nous Portal again' }).click()
    expect(startManualProviderOAuth).toHaveBeenCalledWith('nous', undefined)
  })
})

describe('message timeline timestamps', () => {
  it('always renders precise user and assistant lifecycle times', async () => {
    const { container } = render(<Harness />)

    await screen.findByText('done')

    const stamps = Array.from(container.querySelectorAll('[data-slot="timeline-timestamp"]')).map(node =>
      node.textContent?.trim()
    )

    const startedAt = createdAt.getTime() / 1000

    expect(stamps).toContain(formatTimelineTimestamp(startedAt))
    expect(stamps).toContain(formatTimelineRange(startedAt, completedAt))
    expect(stamps).toContain(formatTimelineRange(startedAt + 0.05, startedAt + 0.1))
    expect(stamps).toContain(formatTimelineRange(startedAt + 0.125, startedAt + 0.5))
  })

  it('suppresses an aggregate assistant stamp that exactly duplicates its sole part', async () => {
    const startedAt = createdAt.getTime() / 1000

    const assistant = {
      ...assistantMessage(),
      content: [{ completedAt, text: 'done', timestamp: startedAt, type: 'text' }]
    } as unknown as ThreadMessage

    const { container } = render(<Harness assistant={assistant} />)

    await screen.findByText('done')

    const stamps = Array.from(container.querySelectorAll('[data-slot="timeline-timestamp"]')).map(node =>
      node.textContent?.trim()
    )

    expect(stamps.filter(stamp => stamp === formatTimelineRange(startedAt, completedAt))).toHaveLength(1)
  })
})