test: caminhos-base de lib, hooks e services
This commit is contained in:
1 parent
9d911603f7
commit
adc37e1921
18 files changed
+2961
-142
No files matched your search
@@ -0,0 +1,276 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { useChatStorage, type SessionSummary } from './use-chat-storage';
|
||||
import type { Message } from './use-chat';
|
||||
|
||||
// Backend Tauri e Ollama (fetch para localhost:11434) viram fakes: nenhum modelo é chamado.
|
||||
const invokeMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));
|
||||
|
||||
let storedSessions: SessionSummary[] = [];
|
||||
let saveError: unknown = null;
|
||||
|
||||
function session(id: string, title: string): SessionSummary {
|
||||
return { id, title, emoji: '💬', updated_at: '2026-01-01', preview: '', platform: 'Linux' };
|
||||
}
|
||||
|
||||
function ollama(reply: { ok?: boolean; status?: number; content?: unknown } | Error) {
|
||||
const fetchMock = vi.fn(async () => {
|
||||
if (reply instanceof Error) throw reply;
|
||||
return {
|
||||
ok: reply.ok ?? true,
|
||||
status: reply.status ?? 200,
|
||||
json: async () => (reply.content === undefined ? {} : { message: { content: reply.content } }),
|
||||
};
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
return fetchMock;
|
||||
}
|
||||
|
||||
const saves = () =>
|
||||
invokeMock.mock.calls.filter(([cmd]) => cmd === 'save_chat_session').map(([, args]) => args as {
|
||||
id: string; title: string; messages: Message[]; platform: string; memory_context: string[];
|
||||
});
|
||||
|
||||
async function mount() {
|
||||
const hook = renderHook(() => useChatStorage());
|
||||
await waitFor(() => expect(invokeMock).toHaveBeenCalledWith('load_chat_sessions'));
|
||||
await act(async () => {});
|
||||
return hook;
|
||||
}
|
||||
|
||||
const user = (content: string): Message => ({ role: 'user', content });
|
||||
const bot = (content: string, metadata?: unknown): Message => ({ role: 'assistant', content, metadata });
|
||||
|
||||
beforeEach(() => {
|
||||
storedSessions = [];
|
||||
saveError = null;
|
||||
invokeMock.mockReset();
|
||||
invokeMock.mockImplementation(async (cmd: string) => {
|
||||
if (cmd === 'load_chat_sessions') return storedSessions;
|
||||
if (cmd === 'save_chat_session') {
|
||||
if (saveError) throw saveError;
|
||||
return undefined;
|
||||
}
|
||||
throw new Error(`comando inesperado: ${cmd}`);
|
||||
});
|
||||
vi.spyOn(navigator, 'platform', 'get').mockReturnValue('Linux x86_64');
|
||||
for (const level of ['log', 'warn', 'error'] as const) vi.spyOn(console, level).mockImplementation(() => {});
|
||||
});
|
||||
|
||||
describe('generateTitleFromUserMessage', () => {
|
||||
it('modelo responde título: devolve o título limpo', async () => {
|
||||
ollama({ content: ' Receita de bolo ' });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('como faço bolo?')).toBe('Receita de bolo');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['404 (modelo ausente)', 404],
|
||||
['500 (erro do servidor)', 500],
|
||||
['400 (outro erro)', 400],
|
||||
])('HTTP %s: usa a mensagem do usuário', async (_n, status) => {
|
||||
ollama({ ok: false, status });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage(' pergunta curta ')).toBe('pergunta curta');
|
||||
});
|
||||
|
||||
it('fetch rejeita (Ollama fora do ar): usa a mensagem do usuário', async () => {
|
||||
ollama(new TypeError('Failed to fetch'));
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('oi')).toBe('oi');
|
||||
});
|
||||
|
||||
it('resposta sem message.content: usa a mensagem do usuário', async () => {
|
||||
ollama({});
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('oi')).toBe('oi');
|
||||
});
|
||||
|
||||
it('título entre aspas: remove as aspas', async () => {
|
||||
ollama({ content: `"'Viagem a Roma'"` });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('x')).toBe('Viagem a Roma');
|
||||
});
|
||||
|
||||
it('título só com pontuação: usa a mensagem do usuário', async () => {
|
||||
ollama({ content: '"..."' });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('pergunta')).toBe('pergunta');
|
||||
});
|
||||
|
||||
it('título só com bloco <metadata>: usa a mensagem do usuário', async () => {
|
||||
ollama({ content: '<metadata>{"a":1}</metadata>' });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('pergunta')).toBe('pergunta');
|
||||
});
|
||||
|
||||
it('título com mais de 60 caracteres: corta em 60 e põe reticências', async () => {
|
||||
ollama({ content: 'x'.repeat(80) });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('p')).toBe('x'.repeat(60) + '...');
|
||||
});
|
||||
|
||||
it('fallback com mensagem acima de 50 caracteres: corta em 50 e põe reticências', async () => {
|
||||
ollama({ ok: false, status: 404 });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('y'.repeat(70))).toBe('y'.repeat(50) + '...');
|
||||
});
|
||||
|
||||
it('fallback com mensagem em branco: "Nova Conversa"', async () => {
|
||||
ollama({ ok: false, status: 404 });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage(' ')).toBe('Nova Conversa');
|
||||
});
|
||||
});
|
||||
|
||||
describe('saveSession', () => {
|
||||
it('sem mensagens: não salva', async () => {
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', []));
|
||||
expect(saves()).toEqual([]);
|
||||
});
|
||||
|
||||
it('sessão existente com título: salva com o título atual e as keywords de string sem repetir', async () => {
|
||||
storedSessions = [session('s1', 'Título salvo')];
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [
|
||||
user('q'),
|
||||
bot('a', { keywords: ['rust', 'tauri', 7] }),
|
||||
bot('b', { keywords: ['rust'] }),
|
||||
bot('c', { keywords: 'não é lista' }),
|
||||
user('d'),
|
||||
]));
|
||||
expect(saves()).toEqual([expect.objectContaining({ id: 's1', title: 'Título salvo', platform: 'Linux x86_64', memory_context: ['rust', 'tauri'] })]);
|
||||
});
|
||||
|
||||
it('sessão existente e currentTitle informado: currentTitle prevalece', async () => {
|
||||
storedSessions = [session('s1', 'Antigo')];
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q')], 'Renomeado'));
|
||||
expect(saves()[0].title).toBe('Renomeado');
|
||||
});
|
||||
|
||||
it('sessão existente: falha ao salvar não propaga nem recarrega a lista', async () => {
|
||||
storedSessions = [session('s1', 'Antigo')];
|
||||
saveError = new Error('disco cheio');
|
||||
const { result } = await mount();
|
||||
const loadsBefore = invokeMock.mock.calls.filter(([c]) => c === 'load_chat_sessions').length;
|
||||
await act(() => result.current.saveSession('s1', [user('q')]));
|
||||
expect(invokeMock.mock.calls.filter(([c]) => c === 'load_chat_sessions')).toHaveLength(loadsBefore);
|
||||
});
|
||||
|
||||
it('platform vazio: usa o primeiro token do userAgent', async () => {
|
||||
storedSessions = [session('s1', 'Antigo')];
|
||||
vi.spyOn(navigator, 'platform', 'get').mockReturnValue('');
|
||||
vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue('Mozilla/5.0 (X11)');
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q')]));
|
||||
expect(saves()[0].platform).toBe('Mozilla/5.0');
|
||||
});
|
||||
|
||||
it('sessão nova com só a mensagem do usuário: espera a resposta e não salva', async () => {
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q')]));
|
||||
expect(saves()).toEqual([]);
|
||||
});
|
||||
|
||||
it('sessão existente com "Nova Conversa" e 1 mensagem: tratada como nova, não salva', async () => {
|
||||
storedSessions = [session('s1', 'Nova Conversa')];
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q')]));
|
||||
expect(saves()).toEqual([]);
|
||||
});
|
||||
|
||||
it('sessão nova com currentTitle: salva já com ele, sem chamar o modelo', async () => {
|
||||
const fetchMock = ollama({ content: 'não usar' });
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a')], 'Dado'));
|
||||
expect(saves()[0].title).toBe('Dado');
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sessão nova com metadata.title: usa o título aparado', async () => {
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a', { title: ' Do modelo ', summary: 'resumo' })]));
|
||||
expect(saves()[0].title).toBe('Do modelo');
|
||||
});
|
||||
|
||||
it('sessão nova com só metadata.summary: usa o resumo', async () => {
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a', { summary: ' Resumo ' })]));
|
||||
expect(saves()[0].title).toBe('Resumo');
|
||||
});
|
||||
|
||||
it('metadata.title em branco: passa para a próxima resposta do assistente', async () => {
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a', { title: ' ' }), bot('b', { summary: 'Segundo' })]));
|
||||
expect(saves()[0].title).toBe('Segundo');
|
||||
});
|
||||
|
||||
it('metadata.summary em branco: segue para a próxima resposta', async () => {
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a', { summary: ' ' }), bot('b', { title: 'Terceiro' })]));
|
||||
expect(saves()[0].title).toBe('Terceiro');
|
||||
});
|
||||
|
||||
it('sessão nova com metadata.title: falha ao salvar não propaga', async () => {
|
||||
saveError = new Error('disco cheio');
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a', { title: 'T' })]));
|
||||
expect(saves()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('sem título em metadata: gera com o modelo usando até 4 mensagens sem metadata e salva', async () => {
|
||||
const fetchMock = ollama({ content: 'Título gerado' });
|
||||
const { result } = await mount();
|
||||
const msgs = [user('q1'), bot('r1 <metadata>{"x":1}</metadata>'), user('q2'), bot('r2'), user('q3')];
|
||||
await act(() => result.current.saveSession('s1', msgs));
|
||||
await waitFor(() => expect(saves()).toHaveLength(1));
|
||||
expect(saves()[0].title).toBe('Título gerado');
|
||||
const sent = JSON.parse((fetchMock.mock.calls[0] as unknown as [string, { body: string }])[1].body).messages;
|
||||
expect(sent.slice(1).map((m: Message) => m.content)).toEqual(['q1', 'r1', 'q2', 'r2']);
|
||||
expect(result.current.isGeneratingTitle).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['HTTP 404', { ok: false, status: 404 }],
|
||||
['HTTP 400', { ok: false, status: 400 }],
|
||||
['resposta vazia', { content: '' }],
|
||||
['título só pontuação', { content: '"!!"' }],
|
||||
['erro de rede', new Error('Failed to fetch')],
|
||||
])('geração falha (%s): salva com o início da primeira pergunta', async (_n, reply) => {
|
||||
ollama(reply);
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [bot('olá'), user(`${'p'.repeat(60)} <metadata>{}</metadata>`)]));
|
||||
await waitFor(() => expect(saves()).toHaveLength(1));
|
||||
expect(saves()[0].title).toBe('p'.repeat(50) + '...');
|
||||
expect(result.current.isGeneratingTitle).toBe(false);
|
||||
});
|
||||
|
||||
it('geração falha e não há mensagem do usuário: "Nova Conversa"', async () => {
|
||||
ollama({ ok: false, status: 404 });
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [bot('a'), bot('b')]));
|
||||
await waitFor(() => expect(saves()).toHaveLength(1));
|
||||
expect(saves()[0].title).toBe('Nova Conversa');
|
||||
});
|
||||
|
||||
it('título gerado mas falha ao salvar: libera isGeneratingTitle', async () => {
|
||||
ollama({ content: 'Ok' });
|
||||
saveError = new Error('disco cheio');
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a')]));
|
||||
await waitFor(() => expect(saves()).toHaveLength(1));
|
||||
await waitFor(() => expect(result.current.isGeneratingTitle).toBe(false));
|
||||
});
|
||||
|
||||
it('geração de título já em andamento: não dispara outra', async () => {
|
||||
const fetchMock = ollama({ content: 'x' });
|
||||
const { result } = await mount();
|
||||
act(() => result.current.setIsGeneratingTitle(true));
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a')]));
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(saves()).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,265 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { detectToolCalls, useChat, type Message } from './use-chat';
|
||||
import { useSettingsStore } from '@/store/settings-store';
|
||||
|
||||
// Backend Tauri e eventos de streaming do Ollama viram fakes em processo.
|
||||
const { invokeMock, handlers } = vi.hoisted(() => ({
|
||||
invokeMock: vi.fn(),
|
||||
handlers: {} as Record<string, (event: { payload: unknown }) => void>,
|
||||
}));
|
||||
vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));
|
||||
vi.mock('@tauri-apps/api/event', () => ({
|
||||
listen: vi.fn(async (name: string, cb: (event: { payload: unknown }) => void) => {
|
||||
handlers[name] = cb;
|
||||
return () => {};
|
||||
}),
|
||||
}));
|
||||
|
||||
function backend({ running = true as boolean | Error, stream = undefined as unknown } = {}) {
|
||||
invokeMock.mockImplementation(async (cmd: string) => {
|
||||
if (cmd === 'check_ollama_running') {
|
||||
if (running instanceof Error) throw running;
|
||||
return running;
|
||||
}
|
||||
if (cmd === 'chat_stream') {
|
||||
if (stream !== undefined) throw stream;
|
||||
return undefined;
|
||||
}
|
||||
throw new Error(`comando inesperado: ${cmd}`);
|
||||
});
|
||||
}
|
||||
|
||||
const streamCall = () => invokeMock.mock.calls.find(([cmd]) => cmd === 'chat_stream')?.[1] as
|
||||
| { sessionId: string | null; messages: Array<{ role: string; content: string }>; systemPrompt: string | null }
|
||||
| undefined;
|
||||
|
||||
async function mount(history: Message[] = []) {
|
||||
const hook = renderHook(() => useChat());
|
||||
await waitFor(() => expect(handlers['chat-token']).toBeDefined());
|
||||
if (history.length) act(() => hook.result.current.setMessages(history));
|
||||
return hook;
|
||||
}
|
||||
|
||||
const lastContent = (messages: Message[]) => messages[messages.length - 1].content;
|
||||
|
||||
beforeEach(() => {
|
||||
invokeMock.mockReset();
|
||||
for (const k of Object.keys(handlers)) delete handlers[k];
|
||||
localStorage.clear();
|
||||
useSettingsStore.setState({ contextWindow: 4096 });
|
||||
for (const level of ['log', 'warn', 'error', 'group', 'groupEnd'] as const) vi.spyOn(console, level).mockImplementation(() => {});
|
||||
});
|
||||
|
||||
describe('useChat.sendMessage', () => {
|
||||
it('mensagem nova: adiciona a do usuário e um assistente vazio e chama chat_stream', async () => {
|
||||
backend();
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.sendMessage('oi modelo', 'llama3'));
|
||||
expect(result.current.messages).toEqual([
|
||||
{ role: 'user', content: 'oi modelo' },
|
||||
{ role: 'assistant', content: '' },
|
||||
]);
|
||||
expect(streamCall()).toMatchObject({ sessionId: null, systemPrompt: null, messages: [{ role: 'user', content: 'oi modelo' }] });
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
it('última mensagem já é a mesma do usuário: não duplica', async () => {
|
||||
backend();
|
||||
const { result } = await mount([{ role: 'user', content: 'repetida' }]);
|
||||
await act(() => result.current.sendMessage('repetida', 'm'));
|
||||
expect(result.current.messages.filter((m) => m.role === 'user')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('última mensagem do usuário com outro texto: adiciona a nova', async () => {
|
||||
backend();
|
||||
const { result } = await mount([{ role: 'user', content: 'antiga' }]);
|
||||
await act(() => result.current.sendMessage('nova', 'm'));
|
||||
expect(result.current.messages.map((m) => m.content)).toEqual(['antiga', 'nova', '']);
|
||||
});
|
||||
|
||||
it('onBeforeModelRequest recebe as mensagens pendentes antes do modelo', async () => {
|
||||
backend();
|
||||
const { result } = await mount();
|
||||
const hook = vi.fn(async () => {
|
||||
expect(streamCall()).toBeUndefined();
|
||||
});
|
||||
await act(() => result.current.sendMessage('x', 'm', undefined, { onBeforeModelRequest: hook }));
|
||||
expect(hook).toHaveBeenCalledWith([{ role: 'user', content: 'x' }]);
|
||||
});
|
||||
|
||||
it('com system prompt: vai na frente do payload e no parâmetro systemPrompt', async () => {
|
||||
backend();
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.sendMessage('x', 'm', 'seja breve'));
|
||||
expect(streamCall()).toMatchObject({
|
||||
systemPrompt: 'seja breve',
|
||||
messages: [{ role: 'system', content: 'seja breve' }, { role: 'user', content: 'x' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('histórico acima de 90% da janela de tokens: descarta as mensagens mais antigas', async () => {
|
||||
backend();
|
||||
useSettingsStore.setState({ contextWindow: 100 }); // 90 tokens ≈ 360 caracteres
|
||||
const { result } = await mount([
|
||||
{ role: 'user', content: 'a'.repeat(200) },
|
||||
{ role: 'assistant', content: 'b'.repeat(200) },
|
||||
]);
|
||||
await act(() => result.current.sendMessage('agora', 'm'));
|
||||
expect(streamCall()!.messages.map((m) => m.content)).toEqual(['b'.repeat(200), 'agora']);
|
||||
});
|
||||
|
||||
it('contextWindow 0: usa 4096 e mantém o histórico grande', async () => {
|
||||
backend();
|
||||
useSettingsStore.setState({ contextWindow: 0 });
|
||||
const { result } = await mount([{ role: 'assistant', content: 'c'.repeat(8000) }]);
|
||||
await act(() => result.current.sendMessage('x', 'm'));
|
||||
expect(streamCall()!.messages).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('mais de 9 mensagens anteriores: envia só as 9 últimas mais a atual', async () => {
|
||||
backend();
|
||||
const history: Message[] = Array.from({ length: 12 }, (_, i) => ({ role: i % 2 ? 'assistant' : 'user', content: `m${i}` }));
|
||||
const { result } = await mount(history);
|
||||
await act(() => result.current.sendMessage('atual', 'm'));
|
||||
expect(streamCall()!.messages.map((m) => m.content)).toEqual(['m3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9', 'm10', 'm11', 'atual']);
|
||||
});
|
||||
|
||||
it('payloadContentOverride: troca só o conteúdo enviado da última mensagem do usuário', async () => {
|
||||
backend();
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.sendMessage('visível', 'm', 'sys', { payloadContentOverride: 'com contexto web' }));
|
||||
expect(streamCall()!.messages).toEqual([
|
||||
{ role: 'system', content: 'sys' },
|
||||
{ role: 'user', content: 'com contexto web' },
|
||||
]);
|
||||
expect(result.current.messages[0].content).toBe('visível');
|
||||
});
|
||||
|
||||
it('assistente vazio já no fim: não adiciona outro antes do streaming', async () => {
|
||||
backend();
|
||||
const { result } = await mount([{ role: 'user', content: 'q' }, { role: 'assistant', content: '' }]);
|
||||
await act(() => result.current.sendMessage('q2', 'm'));
|
||||
expect(result.current.messages.map((m) => [m.role, m.content])).toEqual([
|
||||
['user', 'q'], ['assistant', ''], ['user', 'q2'], ['assistant', ''],
|
||||
]);
|
||||
});
|
||||
|
||||
it('Ollama parado: mostra o erro e não chama chat_stream', async () => {
|
||||
backend({ running: false });
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.sendMessage('x', 'm'));
|
||||
expect(lastContent(result.current.messages)).toContain('Ollama não está rodando');
|
||||
expect(streamCall()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('verificação do Ollama falha por outro motivo: segue e chama chat_stream', async () => {
|
||||
backend({ running: new Error('ipc indisponível') });
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.sendMessage('x', 'm'));
|
||||
expect(streamCall()).toBeDefined();
|
||||
expect(lastContent(result.current.messages)).toBe('');
|
||||
});
|
||||
|
||||
it('chat-created antes do envio: usa o session_id recebido', async () => {
|
||||
backend();
|
||||
const { result } = await mount();
|
||||
act(() => handlers['chat-created']({ payload: { session_id: 'sess-1', title: 't', emoji: 'e' } }));
|
||||
await act(() => result.current.sendMessage('x', 'm'));
|
||||
expect(streamCall()!.sessionId).toBe('sess-1');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['RequestTimeout', new Error('RequestTimeout'), '**Timeout:**'],
|
||||
['AbortError', Object.assign(new Error('cancelado'), { name: 'AbortError' }), '**Timeout:**'],
|
||||
['ConnectionError', new Error('ConnectionError'), '**Erro de Conexão:**'],
|
||||
['Failed to fetch', new Error('TypeError: Failed to fetch'), '**Erro de Conexão:**'],
|
||||
['ModelNotFound', new Error('ModelNotFound'), '**Modelo Não Encontrado:** O modelo "qwen"'],
|
||||
['ServerError', new Error('ServerError'), '**Erro do Servidor:**'],
|
||||
['NoResponseBody', new Error('NoResponseBody'), 'não retornou uma resposta válida'],
|
||||
['HTTPError com status', new Error('HTTPError: 404'), '**Erro HTTP 404:**'],
|
||||
['HTTPError sem status', new Error('HTTPError'), '**Erro HTTP desconhecido:**'],
|
||||
['erro genérico', new Error('disco cheio'), 'Detalhes: disco cheio'],
|
||||
['rejeição string do Rust', 'falha no rust', 'Detalhes: falha no rust'],
|
||||
])('chat_stream falha com %s: mensagem de erro específica', async (_n, error, expected) => {
|
||||
backend({ stream: error });
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.sendMessage('x', 'qwen'));
|
||||
expect(lastContent(result.current.messages)).toContain(expected);
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseMetadata (fim do streaming via chat-token done)', () => {
|
||||
async function streamed(tokens: string[]) {
|
||||
backend();
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.sendMessage('q', 'm'));
|
||||
act(() => {
|
||||
for (const content of tokens) handlers['chat-token']({ payload: { session_id: 's', content, done: false } });
|
||||
handlers['chat-token']({ payload: { session_id: 's', content: '', done: true } });
|
||||
});
|
||||
return result.current.messages[result.current.messages.length - 1];
|
||||
}
|
||||
|
||||
it('resposta com bloco <metadata>: separa o JSON do texto', async () => {
|
||||
const msg = await streamed(['Resposta final.', '\n<metadata>\n{"emoji":"🤖"}\n</metadata>']);
|
||||
expect(msg).toEqual({ role: 'assistant', content: 'Resposta final.', metadata: { emoji: '🤖' } });
|
||||
});
|
||||
|
||||
it('resposta sem metadata: texto intacto e metadata indefinida', async () => {
|
||||
const msg = await streamed(['Olá ', 'mundo']);
|
||||
expect(msg).toEqual({ role: 'assistant', content: 'Olá mundo', metadata: undefined });
|
||||
});
|
||||
|
||||
it('JSON inválido no bloco: remove o bloco e não define metadata', async () => {
|
||||
const msg = await streamed(['Texto <metadata>{quebrado</metadata>']);
|
||||
expect(msg).toEqual({ role: 'assistant', content: 'Texto', metadata: undefined });
|
||||
});
|
||||
|
||||
it('dois blocos válidos: usa o primeiro e remove ambos', async () => {
|
||||
const msg = await streamed(['A <METADATA>{"n":1}</METADATA> B <metadata>{"n":2}</metadata>']);
|
||||
expect(msg.metadata).toEqual({ n: 1 });
|
||||
expect(msg.content).toBe('A B');
|
||||
});
|
||||
|
||||
it('prefixo "---" sobrando no fim: é removido', async () => {
|
||||
const msg = await streamed(['Fim da resposta\n---\n<metadata>{"a":1}</metadata>']);
|
||||
expect(msg.content).toBe('Fim da resposta');
|
||||
});
|
||||
|
||||
it('nenhum token antes do done: mantém o conteúdo atual da mensagem', async () => {
|
||||
const msg = await streamed([]);
|
||||
expect(msg).toEqual({ role: 'assistant', content: '', metadata: undefined });
|
||||
});
|
||||
});
|
||||
|
||||
describe('detectToolCalls', () => {
|
||||
const tools = [{ server_name: 'srv', tool: { name: 'search' } }];
|
||||
|
||||
it('"use <tool> with <json>": argumentos em JSON', () => {
|
||||
expect(detectToolCalls('use search with {"q": "rust"}', tools)).toEqual([
|
||||
{ server_name: 'srv', tool_name: 'search', arguments: { q: 'rust' } },
|
||||
]);
|
||||
});
|
||||
|
||||
it('texto sem padrão de chamada: nenhuma', () => {
|
||||
expect(detectToolCalls('apenas uma resposta', tools)).toEqual([]);
|
||||
});
|
||||
|
||||
it('ferramenta não disponível: ignora', () => {
|
||||
expect(detectToolCalls('use fetch with {"u": 1}', tools)).toEqual([]);
|
||||
});
|
||||
|
||||
it('argumentos chave=valor: remove aspas e ignora pares sem valor', () => {
|
||||
expect(detectToolCalls(`call search with q=rust, lang='pt', solto`, tools)[0].arguments).toEqual({ q: 'rust', lang: 'pt' });
|
||||
});
|
||||
|
||||
it('forma tool(args) com nome em maiúsculas: casa sem diferenciar caixa', () => {
|
||||
expect(detectToolCalls('SEARCH(q=1)', tools)).toEqual([{ server_name: 'srv', tool_name: 'search', arguments: { q: '1' } }]);
|
||||
});
|
||||
|
||||
it('tool( ) com argumentos em branco: objeto vazio', () => {
|
||||
expect(detectToolCalls('search( )', tools)[0].arguments).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { useDeepResearch } from './use-deep-research';
|
||||
|
||||
// Logger (invoke) e análise contextual viram fakes; o Ollama responde por fetch fake.
|
||||
vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(async () => undefined) }));
|
||||
vi.mock('@/lib/contextual-analyzer', () => ({
|
||||
analyzeQueryContext: vi.fn(async () => {
|
||||
throw new Error('sem análise contextual neste teste');
|
||||
}),
|
||||
}));
|
||||
|
||||
function llmReplies(response: string) {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ response }) })));
|
||||
}
|
||||
|
||||
const QUERY = 'historia da linguagem rust';
|
||||
|
||||
async function decompose(response: string) {
|
||||
llmReplies(response);
|
||||
const { result } = renderHook(() => useDeepResearch());
|
||||
let plan: string[] = [];
|
||||
await act(async () => {
|
||||
plan = await result.current.decompose(QUERY, 'llama3');
|
||||
});
|
||||
return { plan, error: result.current.state.logs[0]?.error };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
for (const level of ['log', 'warn', 'error', 'info'] as const) vi.spyOn(console, level).mockImplementation(() => {});
|
||||
});
|
||||
|
||||
describe('extractQueriesFromResponse (via decompose)', () => {
|
||||
it('array JSON puro: mantém só strings não vazias', async () => {
|
||||
const r = await decompose('["rust origem", "", 3, "rust mozilla"]');
|
||||
expect(r).toEqual({ plan: ['rust origem', 'rust mozilla'], error: undefined });
|
||||
});
|
||||
|
||||
it('bloco ```json: remove a cerca antes de interpretar', async () => {
|
||||
expect((await decompose('```json\n["rust 1.0"]\n```')).plan).toEqual(['rust 1.0']);
|
||||
});
|
||||
|
||||
it('JSON no meio de texto: extrai o trecho', async () => {
|
||||
expect((await decompose('Aqui está o plano: ["rust graydon"] espero ajudar')).plan).toEqual(['rust graydon']);
|
||||
});
|
||||
|
||||
it('trecho parecido com JSON mas inválido: cai na pergunta original com erro registrado', async () => {
|
||||
const r = await decompose('plano: [rust sem aspas]');
|
||||
expect(r).toEqual({ plan: [QUERY], error: 'JSON Parse Failed: Could not extract JSON from response' });
|
||||
});
|
||||
|
||||
it('resposta sem JSON: cai na pergunta original com erro registrado', async () => {
|
||||
const r = await decompose('não sei');
|
||||
expect(r).toEqual({ plan: [QUERY], error: 'JSON Parse Failed: No JSON found in response' });
|
||||
});
|
||||
|
||||
it('objeto com chave conhecida: usa o array dessa chave', async () => {
|
||||
expect((await decompose('{"search_queries": ["rust história", " "]}')).plan).toEqual(['rust história']);
|
||||
});
|
||||
|
||||
it('chave conhecida que não é array: segue para a próxima chave', async () => {
|
||||
expect((await decompose('{"query": "rust", "plan": ["rust plano"]}')).plan).toEqual(['rust plano']);
|
||||
});
|
||||
|
||||
it('objeto sem chave conhecida: usa o primeiro array de strings', async () => {
|
||||
expect((await decompose('{"nums": [1], "vazio": [], "itens": ["rust itens"]}')).plan).toEqual(['rust itens']);
|
||||
});
|
||||
|
||||
it('objeto sem nenhum array de strings: cai na pergunta original', async () => {
|
||||
const r = await decompose('{"nums": [1, 2], "texto": "rust"}');
|
||||
expect(r).toEqual({ plan: [QUERY], error: 'JSON Parse Failed: No array of queries found in response' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { useMcpTools, type McpToolInfo } from './use-mcp-tools';
|
||||
|
||||
// Servidores MCP reais não são iniciados: o comando Tauri devolve lista vazia.
|
||||
const invokeMock = vi.hoisted(() => vi.fn(async () => []));
|
||||
vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));
|
||||
|
||||
const tool = (server_name: string, name: string, input_schema?: unknown): McpToolInfo => ({
|
||||
server_name,
|
||||
tool: { name, description: `desc ${name}`, input_schema },
|
||||
});
|
||||
|
||||
function generate(tools: McpToolInfo[], selected?: string[]) {
|
||||
const { result } = renderHook(() => useMcpTools());
|
||||
return result.current.generateToolsContext(tools, selected);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
describe('generateToolsContext', () => {
|
||||
it('sem ferramentas: string vazia', () => {
|
||||
expect(generate([])).toBe('');
|
||||
});
|
||||
|
||||
it('servidores selecionados sem ferramentas correspondentes: string vazia', () => {
|
||||
expect(generate([tool('fs', 'read')], ['web'])).toBe('');
|
||||
});
|
||||
|
||||
it('sem seleção: cabeçalho genérico e todas as ferramentas', () => {
|
||||
const ctx = generate([tool('fs', 'read'), tool('web', 'search')]);
|
||||
expect(ctx).toContain('Você tem acesso aos servidores MCP listados abaixo.');
|
||||
expect(ctx).toContain('### Servidor: fs');
|
||||
expect(ctx).toContain('### Servidor: web');
|
||||
});
|
||||
|
||||
it('seleção vazia: comporta-se como sem seleção', () => {
|
||||
const ctx = generate([tool('fs', 'read')], []);
|
||||
expect(ctx).toContain('Você tem acesso aos servidores MCP listados abaixo.');
|
||||
expect(ctx).toContain('- **read**: desc read');
|
||||
});
|
||||
|
||||
it('com seleção: cita os servidores e omite os demais', () => {
|
||||
const ctx = generate([tool('fs', 'read'), tool('web', 'search'), tool('db', 'query')], ['web', 'db']);
|
||||
expect(ctx).toContain('servidores MCP selecionados: web, db.');
|
||||
expect(ctx).not.toContain('### Servidor: fs');
|
||||
expect(ctx).toContain('- **search**');
|
||||
expect(ctx).toContain('- **query**');
|
||||
});
|
||||
|
||||
it('duas ferramentas do mesmo servidor: um único cabeçalho de servidor', () => {
|
||||
const ctx = generate([tool('fs', 'read'), tool('fs', 'write')]);
|
||||
expect(ctx.match(/### Servidor: fs/g)).toHaveLength(1);
|
||||
expect(ctx.indexOf('- **read**')).toBeLessThan(ctx.indexOf('- **write**'));
|
||||
});
|
||||
|
||||
it('schema com propriedades: lista parâmetros e usa "any" quando falta o tipo', () => {
|
||||
const ctx = generate([tool('fs', 'read', { properties: { path: { type: 'string' }, flags: {} } })]);
|
||||
expect(ctx).toContain(' - Parâmetros: path (string), flags (any)\n');
|
||||
});
|
||||
|
||||
it('schema sem properties: não lista parâmetros', () => {
|
||||
const ctx = generate([tool('fs', 'read', { type: 'object' })]);
|
||||
expect(ctx).not.toContain('Parâmetros');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { useOperatingSystem } from './use-operating-system';
|
||||
|
||||
vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn() }));
|
||||
|
||||
const invokeMock = vi.mocked(invoke);
|
||||
|
||||
function setUserAgent(ua: string) {
|
||||
vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue(ua);
|
||||
}
|
||||
|
||||
async function detect() {
|
||||
const { result } = renderHook(() => useOperatingSystem());
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
return result.current.os;
|
||||
}
|
||||
|
||||
const UA = {
|
||||
windows: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
|
||||
mac: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0)',
|
||||
linux: 'Mozilla/5.0 (X11; Linux x86_64)',
|
||||
other: 'Mozilla/5.0 (X11; FreeBSD amd64)',
|
||||
};
|
||||
|
||||
describe('useOperatingSystem / detectOS', () => {
|
||||
beforeEach(() => {
|
||||
invokeMock.mockReset();
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
it.each(['linux', 'windows', 'mac'])('backend responde "%s": usa a resposta do backend', async (os) => {
|
||||
invokeMock.mockResolvedValue(os);
|
||||
setUserAgent(UA.other);
|
||||
expect(await detect()).toBe(os);
|
||||
expect(invokeMock).toHaveBeenCalledWith('get_operating_system');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['windows', UA.windows],
|
||||
['mac', UA.mac],
|
||||
['linux', UA.linux],
|
||||
['windows', UA.other],
|
||||
])('backend responde valor desconhecido: user agent decide (%s)', async (expected, ua) => {
|
||||
invokeMock.mockResolvedValue('freebsd');
|
||||
setUserAgent(ua);
|
||||
expect(await detect()).toBe(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['windows', UA.windows],
|
||||
['mac', UA.mac],
|
||||
['linux', UA.linux],
|
||||
['windows', UA.other],
|
||||
])('invoke falha (sem Tauri): user agent decide (%s)', async (expected, ua) => {
|
||||
invokeMock.mockRejectedValue(new Error('no tauri'));
|
||||
setUserAgent(ua);
|
||||
expect(await detect()).toBe(expected);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { useQueryGenerator } from './use-query-generator';
|
||||
|
||||
// O Ollama (fetch para localhost:11434) vira fake: nenhum modelo é chamado.
|
||||
function ollama(reply: { ok?: boolean; response?: unknown } | Error) {
|
||||
const fetchMock = vi.fn(async () => {
|
||||
if (reply instanceof Error) throw reply;
|
||||
return { ok: reply.ok ?? true, json: async () => (reply.response === undefined ? {} : { response: reply.response }) };
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
return fetchMock;
|
||||
}
|
||||
|
||||
async function generate(input: string) {
|
||||
const { result } = renderHook(() => useQueryGenerator());
|
||||
let query = '';
|
||||
await act(async () => {
|
||||
query = await result.current.generateQuery(input, 'llama3');
|
||||
});
|
||||
expect(result.current.isGenerating).toBe(false);
|
||||
return query;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
describe('generateQuery', () => {
|
||||
it('entrada em branco: NO_SEARCH sem chamar o modelo', async () => {
|
||||
const fetchMock = ollama({ response: 'x' });
|
||||
expect(await generate(' ')).toBe('NO_SEARCH');
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('modelo gera query: remove aspas e ponto final', async () => {
|
||||
ollama({ response: ' "preço do dólar hoje." ' });
|
||||
expect(await generate('quanto está o dólar?')).toBe('preço do dólar hoje');
|
||||
});
|
||||
|
||||
it('modelo responde no_search (qualquer caixa): NO_SEARCH', async () => {
|
||||
ollama({ response: 'no_search' });
|
||||
expect(await generate('olá, tudo bem?')).toBe('NO_SEARCH');
|
||||
});
|
||||
|
||||
it('query com menos de 3 caracteres: NO_SEARCH', async () => {
|
||||
ollama({ response: 'ab' });
|
||||
expect(await generate('algo')).toBe('NO_SEARCH');
|
||||
});
|
||||
|
||||
it('resposta sem campo response: NO_SEARCH', async () => {
|
||||
ollama({});
|
||||
expect(await generate('algo')).toBe('NO_SEARCH');
|
||||
});
|
||||
|
||||
it.each(['o que', 'quem', 'quando', 'onde', 'como', 'por que', 'qual', 'quais'])(
|
||||
'HTTP de erro e pergunta factual com "%s": usa a própria pergunta',
|
||||
async (word) => {
|
||||
ollama({ ok: false });
|
||||
const input = `${word.toUpperCase()} xyz`;
|
||||
expect(await generate(input)).toBe(input);
|
||||
},
|
||||
);
|
||||
|
||||
it('HTTP de erro e frase não factual: NO_SEARCH', async () => {
|
||||
ollama({ ok: false });
|
||||
expect(await generate('me conte uma piada')).toBe('NO_SEARCH');
|
||||
});
|
||||
|
||||
it('fetch rejeita e pergunta factual: usa a própria pergunta', async () => {
|
||||
ollama(new TypeError('Failed to fetch'));
|
||||
expect(await generate('quem ganhou a copa?')).toBe('quem ganhou a copa?');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { useQueryPreprocessor, type PreprocessOptions, type PreprocessedQuery } from './use-query-preprocessor';
|
||||
import { useSettingsStore } from '@/store/settings-store';
|
||||
|
||||
// classify_intent é um comando Tauri (Rust): vira fake.
|
||||
const invokeMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));
|
||||
|
||||
function intent(value: string | Error) {
|
||||
invokeMock.mockImplementation(async (cmd: string) => {
|
||||
if (cmd !== 'classify_intent') throw new Error(`comando inesperado: ${cmd}`);
|
||||
if (value instanceof Error) throw value;
|
||||
return value;
|
||||
});
|
||||
}
|
||||
|
||||
async function preprocess(text: string, options?: PreprocessOptions) {
|
||||
const { result } = renderHook(() => useQueryPreprocessor());
|
||||
let out: PreprocessedQuery | undefined;
|
||||
await act(async () => {
|
||||
out = await result.current.preprocess(text, options);
|
||||
});
|
||||
expect(result.current.isProcessing).toBe(false);
|
||||
return out!;
|
||||
}
|
||||
|
||||
const defaults = useSettingsStore.getState();
|
||||
|
||||
beforeEach(() => {
|
||||
invokeMock.mockReset();
|
||||
localStorage.clear();
|
||||
useSettingsStore.setState({
|
||||
queryPreprocessing: defaults.queryPreprocessing,
|
||||
webSearch: { ...defaults.webSearch, enabled: true },
|
||||
});
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
describe('preprocess', () => {
|
||||
it('pergunta factual válida: divide, classifica e decide buscar', async () => {
|
||||
intent('factual');
|
||||
const r = await preprocess('O que é Rust? Quem criou a linguagem?');
|
||||
expect(r.validation.isValid).toBe(true);
|
||||
expect(r.splitResult.splitCount).toBe(2);
|
||||
expect(r.questions).toHaveLength(2);
|
||||
expect(r.intent).toBe('factual');
|
||||
expect(r.shouldSearch).toBe(true);
|
||||
expect(invokeMock).toHaveBeenCalledWith('classify_intent', { query: r.normalized });
|
||||
});
|
||||
|
||||
it('texto abaixo do mínimo: inválido, sem perguntas, sem busca e sem classificar', async () => {
|
||||
intent('factual');
|
||||
const r = await preprocess('ab');
|
||||
expect(r.validation.isValid).toBe(false);
|
||||
expect(r).toMatchObject({ questions: [], intent: 'unknown', shouldSearch: false, splitResult: { splitCount: 0 } });
|
||||
expect(invokeMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skipValidation: aceita texto abaixo do mínimo', async () => {
|
||||
intent('factual');
|
||||
const r = await preprocess('ab', { skipValidation: true });
|
||||
expect(r.validation).toEqual({ isValid: true, errors: [], warnings: [], normalizedLength: 2 });
|
||||
expect(r.shouldSearch).toBe(true);
|
||||
});
|
||||
|
||||
it('settings sem queryPreprocessing: usa mínimo 3 padrão', async () => {
|
||||
useSettingsStore.setState({ queryPreprocessing: undefined as unknown as typeof defaults.queryPreprocessing });
|
||||
intent('factual');
|
||||
expect((await preprocess('ab')).validation.isValid).toBe(false);
|
||||
expect((await preprocess('abc')).validation.isValid).toBe(true);
|
||||
});
|
||||
|
||||
it('padrões irrelevantes configurados: usa os do usuário', async () => {
|
||||
useSettingsStore.setState({ queryPreprocessing: { ...defaults.queryPreprocessing, irrelevantPatterns: ['rust'] } });
|
||||
intent('factual');
|
||||
expect((await preprocess('rust')).validation.warnings).toHaveLength(1);
|
||||
expect((await preprocess('teste')).validation.warnings).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('lista de padrões vazia: cai nos padrões padrão da validação', async () => {
|
||||
useSettingsStore.setState({ queryPreprocessing: { ...defaults.queryPreprocessing, irrelevantPatterns: [] } });
|
||||
intent('factual');
|
||||
expect((await preprocess('teste')).validation.warnings).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('skipSplit: mantém o texto original como única pergunta', async () => {
|
||||
intent('factual');
|
||||
const text = 'O que é Rust? Quem criou a linguagem?';
|
||||
const r = await preprocess(text, { skipSplit: true });
|
||||
expect(r.questions).toEqual([text]);
|
||||
expect(r.splitResult.splitCount).toBe(1);
|
||||
});
|
||||
|
||||
it('skipIntentClassification: intent unknown sem chamar o backend e ainda busca', async () => {
|
||||
intent('conversational');
|
||||
const r = await preprocess('preço do dólar', { skipIntentClassification: true });
|
||||
expect(r.intent).toBe('unknown');
|
||||
expect(r.shouldSearch).toBe(true);
|
||||
expect(invokeMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('classificador falha: intent unknown e segue buscando', async () => {
|
||||
intent(new Error('modelo de intent ausente'));
|
||||
const r = await preprocess('preço do dólar');
|
||||
expect(r.intent).toBe('unknown');
|
||||
expect(r.shouldSearch).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['technical', true],
|
||||
['conversational', false],
|
||||
['opinion', false],
|
||||
['calculation', false],
|
||||
])('intent %s: shouldSearch %s', async (value, expected) => {
|
||||
intent(value);
|
||||
expect((await preprocess('pergunta qualquer aqui')).shouldSearch).toBe(expected);
|
||||
});
|
||||
|
||||
it('busca web desligada: não busca mesmo com intent factual', async () => {
|
||||
useSettingsStore.setState({ webSearch: { ...defaults.webSearch, enabled: false } });
|
||||
intent('factual');
|
||||
expect((await preprocess('preço do dólar')).shouldSearch).toBe(false);
|
||||
});
|
||||
|
||||
it('settings corrompido sem irrelevantPatterns: devolve resultado de erro sem lançar', async () => {
|
||||
const { irrelevantPatterns: _omit, ...rest } = defaults.queryPreprocessing;
|
||||
useSettingsStore.setState({ queryPreprocessing: rest as typeof defaults.queryPreprocessing });
|
||||
intent('factual');
|
||||
const r = await preprocess('preço do dólar');
|
||||
expect(r.validation).toEqual({ isValid: false, errors: ['Erro ao pré-processar query'], warnings: [], normalizedLength: 0 });
|
||||
expect(r.shouldSearch).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user