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