Skip to content

The agent that grows with you

26.5 KB
Raw Blame
vi.mock('@/store/profile', async (): Promise<object> => {
  const { atom } = await import('nanostores')

  return {
    $activeGatewayProfile: atom<string>('default'),
    $profiles: atom<Array<{ name: string; is_default?: boolean }>>([]),
    normalizeProfileKey: (profile: string | null): string => profile || 'default'
  }
})
vi.mock('@/store/session', async (): Promise<object> => {
  const { atom } = await import('nanostores')

  return { $connection: atom(null), $defaultReasoningEffort: atom<string>('') }
})

import { QueryClientProvider } from '@tanstack/react-query'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router'
import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from 'vitest'

import { I18nProvider } from '@/i18n'
import { queryClient } from '@/lib/query-client'
import { localModelsKey, localModelsOwner, watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'
import type { LocalCatalogModel, LocalHardware, LocalModelsStatus, LocalRuntimeJob } from '@/types/hermes'

import { LocalModelsSettings } from './local-models-settings'

// Mock the API layer — the pane's contract is what it RENDERS from these
// payloads, not transport.
vi.mock('@/hermes', () => ({
  activateLocalModel: vi.fn(),
  deleteLocalModel: vi.fn(),
  downloadBrowsedModel: vi.fn(),
  downloadLocalModel: vi.fn(),
  ejectLocalModel: vi.fn(),
  getLocalCatalog: vi.fn(),
  getLocalHardware: vi.fn(),
  getLocalModelsJobs: vi.fn(),
  getLocalModelsStatus: vi.fn(),
  getLocalRuntimeJob: vi.fn(),
  // The page imports the profile store (settings-scope chip), whose module
  // body subscribes $activeGatewayProfile → setApiRequestProfile at load.
  getProfiles: vi.fn(async () => ({ profiles: [] })),
  installLocalRuntime: vi.fn(),
  listHFRepoFiles: vi.fn(),
  pauseLocalDownload: vi.fn(),
  quickstartLocalModels: vi.fn(),
  resumeLocalDownload: vi.fn(),
  searchHFModels: vi.fn(),
  setApiRequestProfile: vi.fn(),
  sideloadLocalModel: vi.fn()
}))

import * as hermes from '@/hermes'

const mocked = vi.mocked(hermes)

const BASE_STATUS: LocalModelsStatus = {
  enabled: true,
  tag: 'b10290',
  configured_tag: 'b10290',
  update_available: false,
  runtime_installed: false,
  runtime_backend: null,
  server_running: false,
  server_base_url: null,
  active_model_id: null,
  loaded_models: {},
  models: [],
  models_dir: 'C:/somewhere/models'
}

const BASE_HARDWARE: LocalHardware = {
  uma: false,
  vram_total_bytes: 32 * 2 ** 30,
  vram_usable_bytes: 26 * 2 ** 30,
  ram_total_bytes: 256 * 2 ** 30,
  ram_available_bytes: 200 * 2 ** 30,
  vram_label: '32.0 GB',
  gpu_name: 'NVIDIA GeForce RTX 5090',
  gpu_util_percent: 12,
  vram_used_bytes: 6 * 2 ** 30
}

const FITTING_MODEL: LocalCatalogModel = {
  id: 'Qwen3.6-27B-UD-Q4_K_XL',
  display_name: 'Qwen3.6 27B',
  description: 'Best all-round agent model; long context stays fast',
  size_bytes: 17.6 * 2 ** 30,
  size_label: '17.6 GB',
  native_context: 262144,
  native_context_label: '256K',
  recommended: true,
  downloaded: false,
  mtp: false,
  fits: true,
  fit_summary: 'runs at its full 256K context',
  start_window: 262144,
  start_window_label: '256K',
  spilled: false
}

const SPILLED_MODEL: LocalCatalogModel = {
  ...FITTING_MODEL,
  id: 'Spilled-Model',
  display_name: 'Spilled Model',
  recommended: false,
  fits: true,
  spilled: true,
  start_window: 65536,
  start_window_label: '64K',
  fit_summary: 'starts at 64K and grows toward 256K as you use it (larger than your GPU memory — runs slower)'
}

const REFUSED_MODEL: LocalCatalogModel = {
  ...FITTING_MODEL,
  id: 'Huge-Model',
  display_name: 'Huge Model',
  recommended: false,
  fits: false,
  fit_summary: 'Needs more memory than this machine has',
  fit_detail: 'needs ~60 GiB at the 64K floor',
  start_window: undefined,
  start_window_label: undefined
}

function setInstallStarting(starting: boolean): void {
  queryClient.getMutationCache().clear()

  if (starting) {
    queryClient
      .getMutationCache()
      .build(queryClient, {
        mutationKey: localModelsKey(localModelsOwner(), 'install'),
        mutationFn: (): Promise<void> => new Promise<void>((): void => {})
      })
      .execute(undefined)
  }
}

function renderPane() {
  return render(
    <QueryClientProvider client={queryClient}>
      <MemoryRouter>
        <I18nProvider>
          <LocalModelsSettings />
        </I18nProvider>
      </MemoryRouter>
    </QueryClientProvider>
  )
}

// The fresh-machine states these tests exercise now lead with the
// quickstart card; the full pane (runtime rows, model list, browser)
// is one 'Let me choose' click away. Render and click through.
async function renderFullPane(): Promise<ReturnType<typeof renderPane>> {
  const result: ReturnType<typeof renderPane> = renderPane()

  // Wait for status to load: the pane either shows the setup card (click
  // through to the full pane) or, when an active runtime/model job routes
  // straight to the full pane, the runtime section directly.
  await waitFor((): void => {
    expect(
      Boolean(screen.queryByRole('button', { name: /let me choose/i })) ||
        screen.queryAllByText(/this machine/i).length > 0
    ).toBe(true)
  })

  const configure: HTMLElement | null = screen.queryByRole('button', { name: /let me choose/i })

  if (configure) {
    fireEvent.click(configure)
  }

  return result
}

beforeEach((): void => {
  queryClient.clear()
  queryClient.setDefaultOptions({ queries: { ...queryClient.getDefaultOptions().queries, retry: false } })
  mocked.getLocalModelsStatus.mockResolvedValue(BASE_STATUS)
  mocked.getLocalHardware.mockResolvedValue(BASE_HARDWARE)
  mocked.getLocalCatalog.mockResolvedValue({ models: [FITTING_MODEL, SPILLED_MODEL, REFUSED_MODEL] })
  // The backend mock ECHOES the atom: the watcher's immediate poll reads
  // seeded jobs instead of wiping them with a default {jobs:[]}.
  mocked.getLocalModelsJobs.mockImplementation(async () => ({
    jobs: [...(queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? [])]
  }))
  queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [])
})

