Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

12.7 KB
Raw Blame
/**
 * @vitest-environment jsdom
 *
 * P11 (3.0.9): the Neuron tweaker. A slider that is not computed for the
 * model offers to compute it (locked, with no false notice, until the model's
 * info is in); a computed one, moved, reaches the engine as
 * one entry; Reset brings the engine back to no vector at all; a chat model
 * in Ollama is told plainly that the sliders cannot reach it; an embedding
 * model is never offered.
 *
 * Run: npx vitest run src/components/neuron/__tests__/neuron-view-steers-the-engine.test.tsx
 */
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { createElement } from 'react'
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react'

const apply = vi.fn(async (_path: string, _entries: unknown[], _tuning?: unknown) => ({ mix: null, restarted: true, load: 0 }))
const buildPreset = vi.fn(async (_path: string, _id: string) => ({ started: true }))
const vectors: Array<Record<string, unknown>> = []

vi.mock('../../../api/neuron', () => ({
  neuronPresets: async () => [
    { id: 'creative', left: 'Sober', right: 'Creative' },
    { id: 'cheerful', left: 'Serious', right: 'Cheerful' },
  ],
  neuronInfo: async (path: string) => path === LLAMA.path ? {
    // The second model's info comes later than the first's, as on disk.
    ...(await new Promise((r) => setTimeout(r, 200)), {}),
    facts: { arch: 'llama', nLayer: 28, nEmbd: 3072, template: 'llama3', name: 'Llama 3.2 3B' },
    modelKey: 'llama-1', generator: true, band: [4, 22], vectors: [...vectors], sae: null, activeMix: null,
  } : ({
    facts: { arch: 'qwen2', nLayer: 24, nEmbd: 896, template: 'chatMl', name: 'Qwen2.5 0.5B Instruct' },
    modelKey: 'qwen-1',
    generator: true,
    band: [3, 20],
    vectors: [...vectors],
    sae: null,
    activeMix: null,
  }),
  neuronStatus: async () => ({ status: job.status, kind: '', title: '', modelPath: job.modelPath, phaseLabel: '', step: 0, total: 0, bytesDone: 0, bytesTotal: 0, rateBps: 0, etaSecs: null, elapsedSecs: 0, resultId: null, error: null, logs: [] }),
  neuronApply: (p: string, e: unknown[], t?: unknown) => apply(p, e, t),
  neuronBuildPreset: (p: string, id: string) => buildPreset(p, id),
  neuronBuildOwn: vi.fn(), neuronCancel: vi.fn(), neuronCompare: vi.fn(), neuronDelete: vi.fn(), neuronDismiss: vi.fn(),
  neuronFeatureAdd: vi.fn(), neuronSaeDownload: vi.fn(), neuronSaeSearch: vi.fn(),
}))
const addGgufFile = vi.hoisted(() => vi.fn(async (): Promise<string | null> => null))
vi.mock('../../../api/engine', () => ({
  addGgufFile: () => addGgufFile(),
  listBundledModels: async () => [...disk.models],
  isEmbeddingGgufName: (name: string) => /embed/.test(name.toLowerCase()),
  bundledEngineStatus: async () => ({ running: true, healthy: true, port: 8127, model_path: '/models/qwen.gguf', ctx: 8192 }),
}))
vi.mock('../../../api/backend', () => ({ openExternal: vi.fn(), backendCall: vi.fn() }))
const QWEN = { name: 'qwen2.5-0.5b-instruct-q8_0', path: '/models/qwen.gguf', size: 1, loaded: true }
const LLAMA = { name: 'llama-3.2-3b-q4_k_m', path: '/models/llama.gguf', size: 1, loaded: false }
const NOMIC = { name: 'nomic-embed-text-v1.5.Q4_K_M', path: '/models/nomic.gguf', size: 1, loaded: false }
const disk = vi.hoisted(() => ({ models: [] as Array<Record<string, unknown>> }))
const slot = vi.hoisted(() => ({ managed: true }))
const job = vi.hoisted(() => ({ status: 'idle', modelPath: '' }))
vi.mock('../../../api/builtin-ensure', () => ({ isManagedBuiltinSlot: () => slot.managed }))

import { NeuronPanel as NeuronView } from '../NeuronPanel'
import { useModelStore } from '../../../stores/modelStore'
import { useNeuronStore } from '../../../stores/neuronStore'
import { useSettingsStore } from '../../../stores/settingsStore'
import { useChatStore } from '../../../stores/chatStore'
import { useUIStore } from '../../../stores/uiStore'
import { HOWTO } from '../../../lib/howto'
import type { Persona } from '../../../types/settings'

