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,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({});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user