afterEach(async () => {
  cleanup()
  queryClient.clear()
  mocked.getLocalModelsJobs.mockResolvedValue({ jobs: [] })
  await act(async () => {
    watchLocalRuntimeJobs()
  })
  vi.clearAllMocks()
  // A running job arms the store's 700ms re-poll; drain it so the timer cannot
  // fire into a torn-down test environment.
  queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [])
})

describe('LocalModelsSettings', () => {
  it.each(['starting', 'running'])(
    'keeps the runtime update view visible with no staged models while %s',
    async phase => {
      mocked.getLocalModelsStatus.mockResolvedValue({ ...BASE_STATUS, runtime_installed: true, update_available: true })

      const jobs: LocalRuntimeJob[] =
        phase === 'running'
          ? [
              {
                job_id: 'engine-update',
                kind: 'runtime-install',
                target: 'target',
                model_id: null,
                status: 'running',
                phase: 'downloading',
                detail: 'Downloading engine archive',
                total_bytes: 100,
                done_bytes: 40,
                percent: 40,
                error: null
              }
            ]
          : []

      mocked.getLocalModelsJobs.mockResolvedValue({ jobs })
      queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), jobs)
      setInstallStarting(phase === 'starting')
      renderPane()
      await screen.findByText('Qwen3.6 27B')
      const setup = screen.queryByRole('button', { name: /set up for me/i })

      const detail =
        phase === 'running'
          ? screen.queryByText('Downloading engine archive')
          : screen.queryByRole('button', { name: /update engine/i })

      act(() => setInstallStarting(false))
      expect(setup).toBeNull()
      expect(detail).toBeTruthy()
    }
  )
  it('keeps a failed explicit update visible with a direct retry and no staged models', async () => {
    mocked.getLocalModelsStatus.mockResolvedValue({ ...BASE_STATUS, runtime_installed: true, update_available: true })
    setInstallStarting(true)
    const view = renderPane()
    await screen.findByRole('button', { name: /update engine/i })

    const failed: LocalRuntimeJob = {
      job_id: 'failed-update',
      total_bytes: null,
      done_bytes: 0,
      kind: 'runtime-install',
      target: 'target',
      model_id: null,
      status: 'error',
      phase: 'download',
      detail: '',
      error: 'Engine archive unavailable'
    }

    mocked.getLocalModelsJobs.mockResolvedValue({ jobs: [failed] })
    act(() => {
      queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [failed])
      setInstallStarting(false)
    })
    expect(screen.queryByRole('button', { name: /set up for me/i })).toBeNull()
    expect(await screen.findByText('Engine archive unavailable')).toBeTruthy()
    view.unmount()
    renderPane()
    const retry = await screen.findByRole('button', { name: /update engine/i })
    expect((retry as HTMLButtonElement).disabled).toBe(false)
    mocked.installLocalRuntime.mockResolvedValue({ backend: 'cpu', job_id: 'retry', tag: 'next' })
    fireEvent.click(retry)
    await waitFor(() => expect(mocked.installLocalRuntime).toHaveBeenCalledTimes(1))
  })
  it('starts runtime installation only once while the request is pending', async () => {
    let finish!: (value: { backend: string; job_id: string; tag: string }) => void
    mocked.installLocalRuntime.mockImplementation(
      () =>
        new Promise(resolve => {
          finish = resolve
        })
    )
    await renderFullPane()
    const button = screen.getByRole('button', { name: /install runtime/i })
    fireEvent.click(button)
    fireEvent.click(button)
    await waitFor((): void => expect(mocked.installLocalRuntime).toHaveBeenCalledTimes(1))
    expect((button as HTMLButtonElement).disabled).toBe(true)
    await act(async () => {
      finish({ backend: 'cpu', job_id: 'install', tag: 'next' })
    })
  })

  it('orders the catalog by fit: resident first, then spilled, then too-big', async () => {
    // Scrambled input — the pane, not the backend, owns display order.
    mocked.getLocalCatalog.mockResolvedValue({ models: [REFUSED_MODEL, SPILLED_MODEL, FITTING_MODEL] })
    await renderFullPane()
    await screen.findByText('Qwen3.6 27B')

    // The matched element is the row-title span; the recommended row's
    // includes its nested pill copy — strip it before comparing order.
    const names = screen
      .getAllByText(/^(Qwen3\.6 27B|Spilled Model|Huge Model)$/)
      .map(el => el.textContent?.replace('Recommended', ''))

    expect(names).toEqual(['Qwen3.6 27B', 'Spilled Model', 'Huge Model'])
  })

  it('explains the Recommended pick on hover', async () => {
    // The tooltip is the resolver's own reason, and it must actually OPEN:
    // Tip works by asChild-cloning hover handlers onto the pill, so a Pill
    // that swallows its rest props kills the tooltip silently (the pill
    // still renders, nothing appears on hover).
    mocked.getLocalCatalog.mockResolvedValue({
      models: [{ ...FITTING_MODEL, recommended_reason: 'speed-gated-quality' }]
    })
    await renderFullPane()
    await screen.findByText('Qwen3.6 27B')

    fireEvent.pointerMove(screen.getByText('Recommended'))
    fireEvent.pointerEnter(screen.getByText('Recommended'))

    await waitFor(() =>
      expect(screen.getAllByText(/would respond too slowly on its memory bandwidth/).length).toBeGreaterThan(0)
    )
  })

  it('enables downloads only once the runtime is installed', async () => {
    mocked.getLocalModelsStatus.mockResolvedValue({
      ...BASE_STATUS,
      runtime_installed: true,
      runtime_backend: 'cuda'
    })
    await renderFullPane()

    await screen.findByText('Qwen3.6 27B')
    const [fittingButton] = screen.getAllByRole('button', { name: /download · 17\.6 GB/i })
    expect((fittingButton as HTMLButtonElement).disabled).toBe(false)
  })

  it('tracks a download job to completion and refreshes', async () => {
    mocked.getLocalModelsStatus.mockResolvedValue({
      ...BASE_STATUS,
      runtime_installed: true,
      runtime_backend: 'cuda'
    })
    mocked.downloadLocalModel.mockResolvedValue({ job_id: 'j1' })

    const running: LocalRuntimeJob = {
      job_id: 'j1',
      kind: 'model-download',
      target: 'Qwen3.6 27B',
      model_id: FITTING_MODEL.id,
      status: 'running',
      phase: 'downloading',
      detail: 'Qwen3.6 27B — 17.6 GB',
      total_bytes: 100,
      done_bytes: 40,
      percent: 40,
      error: null
    }

    mocked.getLocalModelsJobs
      .mockResolvedValueOnce({ jobs: [running] })
      .mockResolvedValue({ jobs: [{ ...running, status: 'done', phase: 'done', done_bytes: 100, percent: 100 }] })

    await renderFullPane()
    await screen.findByText('Qwen3.6 27B')

    const [download] = screen.getAllByRole('button', { name: /download · 17\.6 GB/i })
    download.click()

    // The app-level watcher follows the job; when it settles the pane
    // refreshes (status + catalog re-fetched).
    await waitFor(() => {
      expect(mocked.getLocalModelsJobs).toHaveBeenCalled()
      expect(mocked.getLocalModelsStatus.mock.calls.length).toBeGreaterThanOrEqual(2)
    })
  })

  it('renders progress for a download discovered from the store (survives pane remount)', async () => {
    mocked.getLocalModelsStatus.mockResolvedValue({
      ...BASE_STATUS,
      runtime_installed: true,
      runtime_backend: 'cuda'
    })
    // A running job already in the app-level store — as after closing and
    // reopening the pane mid-download.
    queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
      {
        job_id: 'j9',
        kind: 'model-download',
        target: 'Qwen3.6 27B',
        model_id: FITTING_MODEL.id,
        status: 'running',
        phase: 'downloading',
        detail: '',
        total_bytes: 100,
        done_bytes: 62,
        percent: 62,
        error: null
      }
    ])

    await renderFullPane()
    await screen.findByText('Qwen3.6 27B')

    // The fitting row shows byte progress; the remaining download
    // buttons belong to the other rows (spilled + refused).
    expect(screen.getAllByText(/0\.0 GB of 0\.0 GB|of/).length).toBeGreaterThan(0)
    const remaining = screen.queryAllByRole('button', { name: /download · 17\.6 GB/i })
    expect(remaining.length).toBe(2)
    expect(remaining.some(b => (b as HTMLButtonElement).disabled)).toBe(true)
  })

  it('surfaces a failed download with the backend message', async () => {
    mocked.getLocalModelsStatus.mockResolvedValue({
      ...BASE_STATUS,
      runtime_installed: true,
      runtime_backend: 'cuda'
    })
    queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
      {
        job_id: 'j2',
        kind: 'model-download',
        target: 'Qwen3.6 27B',
        model_id: FITTING_MODEL.id,
        status: 'error',
        phase: 'verifying',
        detail: '',
        total_bytes: 100,
        done_bytes: 100,
        error: 'Downloaded file failed its integrity check and was removed — try again'
      }
    ])

    await renderFullPane()
    await screen.findByText('Qwen3.6 27B')

    expect(await screen.findByText(/integrity check/)).toBeTruthy()
  })
})

