From 60c98fc51e5e4b4c7ef2775651b1e9703caaff56 Mon Sep 17 00:00:00 2001 From: Evandro Fonseca Junior Date: Mon, 16 Nov 2026 00:35:14 -0300 Subject: [PATCH] test: caminhos-base de components --- components/chat/chat-input.test.tsx | 140 +++++++++ components/chat/chat-message.test.tsx | 76 +++++ components/chat/mcp-config-panel.test.tsx | 82 +++++ components/chat/mcp-json-editor.test.tsx | 75 +++++ .../chat/message-step-thinking.test.tsx | 64 ++++ .../chat/model-download-dialog.test.tsx | 286 ++++++++++++++++++ components/chat/prompt-generator.test.tsx | 112 +++++++ components/chat/sidebar-list.test.tsx | 172 +++++++++++ components/setup/model-selector.test.tsx | 134 ++++++++ vitest.config.mts | 3 +- vitest.setup.ts | 5 + 11 files changed, 1148 insertions(+), 1 deletion(-) create mode 100644 components/chat/chat-input.test.tsx create mode 100644 components/chat/chat-message.test.tsx create mode 100644 components/chat/mcp-config-panel.test.tsx create mode 100644 components/chat/mcp-json-editor.test.tsx create mode 100644 components/chat/message-step-thinking.test.tsx create mode 100644 components/chat/model-download-dialog.test.tsx create mode 100644 components/chat/prompt-generator.test.tsx create mode 100644 components/chat/sidebar-list.test.tsx create mode 100644 components/setup/model-selector.test.tsx create mode 100644 vitest.setup.ts diff --git a/components/chat/chat-input.test.tsx b/components/chat/chat-input.test.tsx new file mode 100644 index 0000000..a9289eb --- /dev/null +++ b/components/chat/chat-input.test.tsx @@ -0,0 +1,140 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '@testing-library/react'; +import { ChatInput } from './chat-input'; +import { useSettingsStore } from '@/store/settings-store'; + +// Ramos só visuais (cor do texto inválido, ícone Globe/WifiOff, ícone por categoria) ficam mapeados sem teste. + +const defaults = useSettingsStore.getState().queryPreprocessing; +const box = () => screen.getByPlaceholderText('Pergunte qualquer coisa...') as HTMLTextAreaElement; +const type = (text: string) => fireEvent.change(box(), { target: { value: text } }); + +beforeEach(() => { + localStorage.clear(); + useSettingsStore.setState({ queryPreprocessing: defaults }); +}); + +describe('ChatInput: envio', () => { + it('Enter com texto válido: envia e limpa a caixa', () => { + const onSend = vi.fn(); + render(); + type('qual a versão do node?'); + fireEvent.keyDown(box(), { key: 'Enter' }); + expect(onSend).toHaveBeenCalledWith('qual a versão do node?'); + expect(box().value).toBe(''); + }); + + it('Shift+Enter: não envia', () => { + const onSend = vi.fn(); + render(); + type('linha um'); + fireEvent.keyDown(box(), { key: 'Enter', shiftKey: true }); + expect(onSend).not.toHaveBeenCalled(); + }); + + it('caixa em branco: botão de enviar desativado e Enter não envia', () => { + const onSend = vi.fn(); + render(); + type(' '); + expect(screen.getByRole('button')).toHaveProperty('disabled', true); + fireEvent.keyDown(box(), { key: 'Enter' }); + expect(onSend).not.toHaveBeenCalled(); + }); + + it('texto abaixo do mínimo: mostra o erro de validação e não envia', () => { + const onSend = vi.fn(); + render(); + type('ab'); + expect(screen.getByText(/mínimo/i)).toBeTruthy(); + expect(screen.getByRole('button')).toHaveProperty('disabled', true); + fireEvent.keyDown(box(), { key: 'Enter' }); + expect(onSend).not.toHaveBeenCalled(); + }); + + it('pré-processamento desligado: aceita texto curto', () => { + useSettingsStore.setState({ queryPreprocessing: { ...defaults, enabled: false } }); + const onSend = vi.fn(); + render(); + type('ab'); + fireEvent.click(screen.getByRole('button')); + expect(onSend).toHaveBeenCalledWith('ab'); + }); + + it('settings sem queryPreprocessing: usa mínimo 3 padrão', () => { + useSettingsStore.setState({ queryPreprocessing: undefined as unknown as typeof defaults }); + render(); + type('ab'); + expect(screen.getByRole('button')).toHaveProperty('disabled', true); + type('abc'); + expect(screen.getByRole('button')).toHaveProperty('disabled', false); + }); + + it('padrões irrelevantes vazios: só avisa, ainda envia', () => { + useSettingsStore.setState({ queryPreprocessing: { ...defaults, irrelevantPatterns: [] } }); + const onSend = vi.fn(); + render(); + type('teste'); + fireEvent.keyDown(box(), { key: 'Enter' }); + expect(onSend).toHaveBeenCalledWith('teste'); + }); + + it('carregando: Enter não envia e o botão vira parar', () => { + const onSend = vi.fn(); + const onStop = vi.fn(); + render(); + type('qual a versão do node?'); + fireEvent.keyDown(box(), { key: 'Enter' }); + expect(onSend).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button')); + expect(onStop).toHaveBeenCalled(); + }); +}); + +describe('ChatInput: pesquisa web', () => { + it('desativada: um clique reativa sem confirmação', () => { + const toggle = vi.fn(); + render(); + fireEvent.click(screen.getAllByRole('button')[0]); + expect(toggle).toHaveBeenCalledWith(true); + expect(screen.queryByRole('dialog')).toBeNull(); + }); + + it('ativada: pede confirmação e "Desativar" desliga', () => { + const toggle = vi.fn(); + render(); + fireEvent.click(screen.getAllByRole('button')[0]); + expect(screen.getByRole('dialog', { name: 'Desativar pesquisa web?' })).toBeTruthy(); + fireEvent.click(screen.getByRole('button', { name: 'Desativar' })); + expect(toggle).toHaveBeenCalledWith(false); + }); + + it('ativada e "Cancelar" na confirmação: mantém ligada', () => { + const toggle = vi.fn(); + render(); + fireEvent.click(screen.getAllByRole('button')[0]); + fireEvent.click(screen.getByRole('button', { name: 'Cancelar' })); + expect(toggle).not.toHaveBeenCalled(); + }); + + it('sem categorias: não oferece o menu de fontes', () => { + render(); + expect(screen.queryByTitle('Gerenciar fontes')).toBeNull(); + }); + + it('menu de fontes: marcar categoria chama onToggleCategory com o novo estado', () => { + const onToggleCategory = vi.fn(); + render( + , + ); + const trigger = screen.getByTitle('Gerenciar fontes'); + fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + fireEvent.click(screen.getByRole('menuitemcheckbox', { name: 'Notícias' })); + expect(onToggleCategory).toHaveBeenCalledWith('news', true); + }); +}); diff --git a/components/chat/chat-message.test.tsx b/components/chat/chat-message.test.tsx new file mode 100644 index 0000000..4c7eed1 --- /dev/null +++ b/components/chat/chat-message.test.tsx @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { ChatMessage } from './chat-message'; +import type { Message } from '@/hooks/use-chat'; + +// Ramos só visuais (cor do atual, seleção ao clicar, ícone) ficam mapeados sem teste: dependem de classes CSS. + +const user = (content: string): Message => ({ role: 'user', content }); +const bot = (content: string, metadata?: unknown): Message => ({ role: 'assistant', content, metadata }); + +describe('ChatMessage', () => { + it('metadata de pensamento: renderiza a etapa em vez do balão', () => { + render(); + expect(screen.getByText('Lendo fontes')).toBeTruthy(); + expect(screen.queryByTitle('Copiar Markdown')).toBeNull(); + }); + + it('assistente finalizado: markdown renderizado e ações de cópia visíveis', () => { + render(); + expect(screen.getByText('cargo build').tagName).toBe('STRONG'); + expect(screen.getByTitle('Copiar Markdown')).toBeTruthy(); + }); + + it('assistente em streaming: texto cru, sem markdown e sem ações', () => { + render(); + expect(screen.getByText('Use **cargo**')).toBeTruthy(); + expect(screen.queryByTitle('Copiar Markdown')).toBeNull(); + }); + + it('assistente vazio em streaming: indicador "Gerando resposta..."', () => { + render(); + expect(screen.getByText('Gerando resposta...')).toBeTruthy(); + }); + + it('bloco e prefixo final: removidos do texto exibido', () => { + render({"a":1}')} />); + expect(screen.getByText('Pergunta final')).toBeTruthy(); + expect(screen.queryByText(/metadata/i)).toBeNull(); + }); + + it('busca com termo presente: marca todas as ocorrências', () => { + const { container } = render(); + expect([...container.querySelectorAll('mark')].map((m) => m.textContent)).toEqual(['rust', 'Rust', 'RUST']); + }); + + it('termo de busca com caractere especial de regex: casa literalmente', () => { + const { container } = render(); + expect([...container.querySelectorAll('mark')].map((m) => m.textContent)).toEqual(['(R$']); + }); + + it.each([ + ['termo com menos de 2 caracteres', { highlightTerm: 'r' }], + ['termo ausente no texto', { highlightTerm: 'python' }], + ['durante o streaming', { highlightTerm: 'rust', isStreaming: true }], + ])('%s: sem marcação', (_n, props) => { + const { container } = render(); + expect(container.querySelector('mark')).toBeNull(); + expect(screen.getByText('rust aqui')).toBeTruthy(); + }); + + it('mensagem de sistema: não aplica destaque', () => { + const { container } = render(); + expect(container.querySelector('mark')).toBeNull(); + }); + + it('assistente com termo de busca: marca o termo no texto', () => { + const { container } = render(); + expect(container.querySelector('mark')?.textContent).toBe('rust'); + }); + + it('destaque não interpreta HTML vindo do conteúdo da mensagem', () => { + render( rust')} highlightTerm="rust" />); + expect(screen.queryByRole('img')).toBeNull(); + expect(screen.getByText(//)).toBeTruthy(); + }); +}); diff --git a/components/chat/mcp-config-panel.test.tsx b/components/chat/mcp-config-panel.test.tsx new file mode 100644 index 0000000..1f45e2f --- /dev/null +++ b/components/chat/mcp-config-panel.test.tsx @@ -0,0 +1,82 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { McpConfigPanel } from './mcp-config-panel'; + +// Comandos Tauri dos servidores MCP e o toast viram fakes; nenhum servidor MCP é iniciado. +const { invokeMock, toast } = vi.hoisted(() => ({ invokeMock: vi.fn(), toast: vi.fn() })); +vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock })); +vi.mock('@/hooks/use-toast', () => ({ useToast: () => ({ toast }) })); + +let saveResult: () => Promise = async () => {}; + +beforeEach(() => { + saveResult = async () => {}; + toast.mockReset(); + invokeMock.mockReset(); + invokeMock.mockImplementation(async (cmd: string) => { + if (cmd === 'load_mcp_config') return { mcpServers: {} }; + if (cmd === 'list_mcp_server_status') return []; + if (cmd === 'get_mcp_config_path_command') return '/cfg/mcp.json'; + if (cmd === 'save_mcp_config') return saveResult(); + throw new Error(`comando inesperado: ${cmd}`); + }); + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); + +async function saveWith(json: string) { + render(); + const editor = await screen.findByRole('textbox'); // durante o carregamento só há o spinner + await waitFor(() => expect((editor as HTMLTextAreaElement).value).toContain('mcpServers')); + fireEvent.change(editor, { target: { value: json } }); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Salvar' }))); +} + +const saved = () => invokeMock.mock.calls.filter(([cmd]) => cmd === 'save_mcp_config').map(([, args]) => args); +const lastToast = () => toast.mock.calls[toast.mock.calls.length - 1][0]; + +describe('McpConfigPanel.saveConfig', () => { + it('JSON em branco: avisa e não salva', async () => { + await saveWith(' '); + expect(lastToast()).toMatchObject({ title: 'Erro', description: expect.stringContaining('JSON vazio') }); + expect(saved()).toEqual([]); + }); + + it('JSON inválido: erro de JSON e não salva', async () => { + await saveWith('{ "mcpServers": '); + expect(lastToast()).toMatchObject({ title: 'Erro de JSON', description: expect.stringContaining('JSON inválido:') }); + expect(saved()).toEqual([]); + }); + + it.each(['null', '"texto"'])('JSON %s (não objeto): avisa e não salva', async (json) => { + await saveWith(json); + expect(lastToast()).toMatchObject({ description: 'Configuração inválida: deve ser um objeto JSON.' }); + expect(saved()).toEqual([]); + }); + + it.each([ + ['sem mcpServers', '{"outro": 1}'], + ['mcpServers não objeto', '{"mcpServers": "x"}'], + ])('%s: salva a estrutura mínima', async (_n, json) => { + await saveWith(json); + expect(saved()).toEqual([{ config: { mcpServers: {} } }]); + }); + + it('config válida: salva só mcpServers, avisa sucesso e recarrega o status', async () => { + const servers = { fs: { command: 'npx', args: ['-y', 'server-fs'] } }; + await saveWith(JSON.stringify({ mcpServers: servers, extra: true })); + expect(saved()).toEqual([{ config: { mcpServers: servers } }]); + expect(lastToast()).toMatchObject({ title: 'Sucesso' }); + expect(invokeMock.mock.calls.filter(([cmd]) => cmd === 'list_mcp_server_status')).toHaveLength(2); + expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe(JSON.stringify({ mcpServers: servers }, null, 2)); + }); + + it.each([ + ['Error', new Error('permissão negada'), 'Falha ao salvar configuração MCP: permissão negada'], + ['string do Rust', 'disco cheio', 'Falha ao salvar configuração MCP: Erro desconhecido'], + ])('backend falha com %s: toast de erro', async (_n, error, description) => { + saveResult = async () => { throw error; }; + await saveWith('{"mcpServers": {}}'); + expect(lastToast()).toMatchObject({ title: 'Erro', description }); + expect(screen.getByRole('button', { name: 'Salvar' })).toHaveProperty('disabled', false); + }); +}); diff --git a/components/chat/mcp-json-editor.test.tsx b/components/chat/mcp-json-editor.test.tsx new file mode 100644 index 0000000..ebb4ded --- /dev/null +++ b/components/chat/mcp-json-editor.test.tsx @@ -0,0 +1,75 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen } from '@testing-library/react'; +import { useState } from 'react'; +import { McpJsonEditor } from './mcp-json-editor'; + +// Tema claro/escuro do realce e o anel vermelho do textarea inválido são só visuais: mapeados sem teste. + +function Controlled({ initial, onChange }: { initial: string; onChange?: (v: string) => void }) { + const [value, setValue] = useState(initial); + return { setValue(v); onChange?.(v); }} />; +} + +const editor = () => screen.getByRole('textbox') as HTMLTextAreaElement; +const formatButton = () => screen.getByRole('button', { name: 'Formatar' }); + +beforeEach(() => { + vi.useFakeTimers({ toFake: ['setTimeout'] }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('McpJsonEditor', () => { + it('vazio: sem erro nem "Válido" e Formatar desativado', () => { + render(); + expect(screen.queryByText('Válido')).toBeNull(); + expect(formatButton()).toHaveProperty('disabled', true); + }); + + it('JSON válido: mostra "Válido" e a contagem de linhas no plural', () => { + render(); + expect(screen.getByText('Válido')).toBeTruthy(); + expect(screen.getByText('3 linhas')).toBeTruthy(); + }); + + it('uma linha: contagem no singular', () => { + render(); + expect(screen.getByText('1 linha')).toBeTruthy(); + }); + + it('digitar JSON inválido: mostra a mensagem do parser e repassa o texto', () => { + const onChange = vi.fn(); + render(); + fireEvent.change(editor(), { target: { value: '{"a":' } }); + expect(onChange).toHaveBeenCalledWith('{"a":'); + expect(screen.queryByText('Válido')).toBeNull(); + expect(screen.getByText(/JSON/)).toBeTruthy(); + }); + + it('Formatar JSON válido: reindenta com 2 espaços e mostra "Formatado" por 2 s', () => { + render(); + fireEvent.click(formatButton()); + expect(editor().value).toBe('{\n "a": {\n "b": 1\n }\n}'); + expect(screen.getByText('Formatado')).toBeTruthy(); + act(() => vi.advanceTimersByTime(2000)); + expect(screen.queryByText('Formatado')).toBeNull(); + }); + + it('Formatar JSON inválido: não altera o texto', () => { + const onChange = vi.fn(); + render(); + fireEvent.click(formatButton()); + expect(onChange).not.toHaveBeenCalled(); + expect(editor().value).toBe('{oops'); + expect(screen.queryByText('Formatado')).toBeNull(); + }); + + it('editar depois de formatar: some o "Formatado"', () => { + render(); + fireEvent.click(formatButton()); + fireEvent.change(editor(), { target: { value: '{"a":2}' } }); + expect(screen.queryByText('Formatado')).toBeNull(); + }); +}); diff --git a/components/chat/message-step-thinking.test.tsx b/components/chat/message-step-thinking.test.tsx new file mode 100644 index 0000000..7b40aec --- /dev/null +++ b/components/chat/message-step-thinking.test.tsx @@ -0,0 +1,64 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen, within } from '@testing-library/react'; +import { MessageStepThinking } from './message-step-thinking'; +import type { ThinkingMessageMetadata } from '@/hooks/use-chat'; + +// getStepIcon só escolhe um ícone lucide sem rótulo acessível: caminho mapeado, sem teste (regra: sem classes CSS). + +function step(extra: Partial = {}): ThinkingMessageMetadata { + return { type: 'thinking', stepType: 'web-research', status: 'completed', label: 'Pesquisando na web', timestamp: 0, ...extra }; +} + +beforeEach(() => { + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); + +describe('MessageStepThinking', () => { + it('sem detalhes, fontes ou erro: mostra o rótulo e nenhum botão de expandir', () => { + render(); + expect(screen.getByText('Pesquisando na web')).toBeTruthy(); + expect(screen.queryByRole('button')).toBeNull(); + }); + + it('com detalhes: só aparecem depois de expandir e somem ao recolher', () => { + render(); + expect(screen.queryByText('3 páginas lidas')).toBeNull(); + fireEvent.click(screen.getByRole('button')); + expect(screen.getByText('3 páginas lidas')).toBeTruthy(); + fireEvent.click(screen.getAllByRole('button')[0]); + expect(screen.queryByText('3 páginas lidas')).toBeNull(); + }); + + it('fontes: link com título ou, sem título, com a própria URL', () => { + render(); + fireEvent.click(screen.getByRole('button')); + expect(screen.getByRole('link', { name: 'Site A' }).getAttribute('href')).toBe('https://a.dev'); + expect(screen.getByRole('link', { name: 'https://b.dev' })).toBeTruthy(); + }); + + it('erro: mostra a mensagem ao expandir', () => { + render(); + fireEvent.click(screen.getByRole('button')); + expect(screen.getByText('timeout na busca')).toBeTruthy(); + }); + + it('copiar fonte: escreve a URL na área de transferência', async () => { + const writeText = vi.fn(async () => {}); + vi.spyOn(navigator, 'clipboard', 'get').mockReturnValue({ writeText } as unknown as Clipboard); + render(); + fireEvent.click(screen.getByRole('button')); + const source = screen.getByRole('link', { name: 'Site A' }).parentElement!; + await act(async () => fireEvent.click(within(source).getByRole('button'))); + expect(writeText).toHaveBeenCalledWith('https://a.dev'); + }); + + it('cópia recusada pelo navegador: registra o erro sem quebrar', async () => { + vi.spyOn(navigator, 'clipboard', 'get').mockReturnValue({ writeText: vi.fn(async () => { throw new Error('negado'); }) } as unknown as Clipboard); + render(); + fireEvent.click(screen.getByRole('button')); + const source = screen.getByRole('link', { name: 'Site A' }).parentElement!; + await act(async () => fireEvent.click(within(source).getByRole('button'))); + expect(console.error).toHaveBeenCalledWith('Failed to copy URL:', expect.any(Error)); + expect(screen.getByRole('link', { name: 'Site A' })).toBeTruthy(); + }); +}); diff --git a/components/chat/model-download-dialog.test.tsx b/components/chat/model-download-dialog.test.tsx new file mode 100644 index 0000000..18aaf41 --- /dev/null +++ b/components/chat/model-download-dialog.test.tsx @@ -0,0 +1,286 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { ModelDownloadDialog } from './model-download-dialog'; + +// Comandos Tauri (pull_model, seletor nativo de arquivo, install_gguf_model) e o evento de progresso viram fakes. +const { invokeMock, listeners } = vi.hoisted(() => ({ + invokeMock: vi.fn(), + listeners: {} as Record void>, +})); +vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock })); +vi.mock('@tauri-apps/api/event', () => ({ + listen: vi.fn(async (name: string, cb: (event: { payload: string }) => void) => { + listeners[name] = cb; + return () => {}; + }), +})); + +const backend = { + installed: false, + pull: (): Promise => Promise.withResolvers().promise, // download em andamento + pickFile: async (): Promise => null, + installGguf: async (_args: unknown): Promise => 'modelo-local', +}; + +beforeEach(() => { + backend.installed = false; + backend.pull = () => Promise.withResolvers().promise; + backend.pickFile = async () => null; + backend.installGguf = async () => 'modelo-local'; + invokeMock.mockReset(); + invokeMock.mockImplementation(async (cmd: string, args: unknown) => { + if (cmd === 'check_if_model_installed') return backend.installed; + if (cmd === 'pull_model') return backend.pull(); + if (cmd === 'open_gguf_file_dialog') return backend.pickFile(); + if (cmd === 'install_gguf_model') return backend.installGguf(args); + throw new Error(`comando inesperado: ${cmd}`); + }); + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); + +async function open(onSuccess: ((name: string) => void) | undefined = vi.fn()) { + const onOpenChange = vi.fn(); + render(); + await waitFor(() => expect(listeners['download-progress']).toBeDefined()); + return { onOpenChange, onSuccess }; +} + +const nameField = () => screen.getByLabelText('Nome do Modelo'); +const progress = (payload: object | string) => + act(() => listeners['download-progress']({ payload: typeof payload === 'string' ? payload : JSON.stringify(payload) })); + +async function startDownload(name = 'llama3.2:1b') { + fireEvent.change(nameField(), { target: { value: name } }); + fireEvent.click(screen.getByRole('button', { name: 'Baixar' })); + await screen.findByText('Iniciando download...'); +} + +describe('ModelDownloadDialog: baixar do Ollama', () => { + it('nome com caractere inválido: botão Baixar desativado e Enter não baixa', async () => { + await open(); + fireEvent.change(nameField(), { target: { value: 'llama 3' } }); + fireEvent.keyDown(nameField(), { key: 'Enter' }); + expect(screen.getByRole('button', { name: 'Baixar' })).toHaveProperty('disabled', true); + expect(invokeMock).not.toHaveBeenCalledWith('pull_model', expect.anything()); + }); + + it.each(['/llama', 'llama:', '-llama'])('nome "%s" com /, : ou - na ponta: botão desativado', async (name) => { + await open(); + fireEvent.change(nameField(), { target: { value: name } }); + expect(screen.getByRole('button', { name: 'Baixar' })).toHaveProperty('disabled', true); + }); + + it('Enter com nome válido: inicia o download do nome aparado', async () => { + await open(); + fireEvent.change(nameField(), { target: { value: ' huihui_ai/qwen3:1.7b ' } }); + fireEvent.keyDown(nameField(), { key: 'Enter' }); + await waitFor(() => expect(invokeMock).toHaveBeenCalledWith('pull_model', { name: 'huihui_ai/qwen3:1.7b' })); + }); + + it('modelo já instalado: avisa e "Usar Modelo" notifica e fecha sem baixar', async () => { + backend.installed = true; + const { onOpenChange, onSuccess } = await open(); + fireEvent.change(nameField(), { target: { value: 'mistral:latest' } }); + expect(await screen.findByText('✓ Este modelo já está instalado')).toBeTruthy(); + fireEvent.click(screen.getByRole('button', { name: 'Usar Modelo' })); + expect(onSuccess).toHaveBeenCalledWith('mistral:latest'); + expect(onOpenChange).toHaveBeenCalledWith(false); + expect(invokeMock).not.toHaveBeenCalledWith('pull_model', expect.anything()); + }); + + it('modelo já instalado e Enter: notifica sem baixar e sem fechar', async () => { + backend.installed = true; + const { onOpenChange, onSuccess } = await open(); + fireEvent.change(nameField(), { target: { value: 'mistral:latest' } }); + await screen.findByText('✓ Este modelo já está instalado'); + fireEvent.keyDown(nameField(), { key: 'Enter' }); + expect(onSuccess).toHaveBeenCalledWith('mistral:latest'); + expect(onOpenChange).not.toHaveBeenCalled(); + }); + + it('pull_model falha com Error: mostra a mensagem e volta ao botão Baixar', async () => { + const pending = Promise.withResolvers(); + backend.pull = () => pending.promise; + await open(); + await startDownload(); + await act(async () => pending.reject(new Error('manifest not found'))); + expect(screen.getByText('manifest not found')).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Baixar' })).toHaveProperty('disabled', false); + }); + + it('pull_model falha sem mensagem: texto genérico', async () => { + backend.pull = async () => { throw 'erro do rust'; }; + await open(); + fireEvent.change(nameField(), { target: { value: 'llama3.2:1b' } }); + fireEvent.click(screen.getByRole('button', { name: 'Baixar' })); + expect(await screen.findByText('Falha no download. Tente novamente.')).toBeTruthy(); + }); +}); + +describe('ModelDownloadDialog: evento download-progress', () => { + it('fora de um download: evento ignorado', async () => { + await open(); + progress({ status: 'pulling', percent: 50, raw: '' }); + expect(screen.queryByText('50%')).toBeNull(); + }); + + it.each([ + ['pulling', 'Baixando modelo...', '10%'], + ['verifying', 'Verificando...', '90%'], + ['writing', 'Salvando...', '95%'], + ['outro', 'Baixando...', '0%'], + ])('status %s sem percent: "%s" e %s', async (status, text, pct) => { + await open(); + await startDownload(); + progress({ status, raw: '' }); + expect(screen.getByText(text, { selector: 'span' })).toBeTruthy(); + expect(screen.getByText(pct)).toBeTruthy(); + }); + + it('pulling sem percent depois de 40%: não regride', async () => { + await open(); + await startDownload(); + progress({ status: 'pulling', percent: 40, raw: '' }); + progress({ status: 'pulling', raw: '' }); + expect(screen.getByText('40%')).toBeTruthy(); + }); + + it('payload que não é JSON: status genérico', async () => { + await open(); + await startDownload(); + progress('pulling manifest'); + expect(screen.getByText('Baixando...', { selector: 'span' })).toBeTruthy(); + }); + + it('baixado, total e velocidade: mostra os três; só baixado: mostra só ele', async () => { + await open(); + await startDownload(); + progress({ status: 'pulling', percent: 20, downloaded: '1 GB', total: '4 GB', speed: '9 MB/s', raw: '' }); + expect(screen.getByText('1 GB / 4 GB')).toBeTruthy(); + expect(screen.getByText('9 MB/s')).toBeTruthy(); + progress({ status: 'pulling', percent: 21, downloaded: '1.1 GB', raw: '' }); + expect(screen.getByText('1.1 GB')).toBeTruthy(); + }); + + it.each([ + ['percent 100', { status: 'pulling', percent: 100, raw: '' }], + ['status success', { status: 'success', raw: '' }], + ])('%s: após 500 ms notifica o modelo e fecha', async (_n, payload) => { + const { onOpenChange, onSuccess } = await open(); + await startDownload('qwen:0.5b'); + progress(payload); + expect(onOpenChange).not.toHaveBeenCalled(); + await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false)); + expect(onSuccess).toHaveBeenCalledWith('qwen:0.5b'); + }); + + it('concluído sem onSuccess: só fecha', async () => { + const { onOpenChange } = await open(undefined); + await startDownload(); + progress({ status: 'success', raw: '' }); + await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false)); + }); +}); + +describe('ModelDownloadDialog: fechar e cancelar', () => { + it('cancelar sem download: fecha', async () => { + const { onOpenChange } = await open(); + fireEvent.click(screen.getByRole('button', { name: 'Cancelar' })); + expect(onOpenChange).toHaveBeenCalledWith(false); + }); + + it.each([ + [true, [[false]]], + [false, []], + ])('cancelar durante download com confirmação %s', async (confirmed, calls) => { + vi.stubGlobal('confirm', vi.fn(() => confirmed)); // happy-dom não implementa window.confirm + const { onOpenChange } = await open(); + await startDownload(); + fireEvent.click(screen.getByRole('button', { name: 'Cancelar' })); + expect(onOpenChange.mock.calls).toEqual(calls); + }); + + it.each([ + [true, [[false]]], + [false, []], + ])('Esc durante download com confirmação %s', async (confirmed, calls) => { + vi.stubGlobal('confirm', vi.fn(() => confirmed)); + const { onOpenChange } = await open(); + await startDownload(); + fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' }); + expect(onOpenChange.mock.calls).toEqual(calls); + }); + + it('Esc sem download: fecha sem perguntar', async () => { + const confirm = vi.fn(() => true); + vi.stubGlobal('confirm', confirm); + const { onOpenChange } = await open(); + fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' }); + expect(onOpenChange).toHaveBeenCalledWith(false); + expect(confirm).not.toHaveBeenCalled(); + }); +}); + +describe('ModelDownloadDialog: instalar GGUF local', () => { + async function openLocal(onSuccess?: (name: string) => void) { + const r = await open(onSuccess); + fireEvent.mouseDown(screen.getByRole('tab', { name: 'Instalar Local' }), { button: 0 }); + await screen.findByRole('button', { name: 'Selecionar arquivo GGUF' }); + return r; + } + + it('seletor cancelado: não instala nada', async () => { + await openLocal(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' }))); + expect(invokeMock).not.toHaveBeenCalledWith('install_gguf_model', expect.anything()); + expect(screen.queryByText('Erro ao instalar modelo')).toBeNull(); + }); + + it('arquivo .GGUF sem nome informado: usa o nome do arquivo sem extensão e fecha depois', async () => { + backend.pickFile = async () => 'C:\\modelos\\Phi-3.GGUF'; + const { onOpenChange, onSuccess } = await openLocal(vi.fn()); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' }))); + expect(invokeMock).toHaveBeenCalledWith('install_gguf_model', { filePath: 'C:\\modelos\\Phi-3.GGUF', modelName: 'Phi-3' }); + await waitFor(() => expect(onSuccess).toHaveBeenCalledWith('modelo-local')); + await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false), { timeout: 2000 }); + }); + + it('nome informado: prevalece sobre o do arquivo; arquivo sem .gguf mantém o nome', async () => { + backend.pickFile = async () => '/home/u/modelo.bin'; + await openLocal(); + fireEvent.change(screen.getByLabelText('Nome do Modelo (opcional)'), { target: { value: ' meu-modelo ' } }); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' }))); + expect(invokeMock).toHaveBeenCalledWith('install_gguf_model', { filePath: '/home/u/modelo.bin', modelName: 'meu-modelo' }); + }); + + it('caminho terminado em barra: usa "model" como nome', async () => { + backend.pickFile = async () => '/home/u/'; + await openLocal(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' }))); + expect(invokeMock).toHaveBeenCalledWith('install_gguf_model', { filePath: '/home/u/', modelName: 'model' }); + }); + + it('instalação falha com Error: mostra a mensagem e volta ao seletor', async () => { + backend.pickFile = async () => '/m/a.gguf'; + backend.installGguf = async () => { throw new Error('Ollama recusou o Modelfile'); }; + await openLocal(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' }))); + expect(await screen.findByText('Ollama recusou o Modelfile')).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })).toBeTruthy(); + }); + + it('instalação falha sem mensagem: texto genérico', async () => { + backend.pickFile = async () => '/m/a.gguf'; + backend.installGguf = async () => { throw 'falhou'; }; + await openLocal(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' }))); + expect(await screen.findByText('Erro ao instalar modelo GGUF')).toBeTruthy(); + }); + + it('seletor nativo falha: avisa que não abriu', async () => { + backend.pickFile = async () => { throw new Error('sem portal xdg'); }; + await openLocal(); + await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' }))); + expect(await screen.findByText('Erro ao abrir seletor de arquivo')).toBeTruthy(); + }); +}); diff --git a/components/chat/prompt-generator.test.tsx b/components/chat/prompt-generator.test.tsx new file mode 100644 index 0000000..3e144e2 --- /dev/null +++ b/components/chat/prompt-generator.test.tsx @@ -0,0 +1,112 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { PromptGeneratorDialog } from './prompt-generator'; +import type { LocalModel } from '@/hooks/use-local-models'; + +// Hooks que falam com o Ollama/Tauri viram fakes controlados pelo teste. +const state = vi.hoisted(() => ({ + models: [] as LocalModel[], + loading: false, + generatePrompt: vi.fn(), +})); +vi.mock('@/hooks/use-local-models', () => ({ useLocalModels: () => ({ models: state.models, loading: state.loading }) })); +vi.mock('@/hooks/use-prompt-generator', () => ({ + usePromptGenerator: () => ({ generatePrompt: state.generatePrompt, isGenerating: false }), +})); + +const model = (name: string): LocalModel => ({ name, size: '1 GB', id: name, modified_at: '' }); + +function openWithGoal(defaultModel: string, onPromptGenerated = vi.fn()) { + render(); + fireEvent.click(screen.getByTitle('Gerar com IA')); + fireEvent.change(screen.getByLabelText('Seu Objetivo'), { target: { value: 'assistente de Python' } }); + return { onPromptGenerated, generate: screen.getByRole('button', { name: 'Gerar Prompt' }) }; +} + +beforeEach(() => { + state.models = []; + state.loading = false; + state.generatePrompt.mockReset(); + state.generatePrompt.mockResolvedValue('PROMPT GERADO'); +}); + +describe('PromptGeneratorDialog: escolha do modelo', () => { + it('modelo padrão instalado: gera com ele', async () => { + state.models = [model('mistral'), model('llama3')]; + const { generate } = openWithGoal('llama3'); + fireEvent.click(generate); + await waitFor(() => expect(state.generatePrompt).toHaveBeenCalledWith('assistente de Python', 'llama3')); + }); + + it('sem padrão e com o modelo preferido instalado: usa o preferido', async () => { + state.models = [model('mistral'), model('llama3.2-abliterate:3b')]; + const { generate } = openWithGoal(''); + fireEvent.click(generate); + await waitFor(() => expect(state.generatePrompt).toHaveBeenCalledWith('assistente de Python', 'llama3.2-abliterate:3b')); + }); + + it('sem padrão e sem o preferido: usa o primeiro modelo da lista', async () => { + state.models = [model('mistral'), model('qwen')]; + const { generate } = openWithGoal(' '); + fireEvent.click(generate); + await waitFor(() => expect(state.generatePrompt).toHaveBeenCalledWith('assistente de Python', 'mistral')); + }); + + it('padrão não instalado, mesmo com o preferido presente: mantém o padrão', async () => { + state.models = [model('llama3.2-abliterate:3b')]; + const { generate } = openWithGoal('removido'); + fireEvent.click(generate); + await waitFor(() => expect(state.generatePrompt).toHaveBeenCalledWith('assistente de Python', 'removido')); + }); + + it('modelos carregando: não escolhe nenhum e o botão fica desativado', () => { + state.loading = true; + state.models = [model('mistral')]; + const { generate } = openWithGoal(''); + expect(screen.getByText('Carregando modelos...')).toBeTruthy(); + expect(generate).toHaveProperty('disabled', true); + }); + + it('nenhum modelo instalado: avisa e o botão fica desativado', () => { + const { generate } = openWithGoal(''); + expect(screen.getByText('Nenhum modelo disponível')).toBeTruthy(); + expect(generate).toHaveProperty('disabled', true); + }); +}); + +describe('PromptGeneratorDialog: geração', () => { + it('objetivo em branco: botão desativado', () => { + state.models = [model('mistral')]; + render(); + fireEvent.click(screen.getByTitle('Gerar com IA')); + expect(screen.getByRole('button', { name: 'Gerar Prompt' })).toHaveProperty('disabled', true); + }); + + it('sucesso: entrega o prompt e fecha o diálogo', async () => { + state.models = [model('mistral')]; + const { generate, onPromptGenerated } = openWithGoal('mistral'); + fireEvent.click(generate); + await waitFor(() => expect(onPromptGenerated).toHaveBeenCalledWith('PROMPT GERADO')); + await waitFor(() => expect(screen.queryByText('Gerador de Prompts')).toBeNull()); + }); + + it('falha na geração: não entrega prompt e mantém o diálogo aberto com o objetivo', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + state.models = [model('mistral')]; + state.generatePrompt.mockRejectedValue(new Error('ollama caiu')); + const { generate, onPromptGenerated } = openWithGoal('mistral'); + fireEvent.click(generate); + await waitFor(() => expect(state.generatePrompt).toHaveBeenCalled()); + expect(onPromptGenerated).not.toHaveBeenCalled(); + expect((screen.getByLabelText('Seu Objetivo') as HTMLTextAreaElement).value).toBe('assistente de Python'); + }); + + it('cancelar: fecha e limpa o objetivo', async () => { + state.models = [model('mistral')]; + openWithGoal('mistral'); + fireEvent.click(screen.getByRole('button', { name: 'Cancelar' })); + await waitFor(() => expect(screen.queryByText('Gerador de Prompts')).toBeNull()); + fireEvent.click(screen.getByTitle('Gerar com IA')); + expect((screen.getByLabelText('Seu Objetivo') as HTMLTextAreaElement).value).toBe(''); + }); +}); diff --git a/components/chat/sidebar-list.test.tsx b/components/chat/sidebar-list.test.tsx new file mode 100644 index 0000000..c6c1931 --- /dev/null +++ b/components/chat/sidebar-list.test.tsx @@ -0,0 +1,172 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen, within } from '@testing-library/react'; +import { SidebarList } from './sidebar-list'; +import type { SessionSummary } from '@/hooks/use-chat-storage'; + +// Destaque visual do item selecionado e tooltip de título longo ficam mapeados sem teste (CSS/hover). + +const NOW = new Date('2026-06-15T12:00:00'); + +function session(id: string, extra: Partial = {}): SessionSummary { + return { id, title: `Conversa ${id}`, emoji: '🦀', updated_at: NOW.toISOString(), preview: '', platform: 'Linux', ...extra }; +} + +function renderList(props: Partial[0]> = {}) { + const handlers = { onSelectSession: vi.fn(), onDeleteSession: vi.fn(), onNewChat: vi.fn(), onSearch: vi.fn(), onNavigateMatch: vi.fn() }; + render(); + return handlers; +} + +const card = (title: string) => screen.getByRole('heading', { name: title }).closest('[role="button"]') as HTMLElement; + +beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }); + vi.setSystemTime(NOW); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('SidebarList: lista', () => { + it('sem conversas e sem busca: convida a começar', () => { + renderList(); + expect(screen.getByText('Nenhuma conversa salva')).toBeTruthy(); + }); + + it('sem conversas durante busca: avisa que nada foi encontrado', () => { + renderList({ searchQuery: 'rust' }); + expect(screen.getByText('Nenhuma conversa encontrada')).toBeTruthy(); + }); + + it('clique, Enter e espaço no card: selecionam a conversa; outra tecla não', () => { + const h = renderList({ sessions: [session('a')] }); + fireEvent.click(card('Conversa a')); + fireEvent.keyDown(card('Conversa a'), { key: 'Enter' }); + fireEvent.keyDown(card('Conversa a'), { key: ' ' }); + fireEvent.keyDown(card('Conversa a'), { key: 'a' }); + expect(h.onSelectSession.mock.calls).toEqual([['a'], ['a'], ['a']]); + }); + + it('excluir: chama onDeleteSession sem selecionar a conversa', () => { + const h = renderList({ sessions: [session('a')] }); + fireEvent.click(screen.getByRole('button', { name: 'Deletar conversa "Conversa a"' })); + expect(h.onDeleteSession).toHaveBeenCalledWith('a'); + expect(h.onSelectSession).not.toHaveBeenCalled(); + }); + + it('sem emoji: usa 💬', () => { + renderList({ sessions: [session('a', { emoji: '' })] }); + expect(within(card('Conversa a')).getByText('💬')).toBeTruthy(); + }); + + it.each([ + [1, '1 ocorrência'], + [3, '3 ocorrências'], + ])('busca com %i ocorrência(s): mostra "%s"', (count, text) => { + renderList({ sessions: [session('a', { match_count: count })], searchQuery: 'rust' }); + expect(screen.getByText(text)).toBeTruthy(); + }); + + it('ocorrências sem busca ativa: não mostra contagem', () => { + renderList({ sessions: [session('a', { match_count: 2 })] }); + expect(screen.queryByText(/ocorrências/)).toBeNull(); + }); + + it('selecionada com ocorrências: navegação anterior/próxima sem reselecionar', () => { + const h = renderList({ sessions: [session('a', { match_count: 2 })], searchQuery: 'rust', currentSessionId: 'a' }); + fireEvent.click(screen.getByRole('button', { name: 'Ocorrência anterior' })); + fireEvent.click(screen.getByRole('button', { name: 'Próxima ocorrência' })); + expect(h.onNavigateMatch.mock.calls).toEqual([['a', 'prev'], ['a', 'next']]); + expect(h.onSelectSession).not.toHaveBeenCalled(); + }); + + it.each([ + ['não selecionada', { currentSessionId: 'b' }], + ['sem ocorrências', { currentSessionId: 'a', sessions: [session('a', { match_count: 0 })] }], + ['sem onNavigateMatch', { currentSessionId: 'a', onNavigateMatch: undefined }], + ])('%s: sem botões de navegação', (_n, extra) => { + renderList({ sessions: [session('a', { match_count: 2 })], searchQuery: 'rust', ...extra }); + expect(screen.queryByRole('button', { name: 'Próxima ocorrência' })).toBeNull(); + }); + + it.each([ + ['hoje', '2026-06-15T09:30:00', '09:30'], + ['ontem', '2026-06-14T09:00:00', 'Ontem'], + ['há 3 dias', '2026-06-12T09:00:00', 'sex.'], + ['há 2 meses', '2026-04-10T09:00:00', '10/04'], + ['há 2 anos', '2024-04-10T09:00:00', '10/04/2024'], + ])('data %s: "%s"', (_n, iso, text) => { + renderList({ sessions: [session('a', { updated_at: new Date(iso).toISOString() })] }); + expect(within(card('Conversa a')).getByText(text)).toBeTruthy(); + }); +}); + +describe('SidebarList: busca', () => { + const field = () => screen.getByPlaceholderText('Buscar conversas...'); + + it('digitar 2+ caracteres: busca após 300 ms com o texto aparado', () => { + const h = renderList(); + h.onSearch.mockClear(); + fireEvent.change(field(), { target: { value: ' ru ' } }); + act(() => vi.advanceTimersByTime(299)); + expect(h.onSearch).not.toHaveBeenCalled(); + act(() => vi.advanceTimersByTime(1)); + expect(h.onSearch).toHaveBeenCalledWith('ru'); + }); + + it('digitar só 1 caractere: não busca', () => { + const h = renderList(); + h.onSearch.mockClear(); + fireEvent.change(field(), { target: { value: 'r' } }); + act(() => vi.advanceTimersByTime(1000)); + expect(h.onSearch).not.toHaveBeenCalled(); + }); + + it('digitação rápida: só a última busca dispara', () => { + const h = renderList(); + h.onSearch.mockClear(); + fireEvent.change(field(), { target: { value: 'ru' } }); + act(() => vi.advanceTimersByTime(200)); + fireEvent.change(field(), { target: { value: 'rust' } }); + act(() => vi.advanceTimersByTime(300)); + expect(h.onSearch.mock.calls).toEqual([['rust']]); + }); + + it('apagar o texto: limpa a busca na hora', () => { + const h = renderList(); + fireEvent.change(field(), { target: { value: 'rust' } }); + h.onSearch.mockClear(); + fireEvent.change(field(), { target: { value: '' } }); + expect(h.onSearch).toHaveBeenCalledWith(''); + }); + + it('botão limpar: esvazia o campo e a busca', () => { + const h = renderList(); + fireEvent.change(field(), { target: { value: 'rust' } }); + h.onSearch.mockClear(); + fireEvent.click(screen.getByRole('button', { name: 'Limpar busca' })); + expect((field() as HTMLInputElement).value).toBe(''); + expect(h.onSearch).toHaveBeenCalledWith(''); + }); + + it('buscando: esconde o botão limpar', () => { + renderList({ isSearching: true }); + fireEvent.change(field(), { target: { value: 'rust' } }); + expect(screen.queryByRole('button', { name: 'Limpar busca' })).toBeNull(); + }); + + it('sem onSearch: digitar e limpar não quebram a lista', () => { + renderList({ onSearch: undefined, sessions: [session('a')] }); + fireEvent.change(field(), { target: { value: 'rust' } }); + act(() => vi.advanceTimersByTime(300)); + fireEvent.click(screen.getByRole('button', { name: 'Limpar busca' })); + expect(screen.getByRole('heading', { name: 'Conversa a' })).toBeTruthy(); + }); + + it('nova conversa: chama onNewChat', () => { + const h = renderList(); + fireEvent.click(screen.getByRole('button', { name: 'Nova Conversa' })); + expect(h.onNewChat).toHaveBeenCalled(); + }); +}); diff --git a/components/setup/model-selector.test.tsx b/components/setup/model-selector.test.tsx new file mode 100644 index 0000000..2e671b6 --- /dev/null +++ b/components/setup/model-selector.test.tsx @@ -0,0 +1,134 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { ModelSelector } from './model-selector'; + +// Comandos Tauri (pull_model etc.) e o evento download-progress viram fakes. +const { invokeMock, emit } = vi.hoisted(() => { + const listeners: Record void> = {}; + return { + invokeMock: vi.fn(), + emit: Object.assign((payload: unknown) => listeners['download-progress']({ payload: typeof payload === 'string' ? payload : JSON.stringify(payload) }), { listeners }), + }; +}); +vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock })); +vi.mock('@tauri-apps/api/event', () => ({ + listen: vi.fn(async (name: string, cb: (event: { payload: string }) => void) => { + emit.listeners[name] = cb; + return () => {}; + }), +})); + +let installed = false; +let pull: () => Promise = () => Promise.withResolvers().promise; // download em andamento + +beforeEach(() => { + installed = false; + pull = () => Promise.withResolvers().promise; + invokeMock.mockReset(); + invokeMock.mockImplementation(async (cmd: string) => { + if (cmd === 'check_if_model_installed') return installed; + if (cmd === 'pull_model') return pull(); + throw new Error(`comando inesperado: ${cmd}`); + }); + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); + +async function startDownload(modelId = 'llama3.2:3b') { + const onComplete = vi.fn(); + render(); + await waitFor(() => expect(emit.listeners['download-progress']).toBeDefined()); + fireEvent.click(screen.getByRole('button', { name: /Baixar e Instalar/ })); + await screen.findByText('Iniciando download...'); + return onComplete; +} + +describe('ModelSelector', () => { + it('modelo já instalado: oferece ir para o chat e chama onComplete', async () => { + installed = true; + const onComplete = vi.fn(); + render(); + fireEvent.click(await screen.findByRole('button', { name: /Ir para o Chat/ })); + expect(onComplete).toHaveBeenCalled(); + }); + + it('recomendação fora da lista: botão usa o tamanho do primeiro modelo', async () => { + render(); + expect(await screen.findByRole('button', { name: 'Baixar e Instalar (1.3GB)' })).toBeTruthy(); + }); + + it('pull_model falha: volta ao botão de baixar habilitado e zera o progresso', async () => { + const { promise, reject: fail } = Promise.withResolvers(); + pull = () => promise; + await startDownload(); + await act(async () => fail(new Error('sem rede'))); + const button = await screen.findByRole('button', { name: /Baixar e Instalar/ }); + expect(button).toHaveProperty('disabled', false); + expect(screen.queryByText('0%')).toBeNull(); + }); +}); + +describe('ModelSelector: evento download-progress', () => { + it.each([ + ['pulling', 'Baixando modelo...'], + ['verifying', 'Verificando...'], + ['writing', 'Salvando...'], + ['outro', 'Baixando...'], + ])('status %s sem percent: texto "%s"', async (status, text) => { + await startDownload(); + act(() => emit({ status, raw: '' })); + expect(screen.getByText(text, { selector: 'span' })).toBeTruthy(); + }); + + it('percent informado: mostra o percentual e tamanho/velocidade', async () => { + await startDownload(); + act(() => emit({ status: 'pulling', percent: 42, downloaded: '1 GB', total: '2 GB', speed: '5 MB/s', raw: '' })); + expect(screen.getByText('42%')).toBeTruthy(); + expect(screen.getByText('1 GB / 2 GB')).toBeTruthy(); + expect(screen.getByText('5 MB/s')).toBeTruthy(); + }); + + it('pulling sem percent: progresso sobe para no mínimo 10%', async () => { + await startDownload(); + act(() => emit({ status: 'pulling', raw: '' })); + expect(screen.getByText('10%')).toBeTruthy(); + }); + + it('pulling sem percent depois de 42%: não regride', async () => { + await startDownload(); + act(() => emit({ status: 'pulling', percent: 42, raw: '' })); + act(() => emit({ status: 'pulling', raw: '' })); + expect(screen.getByText('42%')).toBeTruthy(); + }); + + it('verifying sem percent: 90%; writing sem percent: 95%', async () => { + await startDownload(); + act(() => emit({ status: 'verifying', raw: '' })); + expect(screen.getByText('90%')).toBeTruthy(); + act(() => emit({ status: 'writing', raw: '' })); + expect(screen.getByText('95%')).toBeTruthy(); + }); + + it('payload que não é JSON: trata como download em andamento sem mudar o progresso', async () => { + await startDownload(); + act(() => emit('pulling manifest')); + expect(screen.getByText('Baixando...', { selector: 'span' })).toBeTruthy(); + expect(screen.getByText('0%')).toBeTruthy(); + }); + + it('downloaded sem total: mostra só o baixado', async () => { + await startDownload(); + act(() => emit({ status: 'pulling', percent: 5, downloaded: '300 MB', raw: '' })); + expect(screen.getByText('300 MB')).toBeTruthy(); + }); + + it.each([ + ['percent 100', { status: 'pulling', percent: 100, raw: '' }], + ['status success', { status: 'success', raw: '' }], + ])('%s: após 500 ms marca instalado e oferece ir para o chat', async (_n, payload) => { + await startDownload(); + installed = true; + act(() => emit(payload)); + expect(screen.queryByRole('button', { name: /Ir para o Chat/ })).toBeNull(); + expect(await screen.findByRole('button', { name: /Ir para o Chat/ }, { timeout: 2000 })).toBeTruthy(); + }); +}); diff --git a/vitest.config.mts b/vitest.config.mts index 0435a49..7fef8ec 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -8,8 +8,9 @@ export default defineConfig({ alias: [{ find: /^@\//, replacement: fileURLToPath(new URL('./', import.meta.url)) }], }, test: { - include: ['{lib,hooks,services}/**/*.test.ts'], + include: ['{lib,hooks,services}/**/*.test.ts', '{app,components}/**/*.test.tsx'], environment: 'happy-dom', // localStorage para o persist do zustand e DOM para renderHook + setupFiles: ['./vitest.setup.ts'], restoreMocks: true, unstubGlobals: true, }, diff --git a/vitest.setup.ts b/vitest.setup.ts new file mode 100644 index 0000000..46ea624 --- /dev/null +++ b/vitest.setup.ts @@ -0,0 +1,5 @@ +import { afterEach } from 'vitest'; +import { cleanup } from '@testing-library/react'; + +// Sem `globals: true` o Testing Library não registra o cleanup sozinho. +afterEach(cleanup);