AI, fully local on your computer.
TypeScript aiai-toolskiwixllama-cpplocal-ailocal-llmofflineoffline-aioffline-firstprivacy-firstragwikipediazim
// @vitest-environment jsdom
import { describe, it, expect, vi, afterEach, type Mock } from 'vitest'
import { screen, cleanup, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { UI_LANGUAGE_STORAGE_KEY } from '../../src/renderer/i18n'
import { t } from '../../src/shared/i18n'
import type { Conversation, DocumentInfo } from '../../src/shared/types'
import { knowledgePack, WIKIPEDIA_EN_PACK } from '../helpers/knowledge-pack-fixtures'
import { renderHome as renderScreen, stubHomeApi } from '../helpers/home-screen'
import { assertNoUnexpectedApiCalls, stubApi } from '../helpers/renderer'
import { chatScreenStubs, renderChatScreen } from '../helpers/chat-screen'
import { makeConversation, makeDocumentInfo, makeMessage, userMsg } from '../helpers/chat-fixtures'
import { STOPPED_RUNTIME, appStatus, preflightResult, runtimeStatus } from '../helpers/status'
// Renderer tests for the chat screen's structural behaviors (Phase 25 layout, same
// contracts underneath): deleting conversations through the row "⋯" menu + ConfirmDialog
// (the last browser confirm() is gone), markdown rendering, opening the Chat screen
// directly in documents mode, the documents-scope popover (replaces the scope-chip row),
// and the Home screen's "Ask My Documents" navigating to the document-Q&A chat.
// Differs from makeConversation: the title the rows below look up.
function conv(over: Partial<Conversation> = {}): Conversation {
return makeConversation({ title: 'My first chat', ...over })
}
afterEach(() => {
try {
assertNoUnexpectedApiCalls()
} finally {
cleanup()
vi.restoreAllMocks()
window.localStorage.clear()
}
})
/** Open conversation-row "⋯" menu → "Delete conversation" → the confirm dialog. */
async function openDeleteConfirm(user: ReturnType<typeof userEvent.setup>, title: string): Promise<void> {
await user.click(screen.getByRole('button', { name: t('en', 'chat.list.rowOptionsAria', { title }) }))
await user.click(await screen.findByRole('menuitem', { name: /delete conversation/i }))
await screen.findByRole('dialog')
}
describe('ChatScreen — delete conversation (⋯ menu + ConfirmDialog)', () => {
it('deletes after confirming in the dialog and refreshes the sidebar', async () => {
const user = userEvent.setup()
const listConversations = vi
.fn<() => Promise<Conversation[]>>()
.mockResolvedValueOnce([conv()]) // initial mount
.mockResolvedValue([]) // after delete
const deleteConversation = vi.fn(async () => {})
stubApi(
chatScreenStubs({
listConversations,
deleteConversation,
// The open dialog counts the reviews a delete would take with it: none here.
countEvidenceReviewsForConversation: vi.fn(async () => 0)
})
)
renderChatScreen()
await screen.findByText('My first chat')
await openDeleteConfirm(user, 'My first chat')
await user.click(screen.getByRole('button', { name: 'Delete' }))
await waitFor(() => expect(deleteConversation).toHaveBeenCalledWith('c1'))
await waitFor(() => expect(screen.queryByText('My first chat')).not.toBeInTheDocument())
})
it('does nothing when the dialog is cancelled', async () => {
const user = userEvent.setup()
const deleteConversation = vi.fn(async () => {})
stubApi(
chatScreenStubs({
listConversations: vi.fn(async () => [conv()]),
deleteConversation,
countEvidenceReviewsForConversation: vi.fn(async () => 0)
})
)
renderChatScreen()
await screen.findByText('My first chat')
await openDeleteConfirm(user, 'My first chat')
await user.click(screen.getByRole('button', { name: 'Cancel' }))
expect(deleteConversation).not.toHaveBeenCalled()
expect(screen.getByText('My first chat')).toBeInTheDocument()
})
})
describe('ChatScreen — markdown rendering', () => {
it('renders assistant markdown (e.g. **bold**) as formatting, not raw asterisks', async () => {
const user = userEvent.setup()
stubApi(
chatScreenStubs({
listConversations: vi.fn(async () => [conv()]),
listMessages: vi.fn(async () => [
makeMessage({ content: 'Total for **Invoice 42** is due.\n\n- item one\n- item two' })
])
})
)
renderChatScreen()
await user.click(await screen.findByText('My first chat'))
const bold = await screen.findByText('Invoice 42')
expect(bold.tagName).toBe('STRONG')
expect(screen.getByRole('list')).toBeInTheDocument() // the markdown bullet list
expect(screen.queryByText(/\*\*/)).not.toBeInTheDocument()
})
it('renders raw HTML in model output as literal text (no injection)', async () => {
const user = userEvent.setup()
stubApi(
chatScreenStubs({
listConversations: vi.fn(async () => [conv()]),
listMessages: vi.fn(async () => [makeMessage({ content: 'hi <img src=x onerror=alert(1)> there' })])
})
)
renderChatScreen()
await user.click(await screen.findByText('My first chat'))
await screen.findByText(/hi/)
expect(document.querySelector('.msg-content img')).toBeNull()
})
it('leaves user messages as plain text (asterisks intact)', async () => {
const user = userEvent.setup()
stubApi(
chatScreenStubs({
listConversations: vi.fn(async () => [conv()]),
listMessages: vi.fn(async () => [userMsg('u1', 'what is **this**?')])
})
)
renderChatScreen()
await user.click(await screen.findByText('My first chat'))
expect(await screen.findByText('what is **this**?')).toBeInTheDocument()
})
})
describe('ChatScreen — initial mode', () => {
it('opens in documents mode when initialMode="documents"', async () => {
stubApi(chatScreenStubs())
renderChatScreen({ initialMode: 'documents' })
expect(await screen.findByPlaceholderText(/ask about your documents/i)).toBeInTheDocument()
})
it('defaults to plain chat mode', async () => {
stubApi(chatScreenStubs())
renderChatScreen()
expect(await screen.findByPlaceholderText("Message…")).toBeInTheDocument()
})
})
// ---- Documents-scope popover (Phase 25 §3; scope semantics from Phase 17 §5.3) ----
/** The two indexed documents the scope rows name by title. */
const contractPdf = (): DocumentInfo => makeDocumentInfo({ id: 'd1', title: 'contract.pdf' })
const termsDocx = (): DocumentInfo => makeDocumentInfo({ id: 'd2', title: 'terms.docx' })
describe('ChatScreen — documents-scope multi-select picker (plan §13)', () => {
it('shows a persisted specific-doc scope and removes one document via setConversationScope', async () => {
const user = userEvent.setup()
const scoped = conv({ id: 'c9', title: 'Doc Q&A', mode: 'documents', scopeDocumentIds: ['d1', 'd2'] })
const setConversationScope = vi.fn(async () => ({ ...scoped, scopeDocumentIds: ['d2'] }))
const listConversations = vi
.fn<() => Promise<Conversation[]>>()
.mockResolvedValueOnce([scoped])
.mockResolvedValue([{ ...scoped, scopeDocumentIds: ['d2'] }])
stubApi(
chatScreenStubs({
listConversations,
listDocuments: vi.fn(async () => [contractPdf(), termsDocx()]),
setConversationScope
})
)
renderChatScreen()
await user.click(await screen.findByText('Doc Q&A'))
await user.click(await screen.findByRole('button', { name: /answering from: 2 documents/i }))
// The two specific docs render as removable chips.
expect(await screen.findByText('contract.pdf')).toBeInTheDocument()
expect(screen.getByText('terms.docx')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /stop asking contract.pdf/i }))
await waitFor(() =>
expect(setConversationScope).toHaveBeenCalledWith('c9', { collectionIds: [], documentIds: ['d2'] })
)
// A single remaining document is named directly by the "Answering from:" chip (D71).
await waitFor(() =>
expect(screen.getByRole('button', { name: /answering from: terms\.docx/i })).toBeInTheDocument()
)
})
it('adds a document via "Specific documents…" and resets to all documents', async () => {
const user = userEvent.setup()
const scoped = conv({ id: 'c9', title: 'Doc Q&A', mode: 'documents', scopeDocumentIds: ['d1'] })
const setConversationScope = vi.fn(async () => scoped)
const listConversations = vi
.fn<() => Promise<Conversation[]>>()
.mockResolvedValueOnce([scoped])
.mockResolvedValueOnce([{ ...scoped, scopeDocumentIds: ['d1', 'd2'] }])
.mockResolvedValue([{ ...scoped, scopeDocumentIds: ['d1', 'd2'] }])
stubApi(
chatScreenStubs({
listConversations,
listDocuments: vi.fn(async () => [contractPdf(), termsDocx()]),
setConversationScope
})
)
renderChatScreen()
await user.click(await screen.findByText('Doc Q&A'))
await user.click(await screen.findByRole('button', { name: /answering from: contract\.pdf/i }))
// Reveal the doc picker, then add an out-of-scope document as a "+ add" chip.
await user.click(await screen.findByRole('button', { name: /specific documents/i }))
await user.click(await screen.findByRole('button', { name: /\+ terms.docx/i }))
await waitFor(() =>
expect(setConversationScope).toHaveBeenCalledWith('c9', { collectionIds: [], documentIds: ['d1', 'd2'] })
)
expect(await screen.findByRole('button', { name: /answering from: 2 documents/i })).toBeInTheDocument()
// The reset taps to the explicit empty "All documents" scope.
await user.click(screen.getByRole('button', { name: 'All documents' }))
await waitFor(() =>
expect(setConversationScope).toHaveBeenCalledWith('c9', { collectionIds: [], documentIds: [] })
)
})
it('applies the pending handoff scope to the next documents conversation', async () => {
const user = userEvent.setup()
const created = conv({ id: 'c2', title: 'New chat', mode: 'documents', scopeDocumentIds: ['d1'] })
const createConversation = vi.fn(async () => created)
stubApi(chatScreenStubs({ listDocuments: vi.fn(async () => [contractPdf()]), createConversation }))
renderChatScreen({ initialMode: 'documents', initialScopeDocumentIds: ['d1'] })
// The handoff shows in the footer affordance before any conversation exists…
expect(await screen.findByRole('button', { name: /answering from: contract\.pdf/i })).toBeInTheDocument()
// …and the next conversation is created WITH the composite scope (plan D1).
await user.click(screen.getByRole('button', { name: /new document q&a/i }))
await waitFor(() =>
expect(createConversation).toHaveBeenCalledWith({
mode: 'documents',
scope: { collectionIds: [], documentIds: ['d1'] },
collectionId: undefined
})
)
})
// §11.16 "Ask this pack": the pack alone — ticked, documents off — is the next conversation's
// scope, and the chip says so before any conversation exists.
it('applies the pending pack handoff (documents off) to the next documents conversation', async () => {
const user = userEvent.setup()
const wikipedia = knowledgePack({ ...WIKIPEDIA_EN_PACK })
const created = conv({ id: 'c3', title: 'New chat', mode: 'documents' })
const createConversation = vi.fn(async () => created)
stubApi(
chatScreenStubs({
listDocuments: vi.fn(async () => [contractPdf()]),
listKnowledgePacks: vi.fn(async () => [wikipedia]),
createConversation
})
)
renderChatScreen({ initialMode: 'documents', initialScopePackIds: ['p1'] })
// The handoff shows in the footer affordance: the pack, and the honest "documents off" tail.
const packSource = `${t('en', 'chat.scope.packNamed', { name: 'Wikipedia (English)' })} · ${t('en', 'chat.scope.documentsOffSuffix')}`
expect(
await screen.findByRole('button', { name: t('en', 'chat.scope.answeringFrom', { source: packSource }) })
).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /new document q&a/i }))
await waitFor(() =>
expect(createConversation).toHaveBeenCalledWith({
mode: 'documents',
scope: { collectionIds: [], documentIds: [], packIds: ['p1'], documentsOff: true },
collectionId: undefined
})
)
})
it('labels the whole corpus honestly when no scope is set', async () => {
stubApi(chatScreenStubs({ listDocuments: vi.fn(async () => [contractPdf(), termsDocx()]) }))
renderChatScreen({ initialMode: 'documents' })
// The whole-library case names the corpus size (D71) so "answer from everything" reads as a
// deliberate breadth. (The chip never shows 0 — an empty corpus falls to the "Add documents" CTA.)
expect(
await screen.findByRole('button', { name: /answering from: your whole library — 2 documents/i })
).toBeInTheDocument()
})
})
describe('HomeScreen — readiness hub (Phase 26)', () => {
function renderHome(
onNavigate: Mock<(s: string) => void>,
opts: {
activeModelId?: string | null
running?: boolean
docCount?: number
problems?: string[]
lang?: 'en' | 'de'
} = {}
): void {
const docCount = opts.docCount ?? 2
if (opts.lang) window.localStorage.setItem(UI_LANGUAGE_STORAGE_KEY, opts.lang)
stubHomeApi({
getAppStatus: vi.fn(async () => appStatus({ activeModelId: opts.activeModelId ?? null, machineRamGb: 16 })),
getRuntimeStatus: vi.fn(async () =>
opts.running
? runtimeStatus({ modelId: opts.activeModelId ?? 'm1', port: null, message: '' })
: STOPPED_RUNTIME
),
listDocuments: vi.fn(async () =>
Array.from({ length: docCount }, (_, i) => makeDocumentInfo({ id: `d${i + 1}`, title: `doc-${i + 1}.pdf` }))
),
runPreflight: vi.fn(async () => preflightResult({ problems: opts.problems ?? [] }))
})
renderScreen({ onNavigate })
}
/** The loud filled primary buttons currently on screen (Button variant="primary"). */
function loudPrimaries(): HTMLElement[] {
return [...document.querySelectorAll<HTMLElement>('button.btn.primary')]
}
it('when a model IS ready, "Start chatting" is the one loud primary and opens Chat', async () => {
const user = userEvent.setup()
const onNavigate = vi.fn()
renderHome(onNavigate, { activeModelId: 'm1', running: true })
const startChat = await screen.findByRole('button', { name: /start chatting/i })
// Exactly one loud primary, and it is "Start chatting".
await waitFor(() => expect(loudPrimaries()).toHaveLength(1))
expect(loudPrimaries()[0]).toBe(startChat)
await user.click(startChat)
expect(onNavigate).toHaveBeenCalledWith('chat')
})
it('when readiness = needs-a-model, the loud primary becomes "Choose a model" (not "Start chatting")', async () => {
const user = userEvent.setup()
const onNavigate = vi.fn()
renderHome(onNavigate, { activeModelId: null, running: false })
// The hero's loud primary is the unblocking action; exactly one loud primary.
await waitFor(() => expect(loudPrimaries()).toHaveLength(1))
const primary = loudPrimaries()[0]
expect(primary).toHaveTextContent(t('en', 'home.model.choose')) // "Choose a model"
// "Start chatting" is still present but NOT the loud primary (it demoted to secondary).
const startChat = screen.getByRole('button', { name: /start chatting/i })
expect(startChat.className).not.toMatch(/\bprimary\b/)
// The loud primary routes to AI Model (no dead-end at the no-model empty state).
await user.click(primary)
expect(onNavigate).toHaveBeenCalledWith('models')
})
it('the needs-a-model loud primary is "Modell auswählen" in German', async () => {
const onNavigate = vi.fn()
renderHome(onNavigate, { activeModelId: null, running: false, lang: 'de' })
await waitFor(() => expect(loudPrimaries()).toHaveLength(1))
expect(loudPrimaries()[0]).toHaveTextContent(t('de', 'home.model.choose')) // „Modell auswählen"
})
it('"Ask my documents" opens the documents chat, not the import screen', async () => {
const user = userEvent.setup()
const onNavigate = vi.fn()
renderHome(onNavigate, { activeModelId: 'm1', running: true })
// Settle the ready state first (the adaptive hero swaps buttons as readiness resolves,
// so query AFTER it settles to avoid clicking a node React reused by position).
await screen.findByText('Ready to chat.')
await user.click(screen.getByRole('button', { name: /ask my documents/i }))
expect(onNavigate).toHaveBeenCalledWith('ask-documents')
})
it('reads ready when the model runs, with the model name and document count', async () => {
const onNavigate = vi.fn()
renderHome(onNavigate, { activeModelId: 'qwen3-4b-instruct-q4', running: true, docCount: 2 })
expect(await screen.findByText('Ready to chat.')).toBeInTheDocument()
expect(
await screen.findByText(/qwen3-4b-instruct-q4 is running on this device/)
).toBeInTheDocument()
expect(await screen.findByText(/2 documents ready to ask about/)).toBeInTheDocument()
})
it('says the selected model may still be loading while the runtime is down', async () => {
const onNavigate = vi.fn()
renderHome(onNavigate, { activeModelId: 'qwen3-4b-instruct-q4', running: false })
expect(await screen.findByText('Getting ready…')).toBeInTheDocument()
expect(
await screen.findByText(/qwen3-4b-instruct-q4 is selected — it may still be loading/)
).toBeInTheDocument()
})
it('the model row points at the AI Model screen when no model is selected', async () => {
const user = userEvent.setup()
const onNavigate = vi.fn()
renderHome(onNavigate, { activeModelId: null })
expect(await screen.findByText('No model selected yet')).toBeInTheDocument()
// The inline row affordance (a Secondary button) also routes to AI Model. It is the
// non-loud "Choose a model": the loud hero primary is covered by the adaptive tests.
const card = document.querySelector('.readiness-card') as HTMLElement
await user.click(within(card).getByRole('button', { name: /choose a model/i }))
expect(onNavigate).toHaveBeenCalledWith('models')
})
it('nudges toward Documents when none are imported (and hides "Ask my documents")', async () => {
const user = userEvent.setup()
const onNavigate = vi.fn()
renderHome(onNavigate, { docCount: 0 })
expect(await screen.findByText(/No documents yet/)).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /ask my documents/i })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /add documents/i }))
expect(onNavigate).toHaveBeenCalledWith('documents')
})
it('shows preflight problems as a quiet warning', async () => {
renderHome(vi.fn(), { problems: ['The drive has very little free space left.'] })
expect(
await screen.findByText('The drive has very little free space left.')
).toBeInTheDocument()
})
})