describe('quickstart', () => {
  it('leads with one button on a fresh machine and fires the quickstart job', async () => {
    mocked.quickstartLocalModels.mockResolvedValue({
      display_name: 'Qwen3.6 27B',
      download_bytes: FITTING_MODEL.size_bytes,
      job_id: 'q1',
      model_id: 'qwen3.6-27b',
      needs_download: true,
      needs_runtime: true
    })
    renderPane()

    // The card names the recommended model and the one-click action; the
    // runtime/model machinery is NOT on screen.
    expect(await screen.findByRole('button', { name: /set up for me/i })).toBeTruthy()
    expect(screen.queryByText('Install the local runtime')).toBeNull()

    fireEvent.click(screen.getByRole('button', { name: /set up for me/i }))
    await waitFor(() => {
      expect(mocked.quickstartLocalModels).toHaveBeenCalled()
    })
  })

  it('pins the quickstart progress view while the job runs', async () => {
    queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
      {
        job_id: 'q1',
        kind: 'quickstart',
        target: 'Qwen3.6 27B',
        model_id: 'qwen3.6-27b',
        status: 'running',
        phase: 'downloading',
        detail: 'Qwen3.6 27B — 17.6 GB',
        total_bytes: 100,
        done_bytes: 30,
        percent: 30,
        error: null
      }
    ])
    renderPane()

    // The hero names the model and shows the composed status line
    // (state · bytes · speed · ETA) while the job runs; the raw backend
    // detail is only the lead when there are no bytes to report yet.
    expect(await screen.findByText('Qwen3.6 27B')).toBeTruthy()
    expect(await screen.findByText(/^Downloading · /)).toBeTruthy()
    // One job, one view: no setup or model-choice buttons while it runs.
    expect(screen.queryByRole('button', { name: /set up for me/i })).toBeNull()
  })

  it('skips the card entirely once a model is staged', async () => {
    mocked.getLocalModelsStatus.mockResolvedValue({
      ...BASE_STATUS,
      runtime_installed: true,
      runtime_backend: 'cuda',
      models: [{ id: 'Qwen3.6-27B-UD-Q4_K_XL', size_bytes: 17 * 2 ** 30, size_label: '17.6 GB' }]
    })
    renderPane()

    // Straight to the full pane — no quickstart hero for a working setup.
    expect(await screen.findByText('Qwen3.6 27B')).toBeTruthy()
    expect(screen.queryByRole('button', { name: /set up for me/i })).toBeNull()
  })
})

