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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { chunkBySections, summarizeMarkdown } from './content-condenser';
|
||||||
|
|
||||||
|
const words = (n: number, w = 'palavra') => Array.from({ length: n }, () => w).join(' ');
|
||||||
|
|
||||||
|
describe('summarizeMarkdown', () => {
|
||||||
|
it('com headings e sem espaço para tudo: inclui a 1ª seção e trunca a 2ª com "..."', () => {
|
||||||
|
const md = `# Um\n${words(30, 'alfa')}\n# Dois\n${words(100, 'beta')}`;
|
||||||
|
const out = summarizeMarkdown(md, 400);
|
||||||
|
expect(out.startsWith(`## Um\n\n${words(30, 'alfa')}\n\n## Dois\n\nbeta`)).toBe(true);
|
||||||
|
expect(out.endsWith('...')).toBe(true);
|
||||||
|
expect(out.length).toBeLessThan(md.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('conteúdo vazio: devolve o próprio conteúdo', () => {
|
||||||
|
expect(summarizeMarkdown('', 10)).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('conteúdo dentro do limite: devolve sem alterar', () => {
|
||||||
|
const md = '# T\ncurto';
|
||||||
|
expect(summarizeMarkdown(md, 100)).toBe(md);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('heading único: a seção vai até o fim do texto', () => {
|
||||||
|
const md = `# Só\n${'x'.repeat(10)}\n${'y'.repeat(150)}\nfim${' '.repeat(300)}`;
|
||||||
|
expect(summarizeMarkdown(md, 300)).toBe(`## Só\n\n${'x'.repeat(10)}\n${'y'.repeat(150)}\nfim`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('seções de nível 1 vêm antes das de nível 2, mesmo aparecendo depois', () => {
|
||||||
|
const md = `## Sub\nb\n# Top\na\n${' '.repeat(200)}`;
|
||||||
|
expect(summarizeMarkdown(md, 100)).toBe('## Top\n\na\n\n## Sub\n\nb');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('todas as seções cabem depois do trim: sem "..."', () => {
|
||||||
|
const md = `# A\nconteudo a${' '.repeat(300)}\n# B\nconteudo b`;
|
||||||
|
expect(summarizeMarkdown(md, 200)).toBe('## A\n\nconteudo a\n\n## B\n\nconteudo b');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('seção não cabe e sobram até 100 caracteres: para sem cortar a seção', () => {
|
||||||
|
const md = `# A\n${'a'.repeat(50)}\n# B\n${'b'.repeat(300)}`;
|
||||||
|
expect(summarizeMarkdown(md, 200)).toBe(`## A\n\n${'a'.repeat(50)}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('1ª seção já não cabe e o limite é pequeno: cai no recorte bruto do conteúdo', () => {
|
||||||
|
const md = `# A\n${'a'.repeat(300)}`;
|
||||||
|
expect(summarizeMarkdown(md, 120)).toBe(md.substring(0, 120));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sem headings: junta parágrafos e corta o que não cabe com "..."', () => {
|
||||||
|
const md = `${words(10, 'p1')}\n\n${words(100, 'p2')}`;
|
||||||
|
const out = summarizeMarkdown(md, 300);
|
||||||
|
expect(out.startsWith(`${words(10, 'p1')}\n\np2`)).toBe(true);
|
||||||
|
expect(out.endsWith('...')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sem headings e todos os parágrafos cabem: devolve os parágrafos sem "..."', () => {
|
||||||
|
const md = `um\n\n${' '.repeat(10)}\n\n\n\n${' \n'.repeat(80)}dois`;
|
||||||
|
expect(summarizeMarkdown(md, 50)).toBe('um\n\ndois');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sem headings e sobram até 100 caracteres: para sem cortar o parágrafo', () => {
|
||||||
|
const md = `${'a'.repeat(100)}\n\n${'b'.repeat(300)}`;
|
||||||
|
expect(summarizeMarkdown(md, 200)).toBe('a'.repeat(100));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sem headings, 1º parágrafo maior que o limite pequeno: recorte bruto', () => {
|
||||||
|
const md = 'c'.repeat(300);
|
||||||
|
expect(summarizeMarkdown(md, 90)).toBe('c'.repeat(90));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('chunkBySections', () => {
|
||||||
|
it('um chunk por heading, com índices de linha', () => {
|
||||||
|
const chunks = chunkBySections('# A\nlinha a\n# B\nlinha b');
|
||||||
|
expect(chunks.map((c) => [c.content, c.startIndex, c.endIndex])).toEqual([
|
||||||
|
['# A\nlinha a', 0, 1],
|
||||||
|
['# B\nlinha b', 2, 3],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('texto vazio: nenhum chunk', () => {
|
||||||
|
expect(chunkBySections('')).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('texto antes do 1º heading vira um chunk próprio', () => {
|
||||||
|
const chunks = chunkBySections('intro\n# A\na');
|
||||||
|
expect(chunks.map((c) => c.content)).toEqual(['intro', '# A\na']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('só linhas em branco antes do 1º heading: não gera chunk vazio', () => {
|
||||||
|
const chunks = chunkBySections('\n\n# A\na');
|
||||||
|
expect(chunks.map((c) => c.content)).toEqual(['# A\na']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('seção maior que o limite: divide e repete o heading no chunk seguinte', () => {
|
||||||
|
const chunks = chunkBySections(`# A\n${'x'.repeat(20)}\n${'y'.repeat(20)}`, 30);
|
||||||
|
expect(chunks.map((c) => c.content)).toEqual([`# A\n${'x'.repeat(20)}`, `# A\n${'y'.repeat(20)}`]);
|
||||||
|
expect(chunks[1].startIndex).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sem heading e 1ª linha já estoura o limite: não emite chunk vazio antes dela', () => {
|
||||||
|
const chunks = chunkBySections('z'.repeat(50), 10);
|
||||||
|
expect(chunks.map((c) => c.content)).toEqual(['z'.repeat(50)]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('só espaços em branco: passa pelo fallback de parágrafos e não gera chunk', () => {
|
||||||
|
expect(chunkBySections(' \n ')).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { analyzeQueryContext } from './contextual-analyzer';
|
||||||
|
|
||||||
|
// Logs do chatLog vão para o Tauri; aqui viram no-op.
|
||||||
|
vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(async () => undefined) }));
|
||||||
|
|
||||||
|
// Fake do /api/generate do Ollama (stream: false).
|
||||||
|
function stubGenerate(response: unknown, ok = true) {
|
||||||
|
const fetchMock = vi.fn(async () => ({ ok, status: ok ? 200 : 500, statusText: 'x', json: async () => ({ response }) }) as Response);
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
return fetchMock;
|
||||||
|
}
|
||||||
|
|
||||||
|
const FULL = {
|
||||||
|
intent: 'comparison',
|
||||||
|
entities: [{ type: 'product', value: 'Rust', confidence: 0.9 }],
|
||||||
|
topics: ['linguagens'],
|
||||||
|
relationships: [{ from: 'Rust', to: 'Go', relation: 'vs', confidence: 0.8 }],
|
||||||
|
implicitQuestions: ['qual é mais rápida?'],
|
||||||
|
temporalContext: { period: '2024' },
|
||||||
|
geographicContext: { location: 'Brasil' },
|
||||||
|
keywords: ['rust', 'go'],
|
||||||
|
synonyms: ['linguagem'],
|
||||||
|
domain: 'tecnologia',
|
||||||
|
complexity: 'complex',
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('analyzeQueryContext', () => {
|
||||||
|
beforeEach(() => vi.spyOn(console, 'error').mockImplementation(() => {}));
|
||||||
|
|
||||||
|
it('LLM devolve JSON completo: usa todos os campos', async () => {
|
||||||
|
const fetchMock = stubGenerate(JSON.stringify(FULL));
|
||||||
|
const ctx = await analyzeQueryContext('rust vs go', 'qwen');
|
||||||
|
expect(ctx).toEqual({ originalQuery: 'rust vs go', ...FULL });
|
||||||
|
const body = JSON.parse((fetchMock.mock.calls[0] as unknown as [string, RequestInit])[1].body as string);
|
||||||
|
expect(body).toMatchObject({ model: 'qwen', stream: false });
|
||||||
|
expect(body.prompt).toContain('"rust vs go"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('query vazia: contexto vazio sem chamar o modelo', async () => {
|
||||||
|
const fetchMock = stubGenerate('{}');
|
||||||
|
const ctx = await analyzeQueryContext('', 'm');
|
||||||
|
expect(ctx.intent).toBe('unknown');
|
||||||
|
expect(ctx.complexity).toBe('simple');
|
||||||
|
expect(fetchMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('query só com espaços: contexto vazio sem chamar o modelo', async () => {
|
||||||
|
const fetchMock = stubGenerate('{}');
|
||||||
|
expect((await analyzeQueryContext(' ', 'm')).keywords).toEqual([]);
|
||||||
|
expect(fetchMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('HTTP não ok: cai no fallback heurístico', async () => {
|
||||||
|
stubGenerate(JSON.stringify(FULL), false);
|
||||||
|
const ctx = await analyzeQueryContext('como instalar rust', 'm');
|
||||||
|
expect(ctx.intent).toBe('how-to');
|
||||||
|
expect(ctx.entities).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resposta sem campo response: JSON vazio falha e cai no fallback', async () => {
|
||||||
|
stubGenerate(undefined);
|
||||||
|
expect((await analyzeQueryContext('lista de livros', 'm')).intent).toBe('list');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('JSON dentro de bloco ```json com texto em volta: extrai o objeto', async () => {
|
||||||
|
stubGenerate('Claro!\n```json\n{"intent":"definition"}\n```');
|
||||||
|
expect((await analyzeQueryContext('x', 'm')).intent).toBe('definition');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('JSON sem objeto (array): aceita e preenche os padrões', async () => {
|
||||||
|
stubGenerate('[]');
|
||||||
|
expect(await analyzeQueryContext('x', 'm')).toEqual({
|
||||||
|
originalQuery: 'x',
|
||||||
|
intent: 'unknown',
|
||||||
|
entities: [],
|
||||||
|
topics: [],
|
||||||
|
relationships: [],
|
||||||
|
implicitQuestions: [],
|
||||||
|
temporalContext: undefined,
|
||||||
|
geographicContext: undefined,
|
||||||
|
keywords: [],
|
||||||
|
synonyms: [],
|
||||||
|
domain: undefined,
|
||||||
|
complexity: 'moderate',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['intent', 'unknown'],
|
||||||
|
['entities', []],
|
||||||
|
['topics', []],
|
||||||
|
['relationships', []],
|
||||||
|
['implicitQuestions', []],
|
||||||
|
['keywords', []],
|
||||||
|
['synonyms', []],
|
||||||
|
['complexity', 'moderate'],
|
||||||
|
])('campo %s ausente: usa o padrão e mantém os demais', async (field, fallback) => {
|
||||||
|
const partial: Record<string, unknown> = { ...FULL };
|
||||||
|
delete partial[field];
|
||||||
|
stubGenerate(JSON.stringify(partial));
|
||||||
|
const ctx = await analyzeQueryContext('q', 'm');
|
||||||
|
expect(ctx).toEqual({ originalQuery: 'q', ...FULL, [field]: fallback });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('JSON inválido: cai no fallback heurístico', async () => {
|
||||||
|
stubGenerate('{intent: oops');
|
||||||
|
expect((await analyzeQueryContext('por que o céu é azul', 'm')).intent).toBe('causal');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('createFallbackContext (via Ollama fora do ar)', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
vi.stubGlobal('fetch', vi.fn(async () => { throw new TypeError('connection refused'); }));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('query factual sem marcadores: intent factual, sem contexto temporal', async () => {
|
||||||
|
const ctx = await analyzeQueryContext('preço do petróleo hoje', 'm');
|
||||||
|
expect(ctx).toMatchObject({ intent: 'factual', keywords: ['preço', 'petróleo', 'hoje'], topics: ['preço', 'petróleo', 'hoje'], complexity: 'moderate' });
|
||||||
|
expect(ctx.temporalContext).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['como', 'como fazer pão', 'how-to'],
|
||||||
|
['tutorial', 'tutorial de git', 'how-to'],
|
||||||
|
['o que é', 'o que é kubernetes', 'definition'],
|
||||||
|
['definição', 'definição de entropia', 'definition'],
|
||||||
|
['quais', 'quais linguagens usar', 'list'],
|
||||||
|
['lista', 'lista de capitais', 'list'],
|
||||||
|
['comparar', 'comparar planos', 'comparison'],
|
||||||
|
['vs', 'react vs vue', 'comparison'],
|
||||||
|
['por que', 'por que chove', 'causal'],
|
||||||
|
['causa', 'causa da inflação', 'causal'],
|
||||||
|
])('marcador "%s": intent correspondente', async (_m, query, intent) => {
|
||||||
|
expect((await analyzeQueryContext(query, 'm')).intent).toBe(intent);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['último', 'último lançamento da apple'],
|
||||||
|
['recente', 'notícia recente'],
|
||||||
|
['atual', 'cotação atual do dólar'],
|
||||||
|
])('termo relativo "%s": temporal recente', async (_t, query) => {
|
||||||
|
expect((await analyzeQueryContext(query, 'm')).temporalContext).toEqual({ relative: 'recente' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([['2024'], ['2023']])('ano %s isolado: vira período', async (year) => {
|
||||||
|
expect((await analyzeQueryContext(`copa ${year}`, 'm')).temporalContext).toEqual({ period: year });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ano grudado em outra palavra: sem período', async () => {
|
||||||
|
expect((await analyzeQueryContext('versao2024 notas', 'm')).temporalContext).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('mais de 5 keywords: complex', async () => {
|
||||||
|
expect((await analyzeQueryContext('alfa beta gama delta epsilon zeta', 'm')).complexity).toBe('complex');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('até 2 keywords: simple, stopwords e palavras curtas fora', async () => {
|
||||||
|
const ctx = await analyzeQueryContext('o mar de lua', 'm');
|
||||||
|
expect(ctx.keywords).toEqual(['mar', 'lua']);
|
||||||
|
expect(ctx.complexity).toBe('simple');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { detectModelContextWindow } from './model-context';
|
||||||
|
import { useSettingsStore } from '@/store/settings-store';
|
||||||
|
|
||||||
|
// Fake do /api/show do Ollama: nenhuma chamada sai do processo.
|
||||||
|
function stubShow(body: unknown, ok = true) {
|
||||||
|
const fetchMock = vi.fn(async () => ({ ok, json: async () => body }) as Response);
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
return fetchMock;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('detectModelContextWindow', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
useSettingsStore.setState({ contextWindow: 2048 });
|
||||||
|
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('modelfile com context_length: usa o valor declarado', async () => {
|
||||||
|
const fetchMock = stubShow({ modelfile: 'PARAMETER context_length: 32000' });
|
||||||
|
expect(await detectModelContextWindow('llama3')).toBe(32000);
|
||||||
|
expect(fetchMock).toHaveBeenCalledWith('http://localhost:11434/api/show', expect.objectContaining({ method: 'POST' }));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('nome vazio: usa contextWindow das settings sem chamar a API', async () => {
|
||||||
|
const fetchMock = stubShow({});
|
||||||
|
expect(await detectModelContextWindow('')).toBe(2048);
|
||||||
|
expect(fetchMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('nome vazio e contextWindow 0: cai em 4096', async () => {
|
||||||
|
useSettingsStore.setState({ contextWindow: 0 });
|
||||||
|
stubShow({});
|
||||||
|
expect(await detectModelContextWindow('')).toBe(4096);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resposta HTTP não ok: usa as settings', async () => {
|
||||||
|
stubShow({ modelfile: 'context_length 9999' }, false);
|
||||||
|
expect(await detectModelContextWindow('m')).toBe(2048);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['7b', 8192],
|
||||||
|
['8b', 8192],
|
||||||
|
['13b', 16384],
|
||||||
|
['14b', 16384],
|
||||||
|
['32k', 32768],
|
||||||
|
['128k', 32768],
|
||||||
|
])('sem context_length e size "%s": infere %i', async (size, expected) => {
|
||||||
|
stubShow({ modelfile: 'FROM x', size });
|
||||||
|
expect(await detectModelContextWindow('m')).toBe(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sem modelfile nem size: usa as settings', async () => {
|
||||||
|
stubShow({});
|
||||||
|
expect(await detectModelContextWindow('m')).toBe(2048);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetch rejeita (Ollama fora do ar): usa as settings', async () => {
|
||||||
|
vi.stubGlobal('fetch', vi.fn(async () => { throw new TypeError('connection refused'); }));
|
||||||
|
expect(await detectModelContextWindow('m')).toBe(2048);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fallback final com contextWindow 0: cai em 4096', async () => {
|
||||||
|
useSettingsStore.setState({ contextWindow: 0 });
|
||||||
|
stubShow({ size: '3b' });
|
||||||
|
expect(await detectModelContextWindow('m')).toBe(4096);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
|
||||||
|
import { enrichQueries } from './query-enricher';
|
||||||
|
import type { QueryContext } from './contextual-analyzer';
|
||||||
|
|
||||||
|
vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(async () => undefined) }));
|
||||||
|
|
||||||
|
function stubGenerate(response: unknown, ok = true) {
|
||||||
|
const fetchMock = vi.fn(async () => ({ ok, status: ok ? 200 : 503, statusText: 'x', json: async () => ({ response }) }) as Response);
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
return fetchMock;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sentPrompt(fetchMock: Mock): string {
|
||||||
|
return JSON.parse((fetchMock.mock.calls[0] as unknown as [string, RequestInit])[1].body as string).prompt;
|
||||||
|
}
|
||||||
|
|
||||||
|
const CTX: QueryContext = {
|
||||||
|
originalQuery: 'praias em Garuva',
|
||||||
|
intent: 'list',
|
||||||
|
entities: [{ type: 'location', value: 'Garuva', confidence: 1 }],
|
||||||
|
topics: ['praias'],
|
||||||
|
relationships: [],
|
||||||
|
implicitQuestions: [],
|
||||||
|
temporalContext: { period: '2024' },
|
||||||
|
geographicContext: { location: 'SC' },
|
||||||
|
keywords: ['praias'],
|
||||||
|
synonyms: ['litoral'],
|
||||||
|
domain: 'turismo',
|
||||||
|
complexity: 'simple',
|
||||||
|
};
|
||||||
|
|
||||||
|
const LLM = {
|
||||||
|
literal: ['praias garuva'],
|
||||||
|
semantic: ['litoral garuva'],
|
||||||
|
related: ['melhor praia garuva'],
|
||||||
|
expanded: ['praia itapoá garuva'],
|
||||||
|
contextual: ['praias garuva 2024'],
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('enrichQueries', () => {
|
||||||
|
beforeEach(() => vi.spyOn(console, 'error').mockImplementation(() => {}));
|
||||||
|
|
||||||
|
it('LLM devolve as 5 categorias: repassa e monta o prompt com o contexto', async () => {
|
||||||
|
const fetchMock = stubGenerate(JSON.stringify(LLM));
|
||||||
|
expect(await enrichQueries('praias em Garuva', CTX, 'qwen')).toEqual(LLM);
|
||||||
|
const prompt = sentPrompt(fetchMock);
|
||||||
|
expect(prompt).toContain('"praias em Garuva"');
|
||||||
|
expect(prompt).toContain('- Entidades: location: Garuva');
|
||||||
|
expect(prompt).toContain('- Contexto Temporal: {"period":"2024"}');
|
||||||
|
expect(prompt).toContain('- Contexto Geográfico: {"location":"SC"}');
|
||||||
|
expect(prompt).toContain('- Domínio: turismo');
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['entities', [], '- Entidades: nenhuma'],
|
||||||
|
['temporalContext', undefined, '- Contexto Temporal: nenhum'],
|
||||||
|
['geographicContext', undefined, '- Contexto Geográfico: nenhum'],
|
||||||
|
['topics', [], '- Tópicos: nenhum'],
|
||||||
|
['keywords', [], '- Palavras-chave: nenhuma'],
|
||||||
|
['synonyms', [], '- Sinônimos: nenhum'],
|
||||||
|
['domain', undefined, '- Domínio: geral'],
|
||||||
|
])('contexto sem %s: prompt usa o marcador vazio', async (field, value, line) => {
|
||||||
|
const fetchMock = stubGenerate(JSON.stringify(LLM));
|
||||||
|
await enrichQueries('q', { ...CTX, [field]: value }, 'm');
|
||||||
|
expect(sentPrompt(fetchMock)).toContain(line);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('HTTP não ok: fallback com sinônimo, período e local', async () => {
|
||||||
|
stubGenerate(JSON.stringify(LLM), false);
|
||||||
|
expect(await enrichQueries('praias em Garuva', CTX, 'm')).toEqual({
|
||||||
|
literal: ['praias em Garuva'],
|
||||||
|
semantic: ['litoral em Garuva'],
|
||||||
|
related: [],
|
||||||
|
expanded: [],
|
||||||
|
contextual: ['praias em Garuva 2024', 'praias em Garuva SC'],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sem campo response: JSON vazio falha e cai no fallback', async () => {
|
||||||
|
stubGenerate(undefined);
|
||||||
|
expect((await enrichQueries('q', { ...CTX, synonyms: [], temporalContext: undefined, geographicContext: undefined }, 'm'))).toEqual({
|
||||||
|
literal: ['q'], semantic: [], related: [], expanded: [], contextual: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fallback com contexto relativo "recente": acrescenta "recente"', async () => {
|
||||||
|
stubGenerate('não é json');
|
||||||
|
const r = await enrichQueries('q', { ...CTX, synonyms: [], temporalContext: { relative: 'recente' }, geographicContext: undefined }, 'm');
|
||||||
|
expect(r.contextual).toEqual(['q recente']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('JSON em bloco ```json com texto em volta: extrai o objeto', async () => {
|
||||||
|
stubGenerate(`Aqui:\n\`\`\`json\n${JSON.stringify(LLM)}\n\`\`\``);
|
||||||
|
expect(await enrichQueries('q', CTX, 'm')).toEqual(LLM);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('JSON sem objeto (array): todas as categorias vazias e literal com a original', async () => {
|
||||||
|
stubGenerate('[]');
|
||||||
|
expect(await enrichQueries('q', CTX, 'm')).toEqual({ literal: ['q'], semantic: [], related: [], expanded: [], contextual: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['literal', ['q']],
|
||||||
|
['semantic', []],
|
||||||
|
['related', []],
|
||||||
|
['expanded', []],
|
||||||
|
['contextual', []],
|
||||||
|
])('categoria %s ausente: usa o padrão e mantém as outras', async (field, fallback) => {
|
||||||
|
const partial: Record<string, unknown> = { ...LLM };
|
||||||
|
delete partial[field];
|
||||||
|
stubGenerate(JSON.stringify(partial));
|
||||||
|
expect(await enrichQueries('q', CTX, 'm')).toEqual({ ...LLM, [field]: fallback });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('literal vazio: garante a query original', async () => {
|
||||||
|
stubGenerate(JSON.stringify({ ...LLM, literal: [] }));
|
||||||
|
expect((await enrichQueries('q', CTX, 'm')).literal).toEqual(['q']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetch rejeita (Ollama fora do ar): fallback', async () => {
|
||||||
|
vi.stubGlobal('fetch', vi.fn(async () => { throw new TypeError('refused'); }));
|
||||||
|
expect((await enrichQueries('q', CTX, 'm')).literal).toEqual(['q']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { validateQuery } from './query-validation';
|
||||||
|
|
||||||
|
const IRRELEVANT = 'Pergunta pode ser irrelevante ou muito simples. Considere ser mais específico.';
|
||||||
|
|
||||||
|
describe('validateQuery', () => {
|
||||||
|
it('pergunta normal: válida, sem erros nem avisos', () => {
|
||||||
|
expect(validateQuery('Qual é a capital da França?')).toEqual({
|
||||||
|
isValid: true,
|
||||||
|
errors: [],
|
||||||
|
warnings: [],
|
||||||
|
normalizedLength: 'qual e a capital da franca?'.length,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('string vazia: inválida logo na entrada', () => {
|
||||||
|
expect(validateQuery('')).toEqual({ isValid: false, errors: ['Texto vazio ou inválido'], warnings: [], normalizedLength: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('valor que não é string: inválido logo na entrada', () => {
|
||||||
|
expect(validateQuery(42 as unknown as string).errors).toEqual(['Texto vazio ou inválido']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('abaixo do mínimo: erro de texto curto', () => {
|
||||||
|
const r = validateQuery('ab');
|
||||||
|
expect(r.isValid).toBe(false);
|
||||||
|
expect(r.errors).toEqual(['Texto muito curto. Mínimo de 3 caracteres necessário.']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('acima do máximo configurado: erro de texto longo', () => {
|
||||||
|
const r = validateQuery('uma pergunta comprida', { maxLength: 10 });
|
||||||
|
expect(r.errors).toEqual(['Texto muito longo. Máximo de 10 caracteres permitido.']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('só espaços: erro de espaços, sem erro de emoji nem de pontuação', () => {
|
||||||
|
const r = validateQuery(' ');
|
||||||
|
expect(r.errors).toEqual([
|
||||||
|
'Texto muito curto. Mínimo de 3 caracteres necessário.',
|
||||||
|
'Texto contém apenas espaços em branco ou caracteres especiais.',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('só emojis: erro de emojis', () => {
|
||||||
|
expect(validateQuery('🚀🔥🎉').errors).toContain('Texto contém apenas emojis.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('só emojis com allowEmojis: não acusa emojis', () => {
|
||||||
|
expect(validateQuery('🚀🔥🎉', { allowEmojis: true }).errors).not.toContain('Texto contém apenas emojis.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('só pontuação: erro de pontuação', () => {
|
||||||
|
const r = validateQuery('???');
|
||||||
|
expect(r.errors).toEqual(['Texto contém apenas pontuação.']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('padrão irrelevante com pontuação: válido, mas com aviso', () => {
|
||||||
|
const r = validateQuery('Teste!!');
|
||||||
|
expect(r.isValid).toBe(true);
|
||||||
|
expect(r.warnings).toEqual([IRRELEVANT]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { calculateSemanticSimilarity } from './relevance-scorer';
|
||||||
|
import type { QueryContext } from './contextual-analyzer';
|
||||||
|
|
||||||
|
function ctx(over: Partial<QueryContext> = {}): QueryContext {
|
||||||
|
return {
|
||||||
|
originalQuery: 'q',
|
||||||
|
intent: 'factual',
|
||||||
|
entities: [],
|
||||||
|
topics: [],
|
||||||
|
relationships: [],
|
||||||
|
implicitQuestions: [],
|
||||||
|
keywords: [],
|
||||||
|
synonyms: [],
|
||||||
|
complexity: 'simple',
|
||||||
|
...over,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('calculateSemanticSimilarity', () => {
|
||||||
|
it('todos os sinais batem: soma ponderada com sinônimos limitados a 0.5', () => {
|
||||||
|
const score = calculateSemanticSimilarity(
|
||||||
|
ctx({
|
||||||
|
keywords: ['energia'],
|
||||||
|
entities: [{ type: 'organization', value: 'Petrobras', confidence: 1 }],
|
||||||
|
topics: ['energia solar'],
|
||||||
|
synonyms: ['fotovoltaica'],
|
||||||
|
temporalContext: { period: '2024', relative: 'recente' },
|
||||||
|
geographicContext: { location: 'Bahia' },
|
||||||
|
}),
|
||||||
|
'Petrobras investe em energia solar fotovoltaica recente na Bahia em 2024',
|
||||||
|
);
|
||||||
|
// 0.3 + 0.3 + 0.2 + 0.5*0.1 + min(1.3,1)*0.1 = 0.95, peso total 1.0
|
||||||
|
expect(score).toBeCloseTo(0.95);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('chunk vazio: 0', () => {
|
||||||
|
expect(calculateSemanticSimilarity(ctx({ keywords: ['x'] }), '')).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('contexto ausente: 0', () => {
|
||||||
|
expect(calculateSemanticSimilarity(null as unknown as QueryContext, 'texto')).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('contexto sem nenhum sinal: só o peso contextual, score 0', () => {
|
||||||
|
expect(calculateSemanticSimilarity(ctx(), 'qualquer texto')).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('metade das keywords no chunk: 0.15 de 0.4', () => {
|
||||||
|
expect(calculateSemanticSimilarity(ctx({ keywords: ['solar', 'eolica'] }), 'energia solar')).toBeCloseTo(0.375);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('entidade encontrada pesa pela confiança', () => {
|
||||||
|
const c = ctx({ entities: [{ type: 'location', value: 'Recife', confidence: 0.5 }] });
|
||||||
|
expect(calculateSemanticSimilarity(c, 'chuva em Recife')).toBeCloseTo(0.375);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('entidade ausente do chunk: 0', () => {
|
||||||
|
const c = ctx({ entities: [{ type: 'location', value: 'Recife', confidence: 1 }] });
|
||||||
|
expect(calculateSemanticSimilarity(c, 'chuva em Natal')).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tópico com menos de 50% das palavras no chunk não conta', () => {
|
||||||
|
expect(calculateSemanticSimilarity(ctx({ topics: ['energia solar barata'] }), 'energia nuclear')).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tópico com pelo menos 50% das palavras (>3 letras) conta', () => {
|
||||||
|
expect(calculateSemanticSimilarity(ctx({ topics: ['energia solar barata'] }), 'energia solar cara')).toBeCloseTo(0.2 / 0.3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sinônimos: 1 de 4 encontrado vale 0.25', () => {
|
||||||
|
const c = ctx({ synonyms: ['carro', 'auto', 'veiculo', 'automovel'] });
|
||||||
|
expect(calculateSemanticSimilarity(c, 'um carro')).toBeCloseTo(0.025 / 0.2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sinônimo ausente: 0', () => {
|
||||||
|
expect(calculateSemanticSimilarity(ctx({ synonyms: ['moto'] }), 'um carro')).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('período temporal no chunk soma 0.5 no contextual', () => {
|
||||||
|
expect(calculateSemanticSimilarity(ctx({ temporalContext: { period: '2023' } }), 'dados de 2023')).toBeCloseTo(0.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('período temporal fora do chunk: 0', () => {
|
||||||
|
expect(calculateSemanticSimilarity(ctx({ temporalContext: { period: '2023' } }), 'dados de 2020')).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('contexto relativo com termo recente no chunk soma 0.3', () => {
|
||||||
|
expect(calculateSemanticSimilarity(ctx({ temporalContext: { relative: 'recente' } }), 'versão atual')).toBeCloseTo(0.3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('contexto relativo sem termo recente no chunk: 0', () => {
|
||||||
|
expect(calculateSemanticSimilarity(ctx({ temporalContext: { relative: 'recente' } }), 'versão antiga')).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('local geográfico no chunk soma 0.5', () => {
|
||||||
|
expect(calculateSemanticSimilarity(ctx({ geographicContext: { location: 'Manaus' } }), 'calor em manaus')).toBeCloseTo(0.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('local geográfico fora do chunk: 0', () => {
|
||||||
|
expect(calculateSemanticSimilarity(ctx({ geographicContext: { location: 'Manaus' } }), 'frio em Curitiba')).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keyword acentuada casa com o mesmo termo acentuado no chunk', () => {
|
||||||
|
expect(calculateSemanticSimilarity(ctx({ keywords: ['França'] }), 'Viagem à França')).toBeCloseTo(0.75);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('local acentuado casa com o mesmo local no chunk', () => {
|
||||||
|
const c = ctx({ geographicContext: { location: 'São Paulo' } });
|
||||||
|
expect(calculateSemanticSimilarity(c, 'trânsito em São Paulo')).toBeCloseTo(0.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('"último" no chunk conta como termo relativo', () => {
|
||||||
|
expect(calculateSemanticSimilarity(ctx({ temporalContext: { relative: 'recente' } }), 'o último relatório')).toBeCloseTo(0.3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('entidade, tópico, sinônimo e período acentuados casam com o chunk acentuado', () => {
|
||||||
|
const c = ctx({
|
||||||
|
entities: [{ type: 'location', value: 'Ceará', confidence: 1 }],
|
||||||
|
topics: ['eleição municipal'],
|
||||||
|
synonyms: ['votação'],
|
||||||
|
temporalContext: { period: 'últimos 5 anos' },
|
||||||
|
});
|
||||||
|
// (0.3 + 0.2 + 0.5*0.1 + 0.5*0.1) / 0.7
|
||||||
|
expect(calculateSemanticSimilarity(c, 'Ceará: eleição municipal e votação nos últimos 5 anos')).toBeCloseTo(0.6 / 0.7);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
import Module from 'node:module';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
|
import { executeProgressiveSearch } from './web-search-fallback';
|
||||||
|
import * as relevanceScorer from './relevance-scorer';
|
||||||
|
import type { ScrapedContent } from '@/services/webSearch';
|
||||||
|
import type { QueryContext } from './contextual-analyzer';
|
||||||
|
|
||||||
|
vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(async () => undefined) }));
|
||||||
|
|
||||||
|
const QUERY = 'energia solar residencial';
|
||||||
|
|
||||||
|
function page(id: string | number, relevant = true): ScrapedContent {
|
||||||
|
return relevant
|
||||||
|
? { title: `Energia solar residencial ${id}`, url: `https://ex.com/${id}`, content: '', markdown: `energia solar residencial ${'x'.repeat(120)}` }
|
||||||
|
: { title: `nada ${id}`, url: `https://ex.com/${id}`, content: '', markdown: '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const pages = (n: number, relevant = true, prefix = 'p') => Array.from({ length: n }, (_, i) => page(`${prefix}${i}`, relevant));
|
||||||
|
|
||||||
|
// Fake do Ollama para expandQuery (rodadas > 1 no modo tradicional).
|
||||||
|
function stubExpansion(response: string) {
|
||||||
|
const fetchMock = vi.fn(async () => ({ ok: true, json: async () => ({ response }) }) as Response);
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
return fetchMock;
|
||||||
|
}
|
||||||
|
|
||||||
|
function logged(text: string) {
|
||||||
|
return vi.mocked(invoke).mock.calls.some(
|
||||||
|
([cmd, args]) => cmd === 'log_to_terminal' && !!args && 'message' in args && String(args.message).includes(text),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('executeProgressiveSearch', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.mocked(invoke).mockClear();
|
||||||
|
stubExpansion('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('1ª rodada com 5 resultados relevantes: early exit com sucesso', async () => {
|
||||||
|
const searchFn = vi.fn(async () => pages(5));
|
||||||
|
const r = await executeProgressiveSearch(QUERY, searchFn, 'm');
|
||||||
|
expect(r).toMatchObject({ success: true, usedFallback: false, totalResultsAnalyzed: 5, finalQuery: QUERY });
|
||||||
|
expect(r.attempts).toHaveLength(1);
|
||||||
|
expect(r.attempts[0]).toMatchObject({ round: 1, strategy: 'literal', query: QUERY, queries: undefined, relevanceScore: 1 });
|
||||||
|
expect(searchFn).toHaveBeenCalledWith(QUERY, 10, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('modo semântico: rodadas por estratégia, sem expansão, várias queries por rodada', async () => {
|
||||||
|
const fetchMock = stubExpansion('nao deveria');
|
||||||
|
const searchFn = vi.fn(async (q: string) => [page(q)]);
|
||||||
|
const r = await executeProgressiveSearch(QUERY, searchFn, 'm', {
|
||||||
|
useSemanticSearch: true,
|
||||||
|
enrichedQueries: { literal: ['a'], semantic: ['b'], related: ['c'], expanded: [], contextual: [] },
|
||||||
|
});
|
||||||
|
expect(r.attempts.map((a) => [a.strategy, a.queries ?? a.query])).toEqual([
|
||||||
|
['literal', ['a', 'b']],
|
||||||
|
['related', 'c'],
|
||||||
|
]);
|
||||||
|
expect(fetchMock).not.toHaveBeenCalled();
|
||||||
|
expect(r.success).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('semântico ligado sem enrichedQueries: cai no modo tradicional', async () => {
|
||||||
|
const searchFn = vi.fn(async () => []);
|
||||||
|
const r = await executeProgressiveSearch(QUERY, searchFn, 'm', { useSemanticSearch: true, maxRounds: 2 });
|
||||||
|
expect(r.attempts.map((a) => a.strategy)).toEqual(['literal', 'literal']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('nenhum resultado em todas as rodadas: fallback com maxRounds tentativas', async () => {
|
||||||
|
const r = await executeProgressiveSearch(QUERY, vi.fn(async () => []), 'm', { maxRounds: 3, enableQueryExpansion: false });
|
||||||
|
expect(r).toMatchObject({ success: false, usedFallback: true, totalResultsAnalyzed: 0, scrapedSources: [] });
|
||||||
|
expect(r.attempts).toHaveLength(3);
|
||||||
|
expect(r.attempts[0].relevanceScore).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tempo total da query esgotado antes da 1ª rodada: nenhuma busca', async () => {
|
||||||
|
let t = 0;
|
||||||
|
vi.spyOn(Date, 'now').mockImplementation(() => (t += 30_000));
|
||||||
|
const searchFn = vi.fn(async () => pages(5));
|
||||||
|
const r = await executeProgressiveSearch(QUERY, searchFn, 'm');
|
||||||
|
expect(searchFn).not.toHaveBeenCalled();
|
||||||
|
expect(r).toMatchObject({ success: false, attempts: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('maxTimeoutPerQuery 0: usa o padrão de 25s em vez de parar na hora', async () => {
|
||||||
|
let t = 0;
|
||||||
|
vi.spyOn(Date, 'now').mockImplementation(() => (t += 1_000));
|
||||||
|
const searchFn = vi.fn(async () => pages(5));
|
||||||
|
const r = await executeProgressiveSearch(QUERY, searchFn, 'm', { maxTimeoutPerQuery: 0 });
|
||||||
|
expect(r.success).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('2ª rodada tradicional: expande a query pelo Ollama', async () => {
|
||||||
|
const fetchMock = stubExpansion('"painel solar para casa."');
|
||||||
|
const searchFn = vi.fn(async (_q: string) => [] as ScrapedContent[]);
|
||||||
|
await executeProgressiveSearch(QUERY, searchFn, 'm', { maxRounds: 2 });
|
||||||
|
expect(searchFn.mock.calls.map((c) => c[0])).toEqual([QUERY, 'painel solar para casa']);
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('expansão desligada: 2ª rodada repete a query original', async () => {
|
||||||
|
const fetchMock = stubExpansion('outra coisa');
|
||||||
|
const searchFn = vi.fn(async (_q: string) => [] as ScrapedContent[]);
|
||||||
|
await executeProgressiveSearch(QUERY, searchFn, 'm', { maxRounds: 2, enableQueryExpansion: false });
|
||||||
|
expect(searchFn.mock.calls.map((c) => c[0])).toEqual([QUERY, QUERY]);
|
||||||
|
expect(fetchMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('searchFn lança: rodada vazia e segue para a próxima', async () => {
|
||||||
|
const searchFn = vi.fn()
|
||||||
|
.mockRejectedValueOnce(new Error('motor caiu'))
|
||||||
|
.mockResolvedValueOnce(pages(5));
|
||||||
|
const r = await executeProgressiveSearch(QUERY, searchFn, 'm', { enableQueryExpansion: false });
|
||||||
|
expect(r.success).toBe(true);
|
||||||
|
expect(r.attempts.map((a) => a.results.length)).toEqual([0, 5]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('timeout da rodada: usa o que já chegou sem esperar a query travada', async () => {
|
||||||
|
const searchFn = vi.fn(async (q: string) => (q === 'trava' ? new Promise<ScrapedContent[]>(() => {}) : [page('ok')]));
|
||||||
|
const r = await executeProgressiveSearch(QUERY, searchFn, 'm', {
|
||||||
|
useSemanticSearch: true,
|
||||||
|
enrichedQueries: { literal: ['rapida', 'trava'], semantic: [], related: [], expanded: [], contextual: [] },
|
||||||
|
maxTimeoutPerRound: 50,
|
||||||
|
});
|
||||||
|
expect(r.attempts).toHaveLength(1);
|
||||||
|
expect(r.attempts[0].results.map((p) => p.url)).toEqual(['https://ex.com/ok']);
|
||||||
|
expect(r.attempts[0].query).toBe('rapida');
|
||||||
|
}, 2_000);
|
||||||
|
|
||||||
|
it('timeout da rodada sem nenhuma query concluída: registra a query original', async () => {
|
||||||
|
const searchFn = vi.fn(() => new Promise<ScrapedContent[]>(() => {}));
|
||||||
|
const r = await executeProgressiveSearch(QUERY, searchFn, 'm', { maxRounds: 1, maxTimeoutPerRound: 20 });
|
||||||
|
expect(r.attempts[0]).toMatchObject({ query: QUERY, results: [] });
|
||||||
|
}, 2_000);
|
||||||
|
|
||||||
|
it('URL repetida entre rodadas: conta só uma vez', async () => {
|
||||||
|
const searchFn = vi.fn(async () => [page('mesma', false)]);
|
||||||
|
const r = await executeProgressiveSearch(QUERY, searchFn, 'm', { maxRounds: 2, enableQueryExpansion: false });
|
||||||
|
expect(r.attempts.map((a) => a.results.length)).toEqual([1, 0]);
|
||||||
|
expect(r.scrapedSources).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('mais de 3 resultados numa rodada: registra quantos sobraram no log', async () => {
|
||||||
|
await executeProgressiveSearch(QUERY, vi.fn(async () => pages(5, false)), 'm', { maxRounds: 1 });
|
||||||
|
expect(logged('... and 2 more results')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('até 3 resultados numa rodada: sem a linha de excedentes', async () => {
|
||||||
|
await executeProgressiveSearch(QUERY, vi.fn(async () => pages(3, false)), 'm', { maxRounds: 1 });
|
||||||
|
expect(logged('more results')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('com contexto: relevância vem de calculateSemanticSimilarity', async () => {
|
||||||
|
// Em produção o webpack resolve este require; o require do Node não carrega .ts sem extensão.
|
||||||
|
const nodeRequire = Module.prototype.require;
|
||||||
|
vi.spyOn(Module.prototype, 'require').mockImplementation(function (this: NodeJS.Module, id: string) {
|
||||||
|
return id === './relevance-scorer' ? relevanceScorer : nodeRequire.call(this, id);
|
||||||
|
} as typeof nodeRequire);
|
||||||
|
const context = { keywords: ['inexistente'], entities: [], topics: [], synonyms: [] } as unknown as QueryContext;
|
||||||
|
const r = await executeProgressiveSearch(QUERY, vi.fn(async () => pages(5)), 'm', { context, maxRounds: 1 });
|
||||||
|
// Pela heurística sem contexto o score seria 1 (early exit); com contexto a keyword não casa.
|
||||||
|
expect(r.attempts[0].relevanceScore).toBe(0);
|
||||||
|
expect(r.success).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('5+ resultados com relevância baixa: não sai cedo', async () => {
|
||||||
|
const r = await executeProgressiveSearch(QUERY, vi.fn(async () => pages(6, false)), 'm', { maxRounds: 1 });
|
||||||
|
expect(r).toMatchObject({ success: false, usedFallback: true, totalResultsAnalyzed: 6 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('minResultsForEarlyExit e minRelevanceForEarlyExit configurados: sai com 1 resultado', async () => {
|
||||||
|
const r = await executeProgressiveSearch(QUERY, vi.fn(async () => [page(1)]), 'm', { minResultsForEarlyExit: 1, minRelevanceForEarlyExit: 0.9 });
|
||||||
|
expect(r.success).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('atingiu maxTotalResults: para antes das rodadas restantes', async () => {
|
||||||
|
let n = 0;
|
||||||
|
const searchFn = vi.fn(async () => pages(4, false, `r${n++}-`));
|
||||||
|
const r = await executeProgressiveSearch(QUERY, searchFn, 'm', { maxTotalResults: 6, maxRounds: 4, enableQueryExpansion: false });
|
||||||
|
expect(r.attempts).toHaveLength(2);
|
||||||
|
expect(r).toMatchObject({ success: false, totalResultsAnalyzed: 8 });
|
||||||
|
});
|
||||||
|
});
|
||||||
+6
-1
@@ -7,6 +7,7 @@
|
|||||||
"build": "next build",
|
"build": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"lint": "eslint",
|
"lint": "eslint",
|
||||||
|
"test": "vitest run",
|
||||||
"generate-changelog": "node scripts/generate-changelog.js",
|
"generate-changelog": "node scripts/generate-changelog.js",
|
||||||
"bump-version": "node scripts/bump-version.js"
|
"bump-version": "node scripts/bump-version.js"
|
||||||
},
|
},
|
||||||
@@ -47,14 +48,18 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/postcss": "^4",
|
"@tailwindcss/postcss": "^4",
|
||||||
"@tauri-apps/cli": "^2.9.4",
|
"@tauri-apps/cli": "^2.9.4",
|
||||||
|
"@testing-library/dom": "^10.4.2",
|
||||||
|
"@testing-library/react": "^16.3.3",
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
"eslint": "^9",
|
"eslint": "^9",
|
||||||
"eslint-config-next": "16.0.3",
|
"eslint-config-next": "16.0.3",
|
||||||
|
"happy-dom": "^21.0.4",
|
||||||
"raw-loader": "^4.0.2",
|
"raw-loader": "^4.0.2",
|
||||||
"tailwindcss": "^4",
|
"tailwindcss": "^4",
|
||||||
"tw-animate-css": "^1.4.0",
|
"tw-animate-css": "^1.4.0",
|
||||||
"typescript": "^5"
|
"typescript": "^5",
|
||||||
|
"vitest": "^5.1.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Generated
+985
-141
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,166 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import type { SearchConfig, SearchResultMetadata } from './webSearch';
|
||||||
|
|
||||||
|
// O backend Rust (Tauri) vira um fake: nenhum motor de busca real é chamado.
|
||||||
|
const invokeMock = vi.hoisted(() => vi.fn());
|
||||||
|
vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));
|
||||||
|
|
||||||
|
const META: SearchResultMetadata = { title: 'T', url: 'https://ex.com/a', snippet: 's' };
|
||||||
|
const ENGINES = ['google', 'bing', 'yahoo', 'duckduckgo', 'startpage'];
|
||||||
|
|
||||||
|
// O serviço é um singleton com circuit breaker e cache de falhas: módulo novo por teste.
|
||||||
|
async function load() {
|
||||||
|
vi.resetModules();
|
||||||
|
const { webSearchService } = await import('./webSearch');
|
||||||
|
const { useSettingsStore } = await import('@/store/settings-store');
|
||||||
|
const { EngineCircuitBreaker } = await import('./engine-circuit-breaker');
|
||||||
|
const { FailureCache } = await import('./failure-cache');
|
||||||
|
return { svc: webSearchService, store: useSettingsStore, EngineCircuitBreaker, FailureCache };
|
||||||
|
}
|
||||||
|
|
||||||
|
function backend(metadata: () => Promise<unknown>) {
|
||||||
|
invokeMock.mockImplementation(async (cmd: string) => {
|
||||||
|
if (cmd === 'search_web_metadata') return metadata();
|
||||||
|
if (cmd === 'scrape_urls') return [];
|
||||||
|
throw new Error(`comando inesperado: ${cmd}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const metadataCalls = () => invokeMock.mock.calls.filter(([cmd]) => cmd === 'search_web_metadata');
|
||||||
|
|
||||||
|
describe('executeMetadataSearch (via smartSearchRag)', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
invokeMock.mockReset();
|
||||||
|
localStorage.clear(); // o persist do zustand reidrataria settings de outro teste
|
||||||
|
for (const level of ['log', 'warn', 'error'] as const) vi.spyOn(console, level).mockImplementation(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('backend devolve metadados: repassa a query aparada, limite e ordem de motores', async () => {
|
||||||
|
const { svc } = await load();
|
||||||
|
backend(async () => [META]);
|
||||||
|
const r = await svc.smartSearchRag(' rust ', 1);
|
||||||
|
expect(r.metadata).toEqual([META]);
|
||||||
|
expect(metadataCalls()[0][1]).toEqual({ query: 'rust', limit: 5, search_config: undefined, engineOrder: ENGINES });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('query com falha recente e resultados parciais: devolve os parciais sem chamar o backend', async () => {
|
||||||
|
const { svc, FailureCache } = await load();
|
||||||
|
vi.spyOn(FailureCache.prototype, 'get').mockReturnValue({ query: 'q', timestamp: Date.now(), error: 'x', partialResults: [META], attempts: 1 });
|
||||||
|
backend(async () => []);
|
||||||
|
expect((await svc.smartSearchRag('q', 1)).metadata).toEqual([META]);
|
||||||
|
expect(metadataCalls()).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('query com falha recente sem parciais: vazio sem chamar o backend', async () => {
|
||||||
|
const { svc, FailureCache } = await load();
|
||||||
|
vi.spyOn(FailureCache.prototype, 'get').mockReturnValue({ query: 'q', timestamp: Date.now(), error: 'x', partialResults: [], attempts: 1 });
|
||||||
|
backend(async () => [META]);
|
||||||
|
expect((await svc.smartSearchRag('q', 1)).metadata).toEqual([]);
|
||||||
|
expect(metadataCalls()).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('settings sem engineOrder: usa a ordem padrão de motores', async () => {
|
||||||
|
const { svc, store } = await load();
|
||||||
|
store.setState({ webSearch: { ...store.getState().webSearch, engineOrder: undefined as unknown as string[] } });
|
||||||
|
backend(async () => [META]);
|
||||||
|
await svc.smartSearchRag('q', 1);
|
||||||
|
expect(metadataCalls()[0][1]).toMatchObject({ engineOrder: ENGINES });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('todos os motores com circuit breaker aberto: tenta todos mesmo assim', async () => {
|
||||||
|
const { svc, EngineCircuitBreaker } = await load();
|
||||||
|
vi.spyOn(EngineCircuitBreaker.prototype, 'getAvailableEngines').mockReturnValue([]);
|
||||||
|
backend(async () => [META]);
|
||||||
|
await svc.smartSearchRag('q', 1);
|
||||||
|
expect(metadataCalls()[0][1]).toMatchObject({ engineOrder: ENGINES });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('motor com circuit breaker aberto: sai da lista enviada ao backend', async () => {
|
||||||
|
const { svc, EngineCircuitBreaker } = await load();
|
||||||
|
vi.spyOn(EngineCircuitBreaker.prototype, 'getAvailableEngines').mockReturnValue(['bing']);
|
||||||
|
backend(async () => [META]);
|
||||||
|
await svc.smartSearchRag('q', 1);
|
||||||
|
expect(metadataCalls()[0][1]).toMatchObject({ engineOrder: ['bing'] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('com SearchConfig: converte para o formato snake_case do Rust', async () => {
|
||||||
|
const { svc } = await load();
|
||||||
|
backend(async () => [META]);
|
||||||
|
const config: SearchConfig = {
|
||||||
|
maxConcurrentTabs: 2,
|
||||||
|
totalSourcesLimit: 7,
|
||||||
|
categories: [{ id: 'c', name: 'Cat', baseSites: ['a.com'], enabled: true }],
|
||||||
|
userCustomSites: ['b.com'],
|
||||||
|
excludedDomains: ['x.com'],
|
||||||
|
};
|
||||||
|
await svc.smartSearchRag('q', 1, config);
|
||||||
|
expect(metadataCalls()[0][1]).toMatchObject({
|
||||||
|
search_config: {
|
||||||
|
max_concurrent_tabs: 2,
|
||||||
|
total_sources_limit: 7,
|
||||||
|
categories: [{ id: 'c', name: 'Cat', base_sites: ['a.com'], enabled: true }],
|
||||||
|
user_custom_sites: ['b.com'],
|
||||||
|
excluded_domains: ['x.com'],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sucesso: registra acerto só para o primeiro motor', async () => {
|
||||||
|
const { svc, EngineCircuitBreaker } = await load();
|
||||||
|
const record = vi.spyOn(EngineCircuitBreaker.prototype, 'recordAttempt');
|
||||||
|
backend(async () => [META]);
|
||||||
|
await svc.smartSearchRag('q', 1);
|
||||||
|
expect(record).toHaveBeenCalledTimes(1);
|
||||||
|
expect(record).toHaveBeenCalledWith('google', true, expect.any(Number));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sucesso com lista de motores vazia: não registra no circuit breaker', async () => {
|
||||||
|
const { svc, store, EngineCircuitBreaker } = await load();
|
||||||
|
store.setState({ webSearch: { ...store.getState().webSearch, engineOrder: [] } });
|
||||||
|
const record = vi.spyOn(EngineCircuitBreaker.prototype, 'recordAttempt');
|
||||||
|
backend(async () => [META]);
|
||||||
|
expect((await svc.smartSearchRag('q', 1)).metadata).toEqual([META]);
|
||||||
|
expect(record).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('erro não recuperável: uma tentativa, falha em todos os motores, vazio e query bloqueada', async () => {
|
||||||
|
const { svc, EngineCircuitBreaker } = await load();
|
||||||
|
const record = vi.spyOn(EngineCircuitBreaker.prototype, 'recordAttempt');
|
||||||
|
backend(async () => { throw new Error('permission denied'); });
|
||||||
|
expect((await svc.smartSearchRag('q', 1)).metadata).toEqual([]);
|
||||||
|
expect(metadataCalls()).toHaveLength(1);
|
||||||
|
expect(record.mock.calls.map(([engine, ok]) => [engine, ok])).toEqual(ENGINES.map((e) => [e, false]));
|
||||||
|
await svc.smartSearchRag('q', 1);
|
||||||
|
expect(metadataCalls()).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('erro recuperável: 3 tentativas com backoff, vazio e query bloqueada', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
try {
|
||||||
|
const { svc } = await load();
|
||||||
|
backend(async () => { throw new Error('network unreachable'); });
|
||||||
|
const pending = svc.smartSearchRag('q', 1);
|
||||||
|
await vi.advanceTimersByTimeAsync(10_000);
|
||||||
|
expect((await pending).metadata).toEqual([]);
|
||||||
|
expect(metadataCalls()).toHaveLength(3);
|
||||||
|
await svc.smartSearchRag('q', 1);
|
||||||
|
expect(metadataCalls()).toHaveLength(3);
|
||||||
|
} finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejeição que não é Error: tratada como falha e devolve vazio', async () => {
|
||||||
|
const { svc } = await load();
|
||||||
|
backend(() => Promise.reject('boom'));
|
||||||
|
expect((await svc.smartSearchRag('q', 1)).metadata).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('backend devolve lista vazia: vazio e sem bloquear a query', async () => {
|
||||||
|
const { svc } = await load();
|
||||||
|
backend(async () => []);
|
||||||
|
expect((await svc.smartSearchRag('q', 1)).metadata).toEqual([]);
|
||||||
|
await svc.smartSearchRag('q', 1);
|
||||||
|
expect(metadataCalls()).toHaveLength(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
// vitest em vez de node --test: o código usa imports com alias `@/` (tsconfig paths),
|
||||||
|
// que o node --test não resolve sem loader próprio. Ver spec 2026-11-16-testes-ciclomaticos-ui, seção 5.
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { defineConfig } from 'vitest/config';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
resolve: {
|
||||||
|
alias: [{ find: /^@\//, replacement: fileURLToPath(new URL('./', import.meta.url)) }],
|
||||||
|
},
|
||||||
|
test: {
|
||||||
|
include: ['{lib,hooks,services}/**/*.test.ts'],
|
||||||
|
environment: 'happy-dom', // localStorage para o persist do zustand e DOM para renderHook
|
||||||
|
restoreMocks: true,
|
||||||
|
unstubGlobals: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
Reference in new issue
Block a user