beforeEach(() => {
  addGgufFile.mockClear()
  apply.mockClear()
  buildPreset.mockClear()
  vectors.length = 0
  slot.managed = true
  job.status = 'idle'
  job.modelPath = ''
  disk.models = [NOMIC, QWEN]
  useNeuronStore.setState({ profiles: {}, scopeByModel: {}, introSeen: true })
  useModelStore.setState({ activeModel: 'openai::qwen2.5-0.5b-instruct-q8_0' })
})
afterEach(() => cleanup())

describe('Neuron tweaker view', () => {
  it('offers to compute a slider the model does not have yet', async () => {
    render(createElement(NeuronView))
    const button = (await screen.findByTestId('neuron-compute-creative')) as HTMLButtonElement
    // Locked until the model's info says the vector tool is there; a click
    // before that does nothing, as it should.
    expect(screen.queryByText(/missing its vector tool/)).toBeNull()
    await waitFor(() => expect(button.disabled).toBe(false))
    fireEvent.click(button)
    await waitFor(() => expect(buildPreset).toHaveBeenCalledWith('/models/qwen.gguf', 'creative'))
  })

  it('sends a moved slider to the engine and Reset sends none', async () => {
    vectors.push({ id: 'creative', kind: 'preset', name: 'Sober ↔ Creative', left: 'Sober', right: 'Creative', unit: 0.8, builtAt: 1, more: [], less: [] })
    render(createElement(NeuronView))
    const row = await screen.findByTestId('neuron-slider-creative')
    // First apply on open: nothing set, no vector.
    await waitFor(() => expect(apply).toHaveBeenCalled())
    expect(apply.mock.calls[0][1]).toEqual([])
    const range = row.querySelector('input[type=range]') as HTMLInputElement
    fireEvent.change(range, { target: { value: '0.6' } })
    await waitFor(() => expect(apply.mock.calls.at(-1)?.[1]).toEqual([{ id: 'creative', strength: 0.6 }]), { timeout: 3000 })
    fireEvent.click(screen.getByTestId('neuron-reset'))
    await waitFor(() => expect(apply.mock.calls.at(-1)?.[1]).toEqual([]), { timeout: 3000 })
  })

  // T1 (3.0.9): after a switch the old model's sliders went to the new
  // model (twice, each a restart) until its info was in.
  it('sends the new model only its own sliders after a switch', async () => {
    disk.models = [QWEN, LLAMA]
    vectors.push({ id: 'creative', kind: 'preset', name: 'Sober ↔ Creative', left: 'Sober', right: 'Creative', unit: 0.8, builtAt: 1, more: [], less: [] })
    useNeuronStore.setState({ profiles: { 'qwen-1': { creative: 0.5 } }, scopeByModel: {} })
    render(createElement(NeuronView))
    await waitFor(() => expect(apply.mock.calls.at(-1)?.[1]).toEqual([{ id: 'creative', strength: 0.5 }]))
    fireEvent.change(screen.getByTestId('neuron-model'), { target: { value: LLAMA.path } })
    await waitFor(() => expect(apply.mock.calls.some((c) => c[0] === LLAMA.path)).toBe(true))
    await new Promise((r) => setTimeout(r, 300))
    const toLlama = apply.mock.calls.filter((c) => c[0] === LLAMA.path)
    expect(toLlama.map((c) => c[1])).toEqual([[]])
  })

  // T1 (3.0.9): a job for the old model that ended after the switch put the
  // old model's info under the new model's name.
  it('stays on the new model when a job for the old one ends', async () => {
    disk.models = [QWEN, LLAMA]
    render(createElement(NeuronView))
    await screen.findByText(/qwen2 · 24 layers/)
    job.status = 'running'
    job.modelPath = QWEN.path
    fireEvent.change(screen.getByTestId('neuron-model'), { target: { value: LLAMA.path } })
    await screen.findByText(/llama · 28 layers/)
    job.status = 'done'
    await new Promise((r) => setTimeout(r, 1500))
    expect(screen.queryByText(/qwen2 · 24 layers/)).toBeNull()
  })

  // T1 (3.0.9): with the scope already on "persona", a persona without its
  // own sliders kept only the one moved; the others fell to 0.
  it('keeps the other sliders when a persona is first moved', async () => {
    for (const id of ['creative', 'cheerful']) vectors.push({ id, kind: 'preset', name: id, left: 'L', right: 'R', unit: 0.8, builtAt: 1, more: [], less: [] })
    useNeuronStore.setState({ profiles: { 'qwen-1': { creative: 0.5, cheerful: 0.4 } }, scopeByModel: { 'qwen-1': 'persona' } })
    useChatStore.setState({ conversations: [], activeConversationId: null })
    useSettingsStore.setState((s) => ({ personas: [{ id: 'coder', name: 'Coder', systemPrompt: 'Code.' } as Persona], activePersonaId: 'coder', settings: { ...s.settings, personasEnabled: true } }))
    render(createElement(NeuronView))
    const row = await screen.findByTestId('neuron-slider-creative')
    await waitFor(() => expect(row.querySelector('input[type=range]')).toBeTruthy())
    fireEvent.change(row.querySelector('input[type=range]') as HTMLInputElement, { target: { value: '0.2' } })
    expect(useNeuronStore.getState().profiles['qwen-1::persona:coder']).toEqual({ creative: 0.2, cheerful: 0.4 })
    await waitFor(() => expect(apply.mock.calls.at(-1)?.[1]).toEqual([{ id: 'cheerful', strength: 0.4 }, { id: 'creative', strength: 0.2 }]), { timeout: 3000 })
  })

  // T1 (3.0.9): the embedding model of Document Chat was the only choice,
  // and the vector tool aborted on it.
  it('offers chat models only, under a labelled picker', async () => {
    render(createElement(NeuronView))
    const picker = (await screen.findByLabelText('Model')) as HTMLSelectElement
    await waitFor(() => expect(picker.options.length).toBe(1))
    expect(picker.options[0].value).toBe('/models/qwen.gguf')
  })

  it('says so when only an embedding model is there', async () => {
    disk.models = [NOMIC]
    useModelStore.setState({ activeModel: 'ollama::llama3:8b' })
    render(createElement(NeuronView))
    expect((await screen.findByTestId('neuron-empty')).textContent).toMatch(/No chat model for the LU Engine yet/)
    expect(screen.getByTestId('neuron-no-chat-model').textContent).toMatch(/embedding model/)
    // Why the Ollama model the user has is not offered, in one sentence.
    expect(screen.getByTestId('neuron-other-apps').textContent).toMatch(/Ollama or LM Studio .* take no control vectors/)
    expect(screen.queryByTestId('neuron-model')).toBeNull()
  })

  // David, 30.10.2026: the line sat at the top, "hingeklatscht". It is one
  // state filling the window under its title bar, both ways, text centred.
  it('stands in the middle of the window when there is no model', async () => {
    disk.models = []
    render(createElement(NeuronView))
    const box = await screen.findByTestId('neuron-empty')
    const panel = screen.getByTestId('neuron-view')
    expect(panel.className).toMatch(/\bh-full\b/)
    expect(panel.className).toMatch(/\bflex\b/)
    expect(box.className).toMatch(/\btext-center\b/)
    expect(box.className).toMatch(/\bitems-center\b/)
  })

  it('its download button opens Discover on the chat lane with the LU Engine as target', async () => {
    disk.models = []
    useModelStore.setState({ activeModel: 'llama3:8b', categoryFilter: 'image' })
    useUIStore.setState({ currentView: 'neuron', discoverTarget: null })
    render(createElement(NeuronView))
    fireEvent.click(await screen.findByTestId('neuron-get-model'))
    expect(useUIStore.getState().currentView).toBe('models')
    expect(useUIStore.getState().discoverTarget).toBe('builtin')
    expect(useModelStore.getState().categoryFilter).toBe('text')
    // The chat model is not touched.
    expect(useModelStore.getState().activeModel).toBe('llama3:8b')
  })

  // David, 30.10.2026: how to bring a GGUF file in, in three short steps,
  // with the button that opens exactly that dialog. The lines are the
  // how-to's (lib/howto.ts 'gguf-file'), so Help says the same.
  it('says in three steps how a GGUF file becomes an LU Engine model, next to its button', async () => {
    disk.models = []
    render(createElement(NeuronView))
    const box = await screen.findByTestId('neuron-gguf-steps')
    const lines = [...box.querySelectorAll('ol > li')].map((li) => li.textContent)
    expect(lines).toEqual(HOWTO['gguf-file'].films[0].steps.map((st) => st.text))
    expect(lines[0]).toMatch(/GGUF file/)
    const button = screen.getByTestId('neuron-add-gguf')
    expect(box.contains(button)).toBe(true)
    expect(button.textContent).toMatch(/GGUF file/)
    fireEvent.click(button)
    await waitFor(() => expect(addGgufFile).toHaveBeenCalledTimes(1))
  })

  it('its GGUF file button adds a file and the tweaker opens on it', async () => {
    disk.models = []
    addGgufFile.mockImplementationOnce(async () => { disk.models = [QWEN]; return QWEN.name })
    render(createElement(NeuronView))
    fireEvent.click(await screen.findByTestId('neuron-add-gguf'))
    expect(await screen.findByTestId('neuron-model')).toBeTruthy()
    expect(addGgufFile).toHaveBeenCalledTimes(1)
  })

  it('says plainly when the chat model runs in Ollama', async () => {
    useModelStore.setState({ activeModel: 'ollama::llama3:8b' })
    render(createElement(NeuronView))
    expect(await screen.findByText(/Ollama takes no control vectors/)).toBeTruthy()
  })
})