describe('BrowseSection', () => {
  it('keeps manual spill selection and HF browsing available without an automatic recommendation', async (): Promise<void> => {
    const stagedId: string = 'Spilled-Model-Q4_K_M'
    mocked.getLocalModelsStatus.mockResolvedValue({ ...BASE_STATUS, runtime_installed: true })
    mocked.getLocalCatalog.mockResolvedValue({ models: [SPILLED_MODEL] })
    renderPane()

    await screen.findByText('Spilled Model')
    expect(screen.getByText('No automatic recommendation for this machine')).toBeTruthy()
    expect(screen.getByText('Uses system RAM')).toBeTruthy()
    expect(screen.queryByRole('button', { name: /set up for me/i })).toBeNull()

    // Attach the browser-only scroll method to the real search container,
    // so a missing or misdirected click handler cannot satisfy the assertion.
    const search: HTMLElement = screen.getByPlaceholderText(/search models/i)
    const browse: Element | null = search.closest('#local-model-browse')
    expect(browse).not.toBeNull()
    const scroll: Mock<(options?: boolean | ScrollIntoViewOptions) => void> = vi.fn()
    Object.defineProperty(browse, 'scrollIntoView', { configurable: true, value: scroll })
    fireEvent.click(screen.getByRole('button', { name: /browse models/i }))
    expect(scroll).toHaveBeenCalledWith({ behavior: 'smooth', block: 'start' })
    expect(mocked.downloadLocalModel).not.toHaveBeenCalled()

    // The backend reports the completed download on refresh. Use must send
    // the staged variant id, not the catalog family id or an automatic pick.
    mocked.downloadLocalModel.mockResolvedValue({ already_downloaded: true, job_id: null })
    mocked.getLocalModelsStatus.mockResolvedValue({
      ...BASE_STATUS,
      runtime_installed: true,
      models: [{ id: stagedId, size_bytes: SPILLED_MODEL.size_bytes, size_label: SPILLED_MODEL.size_label }]
    })
    mocked.getLocalCatalog.mockResolvedValue({
      models: [{ ...SPILLED_MODEL, downloaded: true, downloaded_model_id: stagedId }]
    })
    fireEvent.click(screen.getByRole('button', { name: /download ·/i }))
    await waitFor((): void => {
      expect(mocked.downloadLocalModel).toHaveBeenCalledWith(SPILLED_MODEL.id, {
        connectionId: null,
        profile: 'default'
      })
    })
    mocked.activateLocalModel.mockResolvedValue({ job_id: 'explicit-spill' })
    fireEvent.click(await screen.findByRole('button', { name: /^use$/i }))
    await waitFor((): void => {
      expect(mocked.activateLocalModel).toHaveBeenCalledWith(stagedId, { connectionId: null, profile: 'default' })
    })
    expect(mocked.quickstartLocalModels).not.toHaveBeenCalled()
  })

  it('searches HF after a pause and shows fit-priced files on demand', async () => {
    vi.useFakeTimers()

    try {
      vi.mocked(hermes.searchHFModels).mockResolvedValue({
        hits: [{ downloads: 872724, gated: false, likes: 47, repo: 'unsloth/Qwen3.8-27B-GGUF', updated: '2026-08-18' }]
      })
      vi.mocked(hermes.listHFRepoFiles).mockResolvedValue({
        files: [
          { fit: 'fits-gpu', label: 'Q4_K_M', paths: ['Qwen3.8-27B-Q4_K_M.gguf'], total_bytes: 17 * 2 ** 30 },
          { fit: 'too-big', label: 'F16', paths: ['Qwen3.8-27B-F16.gguf'], total_bytes: 56 * 2 ** 30 }
        ]
      })

      render(
        <QueryClientProvider client={queryClient}>
          <MemoryRouter>
            <I18nProvider>
              <LocalModelsSettings />
            </I18nProvider>
          </MemoryRouter>
        </QueryClientProvider>
      )
      await act(async () => {
        await vi.runOnlyPendingTimersAsync()
      })
      // Fresh machine leads with the quickstart card — enter the full pane.
      fireEvent.click(screen.getByRole('button', { name: /let me choose/i }))

      const box = screen.getByPlaceholderText(/search models/i)
      fireEvent.change(box, { target: { value: 'qwen' } })
      // Debounce: no call until the pause elapses.
      expect(hermes.searchHFModels).not.toHaveBeenCalled()
      await act(async () => {
        await vi.advanceTimersByTimeAsync(400)
      })
      expect(hermes.searchHFModels).toHaveBeenCalledWith('qwen', 20, { connectionId: null, profile: 'default' })
      expect(screen.getByText('unsloth/Qwen3.8-27B-GGUF')).toBeTruthy()

      fireEvent.click(screen.getByRole('button', { name: /show files/i }))
      await act(async () => {
        await vi.runOnlyPendingTimersAsync()
      })
      expect(screen.getByText('Q4_K_M')).toBeTruthy()
      // Each tile has an explicit download button; the too-big quant's is
      // disabled, the fitting one is live and starts the download.
      const q4Btn = screen.getByRole('button', { name: 'Download Q4_K_M' })
      const f16Btn = screen.getByRole('button', { name: 'Download F16' })
      expect((f16Btn as HTMLButtonElement).disabled).toBe(true)
      expect((q4Btn as HTMLButtonElement).disabled).toBe(false)

      vi.mocked(hermes.downloadBrowsedModel).mockResolvedValue({ job_id: 'j1', model_id: 'Qwen3.8-27B-Q4_K_M' })
      fireEvent.click(q4Btn)
      await act(async () => {
        await vi.runOnlyPendingTimersAsync()
      })
      expect(hermes.downloadBrowsedModel).toHaveBeenCalledWith(
        'unsloth/Qwen3.8-27B-GGUF',
        ['Qwen3.8-27B-Q4_K_M.gguf'],
        { connectionId: null, profile: 'default' }
      )
    } finally {
      vi.useRealTimers()
    }
  })
})

describe('added-by-you rows', () => {
  it('staged models outside the catalog get the full action set', async () => {
    vi.mocked(hermes.getLocalModelsStatus).mockResolvedValue({
      ...BASE_STATUS,
      loaded_models: { 'Hermes-4.3-36B-Q5_K_M': 'loaded' },
      models: [{ id: 'Hermes-4.3-36B-Q5_K_M', size_bytes: 25 * 2 ** 30, size_label: '25.0 GB' }],
      placement: {
        'Hermes-4.3-36B-Q5_K_M': {
          granted_window_label: '96K',
          spilled: false,
          window: 98304,
          window_label: '96K'
        }
      },
      server_running: true
    })
    vi.mocked(hermes.getLocalCatalog).mockResolvedValue({ models: [] })

    renderPane()
    await screen.findByText('Hermes-4.3-36B-Q5_K_M')

    // Full management surface: Use, eject, delete, live placement pill.
    expect(screen.getByText(/added by you/i)).toBeTruthy()
    expect(screen.getByRole('button', { name: /use/i })).toBeTruthy()
    expect(screen.getByText(/96K/)).toBeTruthy()
    const buttons = screen.getAllByRole('button')
    expect(buttons.length).toBeGreaterThanOrEqual(3)
  })
})

describe('quickstart completion navigation', () => {
  it('lands on a new chat when a quickstart it watched finishes; stale done jobs on mount never navigate', async () => {
    const routeProbe = vi.fn()

    function Probe() {
      const loc = useLocation()
      routeProbe(loc.pathname)

      return null
    }

    const doneJob: LocalRuntimeJob = {
      done_bytes: 0,
      detail: '',
      error: null,
      job_id: 'stale-done',
      kind: 'quickstart',
      model_id: 'qwen3.8-27b',
      phase: 'done',
      status: 'done',
      target: 'Qwen3.8 27B',
      total_bytes: null
    }

    // A finished quickstart already in history when the pane mounts —
    // must NOT trigger navigation.
    queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [doneJob])

    render(
      <QueryClientProvider client={queryClient}>
        <MemoryRouter initialEntries={['/settings']}>
          <I18nProvider>
            <LocalModelsSettings />
          </I18nProvider>
          <Probe />
        </MemoryRouter>
      </QueryClientProvider>
    )
    await act(async () => {})
    expect(routeProbe).not.toHaveBeenCalledWith('/')

    // A quickstart the pane SAW running that then completes -> navigate.
    const running: LocalRuntimeJob = { ...doneJob, job_id: 'live-run', phase: 'downloading', status: 'running' }
    await act(async (): Promise<void> => {
      queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [doneJob, running])
      await new Promise<void>((resolve): void => {
        setTimeout(resolve, 0)
      })
    })
    await act(async () => {
      queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
        doneJob,
        { ...running, phase: 'done', status: 'done' }
      ])
    })
    await waitFor((): void => expect(routeProbe).toHaveBeenCalledWith('/'))
  })
})

describe('quickstart finalization', (): void => {
  it('quickstart hero suppresses the byte counter outside download phases', async () => {
    queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
      {
        job_id: 'q1',
        kind: 'quickstart',
        target: 'Qwen3.6 27B',
        model_id: 'qwen3.6-27b',
        status: 'running',
        phase: 'installing-runtime',
        detail: 'Unpacking runtime',
        total_bytes: 100,
        done_bytes: 100,
        percent: 100,
        error: null
      }
    ])

    renderPane()
    await screen.findByText('Unpacking runtime')

    // Stage detail yes; byte counter no — a 100% counter on an install
    // phase would lie about the model leg still ahead.
    expect(screen.queryByText(/of/)).toBeNull()
  })
})