Author SHA1 Message Date
evandro 60c98fc51e test: caminhos-base de components 2026-11-16 00:35:14 -03:00
evandro 9a0e0205dc fix: escapa HTML do conteúdo no destaque de busca do chat
O destaque montava HTML com o texto cru da mensagem e injetava via
dangerouslySetInnerHTML: <img onerror> numa mensagem executava script
ao buscar um termo presente nela.
2026-11-16 00:30:39 -03:00
evandro da9b5e1865 fix: mensagem do usuário com destaque de busca não quebra a renderização
children=false junto com dangerouslySetInnerHTML faz o React lançar
'Can only set one of children or dangerouslySetInnerHTML'.
2026-11-16 00:30:26 -03:00
evandro 52da9be974 fix: SelectItem sem valor vazio no gerador de prompts
Com nenhum modelo instalado, o Radix Select lança ao renderizar
<SelectItem value=""> e o diálogo quebra ao abrir.
2026-11-16 00:28:24 -03:00
evandro adc37e1921 test: caminhos-base de lib, hooks e services 2026-11-16 00:26:52 -03:00
evandro 9d911603f7 fix: timeout da rodada usa só as queries já concluídas
No timeout, executeProgressiveSearch chamava Promise.allSettled nas
mesmas promises e esperava todas terminarem; uma busca travada prendia
a pesquisa inteira apesar do maxTimeoutPerRound.
2026-11-16 00:19:04 -03:00
evandro 7247e1e80b fix: troca chatLog.success inexistente por chatLog.info
chatLog não tem success: a chamada lançava TypeError dentro do try, e
analyzeQueryContext e enrichQueries sempre descartavam a resposta do
modelo e caíam no fallback heurístico.
2026-11-16 00:16:21 -03:00
evandro 94941414e9 fix: normaliza termos do contexto antes de comparar com o chunk
calculateSemanticSimilarity normalizava o chunk (sem acentos) mas só
aplicava toLowerCase em keywords, entidades, tópicos, sinônimos, período
e local, e a lista de termos relativos tinha 'último' acentuado. Termos
com acento nunca casavam.
2026-11-16 00:14:08 -03:00
evandro f0b7db8c12 docs(readme): redesenha o README com hero em SVG [skip ci] 2026-10-24 04:57:52 -03:00
evandro 2835957e40 docs: redesign do README (padrão TwitterBR-MOD) — dados atualizados
Build and Release / build (appimage, ubuntu-latest, x86_64-unknown-linux-gnu) (push) Failing after 6m25s
Build and Release / build (dmg, macos-latest, aarch64-apple-darwin) (push) Canceled after 0s
Build and Release / build (dmg, macos-latest, x86_64-apple-darwin) (push) Canceled after 0s
Build and Release / build (msi, windows-latest, x86_64-pc-windows-msvc) (push) Canceled after 0s
Build and Release / create-release (push) Canceled after 0s
2026-10-13 21:50:58 -03:00
Evandro Fonseca Junior 3e57b78aa7 Merge pull request #7 from evandrodevbr:develop
Build and Release / build (appimage, ubuntu-latest, x86_64-unknown-linux-gnu) (push) Failing after 6m18s
Build and Release / build (dmg, macos-latest, aarch64-apple-darwin) (push) Canceled after 0s
Build and Release / build (dmg, macos-latest, x86_64-apple-darwin) (push) Canceled after 0s
Build and Release / build (msi, windows-latest, x86_64-pc-windows-msvc) (push) Canceled after 0s
Build and Release / create-release (push) Canceled after 0s
chore: add 'develop' branch to release workflow triggers
2025-11-27 23:04:26 -03:00
Evandro Fonseca Junior cde8e5ac00 chore: add 'develop' branch to release workflow triggers
- Included 'develop' branch in the GitHub Actions release workflow to enable automated releases from the development branch, enhancing CI/CD processes.
2025-11-27 23:03:58 -03:00
Evandro Fonseca Junior 6fdbd4bfe6 chore: update pnpm workspace configuration
- Added root package to the pnpm workspace configuration to streamline dependency management across the project.
2025-11-27 23:02:59 -03:00
Evandro Fonseca Junior d01d26e74f Merge pull request #6 from evandrodevbr:develop
chore: streamline pnpm installation in release workflow
2025-11-27 22:59:06 -03:00
Evandro Fonseca Junior e51a54c568 Merge remote-tracking branch 'origin/master' into develop 2025-11-27 22:58:59 -03:00
Evandro Fonseca Junior a319a9cf8d chore: streamline pnpm installation in release workflow
- Removed duplicate pnpm installation steps in the GitHub Actions release workflow.
- Ensured consistent setup of pnpm across jobs to optimize workflow efficiency.
2025-11-27 22:58:29 -03:00
Evandro Fonseca Junior 1daa6c77ee Merge pull request #5 from evandrodevbr:develop
remove: delete the document "Estabilizar Scraper Rust (Browser Resurrection, Send e Retry)" as it is no longer needed for the project. This document contained analysis, context, and implementation plans for improving the scraper's resilience and functionality.
2025-11-27 22:54:28 -03:00
Evandro Fonseca Junior 3e5727ffc7 remove: delete the document "Estabilizar Scraper Rust (Browser Resurrection, Send e Retry)" as it is no longer needed for the project. This document contained analysis, context, and implementation plans for improving the scraper's resilience and functionality. 2025-11-27 22:53:55 -03:00
Evandro Fonseca Junior 162a6f37f7 Merge pull request #4 from evandrodevbr:app-automatic-att
feat: integrate automatic update checks and enhance settings UI
2025-11-27 22:48:06 -03:00
Evandro Fonseca Junior 7d169d8a61 Merge pull request #1 from evandrodevbr/develop
feat: enhance chat functionality with markdown support and default prompts
2025-11-19 00:40:26 -03:00
39 changed files with 4276 additions and 305 deletions

No files matched your search

+11 -10
View File
@@ -5,6 +5,7 @@ on:
branches:
- main
- master
- develop
workflow_dispatch:
env:
@@ -39,17 +40,17 @@ jobs:
with:
fetch-depth: 0
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: 8
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'pnpm'
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: 8
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
with:
@@ -110,17 +111,17 @@ jobs:
with:
fetch-depth: 0
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: 8
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'pnpm'
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: 8
- name: Get version
id: get_version
run: |
@@ -1,114 +0,0 @@
## 📋 Análise
**Solicitação**: Corrigir falhas de conexão do browser headless e o erro de compilação `Send`, tornar o scraper resiliente com retry e ampliar resultados de busca.
**Objetivo real**: Garantir estabilidade contínua do backend de scraping, mesmo quando o Chrome headless cai, evitando violações de `Send` e melhorando a cobertura de fontes.
## 🔍 Contexto Identificado
### Arquivos Examinados
- `src-tauri/src/lib.rs:1176–1193` get_or_create_browser: cria/reutiliza `Browser` singleton.
- `src-tauri/src/lib.rs:1247–1277` search_web_metadata: comando Tauri que exige `Future + Send`.
- `src-tauri/src/web_scraper.rs:136–240` search_duckduckgo_metadata: parsing HTML, previously segurava `Html` atravessando `await`.
- `src-tauri/src/web_scraper.rs:469–538` search_and_scrape_with_config: coordena scraping paralelo e coleta resultados.
- `src-tauri/src/web_scraper.rs:605–736` fetch_and_convert_sync: cria aba, navega, extrai HTML e usa Readability.
- `src-tauri/src/lib.rs:1306–1399` force_kill_browser: encerra processos Chrome headless.
### Padrões Detectados
- **Singleton Browser** via `State<BrowserState>` com `Arc<Browser>`.
- **Concorrência controlada** com `Semaphore` e `tokio::spawn_blocking` para operações de Chrome.
- **Fallbacks**: limpeza de URL, filtros anti-ads, Readability + fallback por parágrafos.
### Dependências Mapeadas
```
web_scraper (modificado)
├─ headless_chrome::Browser/Tab
├─ reqwest (HTTP)
├─ scraper (Html, Selector) [não Send]
└─ readability, html2text
lib (modificado)
└─ tauri commands (Future + Send obrigatório)
```
## 🎯 Abordagens Viáveis
### Abordagem A: Verificação ativa de Browser + Retry cooperativo
**Conceito**: Validar liveness do `Browser` antes de uso; se cair durante scraping, recriar e repetir uma passada de URLs com limite de tentativas.
```
request → get_or_create_browser (is_alive?) → spawn scraping
↳ erro conn fechada → reset + recreate → retry restante (1x)
```
**Vantagens**: ✓ Simples de integrar, ✓ Minimiza impacto, ✓ Boa resiliência
**Desvantagens**: ✗ Retry global pode repetir algumas URLs
**Complexidade**: O(n) | Tempo: 3–4h | Risco: Médio
### Abordagem B: Pool/Auto-heal por task
**Conceito**: Cada task recupera o browser ao falhar e re-executa só sua URL.
```
spawn_blocking(url) → new_tab → erro conn → sinaliza reset → reobtem browser → reprocessa url
```
**Vantagens**: ✓ Isolamento por URL
**Desvantagens**: ✗ Coordenação de estado entre threads, ✗ Maior complexidade
**Complexidade**: O(n) | Tempo: 5–6h | Risco: Médio-Alto
## 🏆 Recomendação
**Abordagem A** porque:
- Alinha com o padrão singleton já existente.
- Menor acoplamento entre tarefas e estado global.
- Implementação direta com menor risco de condições de corrida.
## ⚠️ Riscos & Mitigações
| Risco | Prob | Impacto | Mitigação |
|-------|------|---------|-----------|
| Loop de retry infinito | Baixa | Médio | Limitar a 1–2 tentativas, backoff curto |
| Recriação concorrente do Browser | Média | Médio | Guardar lock no `BrowserState` e checar antes de recriar |
| Demasiadas abas simultâneas | Média | Médio | Reduzir `max_concurrent_tabs` ao detectar falha |
| DDG bloqueios 429 | Média | Baixo | Rotação User-Agent e backoff |
## 📝 Plano de Execução
1. Ajustes `Send` (consolidação)
- Isolar parsing `scraper::Html` em escopo síncrono que retorna `Vec<SearchResultMetadata>` (já aplicado em parte na função; revisar para todos os caminhos).
- Garantir que nenhum `Html`/`Selector` vive além do `await` nos métodos `search_*`.
- Verificar pontos: `src-tauri/src/web_scraper.rs:136–240` e demais que usem `Html`.
2. Browser Resurrection
- Adicionar `fn is_browser_alive(browser: &Browser) -> bool` em `web_scraper.rs` ou `lib.rs` (ex.: tentar `new_tab()` e descartar; ou `get_tabs()`; se falhar → false).
- Alterar `get_or_create_browser` (`src-tauri/src/lib.rs:1176–1193`) para: se `Some(browser)` e `!is_alive(browser)` → `reset` e `create_browser()`.
- Em `force_kill_browser` (`src-tauri/src/lib.rs:1306–1399`): após kill, setar `BrowserState` para `None` via lock (ou orientar UI a chamar `reset_browser` antes do kill), garantindo recriação no próximo uso.
3. Retry resiliente no Scraper
- Envolver `fetch_and_convert_sync` com camada de retry (máx. 2 tentativas) na orquestração async (`search_and_scrape_with_config` em `src-tauri/src/web_scraper.rs:469–538`).
- Se erro contiver "underlying connection is closed"/timeout global do browser:
- Executar `reset_browser` e `get_or_create_browser` para novo `Arc<Browser)`.
- Reprocessar as URLs que falharam apenas uma vez com o novo browser.
- Reduzir temporariamente `max_concurrent_tabs` para 3 ao detectar queda, evitando sobrecarga imediata.
4. Paginação no DuckDuckGo
- Em `search_duckduckgo` (`src-tauri/src/web_scraper.rs:78–133`): suportar paginação via parâmetro `s=<offset>` até atingir `limit` (30–50).
- Extrair links por página, deduplicar, respeitar `excluded_domains`/ads.
5. Telemetria e Logs
- Logar eventos de recreação de browser, tentativas de retry e motivos.
- Contadores: quedas de browser, tentativas, tempo médio por URL.
6. Testes/Validação
- Caso 1: Forçar `force_kill_browser` durante scraping → validar que a próxima chamada recria o browser e conclui.
- Caso 2: Simular DDG com >= 40 resultados → paginar e coletar sem violar `Send`.
- Caso 3: Stress com `max_concurrent_tabs=5` → se cair, reduzir e recuperar.
## Key Changes (Resumo de Implementação)
- `lib.rs:1176–1193`: `get_or_create_browser` verifica liveness; recria se morto.
- `lib.rs:1306–1399`: sincronia com `reset_browser` ao matar processos.
- `web_scraper.rs:469–538`: retry global (1x) e recriação de browser ao detectar conexão fechada; ajuste dinamicamente `Semaphore` na segunda passada.
- `web_scraper.rs:78–133`: paginação DDG com `s=` offset.
- `web_scraper.rs:136–240`: parsing isolado; garantir que `Html` é dropado antes do `await`.
## Entregáveis
- Código robusto em `web_scraper.rs` e `lib.rs` com:
- Correção total do `Send`.
- Resurreição automática do browser.
- Retry controlado por erro de conexão.
- Paginação para 30–50 resultados.
- Logs melhorados e validação manual automática.
## ❓ Aguardando Aprovação
- [ ] Posso prosseguir com as mudanças propostas?
- [ ] Preferências de `max_concurrent_tabs` e `limit` padrão (sugestão: 5 e 40)?
- [ ] Deseja manter `force_kill_browser` como utilitário avançado, com alerta na UI para reiniciar o scraper?
+66 -21
View File
@@ -1,36 +1,81 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
<div align="center">
## Getting Started
<img src="assets/readme/hero.svg" width="100%" alt="OllaHub: desktop chat for your local Ollama models, with web search and MCP tools">
First, run the development server:
![Version 0.1.0](https://img.shields.io/badge/version-0.1.0-555?style=flat-square)
![Tauri 2](https://img.shields.io/badge/Tauri-2-24C8DB?style=flat-square&logo=tauri&logoColor=white)
![Next.js 16](https://img.shields.io/badge/Next.js-16.0.3-000000?style=flat-square&logo=nextdotjs&logoColor=white)
![React 19](https://img.shields.io/badge/React-19-61DAFB?style=flat-square&logo=react&logoColor=black)
![Platforms](https://img.shields.io/badge/platforms-Windows_%7C_macOS_%7C_Linux-1447e6?style=flat-square)
[Quick start](#quick-start) · [Docs](docs/) · [Issues](https://git.evandro.dev.br/evandro/OllaHub/issues)
</div>
## What it is
OllaHub is a desktop chat app for the models you run with [Ollama](https://ollama.com). On first run it scans your hardware, recommends a model and downloads it. After that it chats with streaming, keeps history in a local SQLite database, and can add context from web search, MCP tools and scheduled tasks. The UI is Next.js inside a Tauri 2 window, and a Rust backend does the work.
OllaHub is a client, not a model runtime. It talks to the Ollama API (default `http://localhost:11434`, configurable in Settings), tries to start Ollama when it is installed but stopped, and can download the Ollama installer when it is missing.
## Why use it
- **Local by default.** Prompts go to your own Ollama, and chats live in `ollahub.db` in the app data directory, with FTS5 full-text search. Besides downloads (models, the embedding model, updates), web search is what reaches the internet.
- **Web answers ranked on your machine.** Headless Chrome scrapes Google, Bing, Yahoo, DuckDuckGo and Startpage (order configurable), then local embeddings (`all-MiniLM-L6-v2` on ONNX Runtime) rank and prune the pages, with a BM25-like fallback when the embedding model is unavailable. A deep-research mode runs planning → searching → aggregating → validating → formulating.
- **More than a chat box.** MCP servers run as child processes configured in `mcp_config.json`, their tools can be called from the chat, and cron tasks (search and summarize, notification, custom prompt) keep running in the background.
**When not to use it:** if you want a finished, tested product (version `0.1.0`, no test suite), a model runtime of its own, or a server you can run without a desktop.
## How it works
- **Frontend** (`app/`, `components/`, `hooks/`, `lib/`, `store/`): Next.js 16 with `output: 'export'`, React 19, Tailwind 4, Radix UI and Zustand. It calls the backend through Tauri `invoke` and events.
- **Backend** (`src-tauri/src/`): `lib.rs` holds the commands for chat (`chat_stream`), models, the Ollama lifecycle, sessions, MCP, search, tasks, export and the installer. `db.rs` handles SQLite, `web_scraper.rs` the search engines, `embeddings.rs` the ranking, and `scheduler.rs` the cron tasks stored in `tasks.json`.
- **Models:** list, delete and pull with progress, install a local `.gguf` file, and get a recommendation for your hardware.
- **System monitor:** CPU and RAM stats plus GPU VRAM, usage and temperature. GPU detection uses `wmic` and `nvidia-smi` on Windows and `lspci` on Linux.
- **Updates:** the Tauri updater checks automatically. Its endpoint in `src-tauri/tauri.conf.json` points to a GitHub Releases `latest.json`.
More notes: [`docs/updater-setup.md`](docs/updater-setup.md) (signing keys and updater) and [`docs/style-guide.md`](docs/style-guide.md) (UI spacing, radii, accessibility).
## Quick start
No release is published on this repository yet, so build it locally. You need Node.js 20, pnpm 8, a stable Rust toolchain and the [Tauri 2 prerequisites](https://tauri.app/start/prerequisites/) (the versions come from the CI workflow). On Ubuntu the workflow also installs `libwebkit2gtk-4.1-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev patchelf`. Ollama is needed at runtime.
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
git clone https://git.evandro.dev.br/evandro/OllaHub.git
cd OllaHub
pnpm install
pnpm tauri dev # starts `pnpm dev` (Next.js on http://localhost:3000) inside the Tauri window
pnpm tauri build # runs `pnpm generate-changelog && pnpm build`, then bundles the installer
pnpm lint # ESLint
pnpm bump-version # patch | minor | major, optional --commit
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
The workflow [`.github/workflows/release.yml`](.github/workflows/release.yml) builds `msi` (Windows), `dmg` (macOS, Apple Silicon and Intel) and `AppImage` (Linux) on pushes to `main`, `master` and `develop`, and publishes release `v<version>` on pushes to `main` or `master`.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
> [!WARNING]
> **Two things the app does on its own.**
> 1. Opening the chat page pulls the small helper model **`qwen2.5:0.5b`** if it is not installed yet, used for automatic chat titles. Expect an extra download on first use.
> 2. **Closing the window only hides it.** The close request is intercepted (`prevent_close`) so scheduled tasks keep running, but there is no tray icon to bring the window back yet; the tray step is still pending in [`IMPLEMENTATION_GUIDE.md`](IMPLEMENTATION_GUIDE.md).
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Project status
## Learn More
Early: version `0.1.0`, 47 commits between 2025-10-27 and 2025-11-27, no automated tests (`package.json` defines `dev`, `build`, `start`, `lint`, `generate-changelog` and `bump-version`). Known limitations:
To learn more about Next.js, take a look at the following resources:
- **No tray icon yet:** closing the window hides it (see the warning above).
- **"Start with the system" does nothing yet:** the setting only toggles a stored flag; the code has a `TODO` until `tauri-plugin-autostart` is configured.
- **RAG inside `chat_stream` is not wired:** the `enable_rag` branch is commented out as `TODO`; the frontend assembles web context before the request.
- **Embeddings outside Windows:** the ONNX Runtime library is downloaded automatically only on Windows. On macOS and Linux, provide it in the app data folder or on the system path, otherwise ranking falls back to BM25-like scoring.
- **Unused leftovers:** `src-tauri/scripts/scraper.py` is not called by the Rust backend, and the 188 model files in `data/models/` are not referenced by the app code.
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
## License
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
No published license: all rights reserved.
## Deploy on Vercel
Built with [Tauri](https://tauri.app), [Next.js](https://nextjs.org), [Radix UI](https://www.radix-ui.com), [Tailwind CSS](https://tailwindcss.com), [Zustand](https://zustand-demo.pmnd.rs), [Lucide](https://lucide.dev), [headless_chrome](https://github.com/rust-headless-chrome/rust-headless-chrome), [ONNX Runtime](https://onnxruntime.ai) and the [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) model.
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
<div align="center">
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
<sub>Made by <a href="https://evandro.dev.br">Evandro Fonseca Junior</a> · <a href="https://git.evandro.dev.br/evandro">git.evandro.dev.br</a></sub>
</div>
+59
View File
@@ -0,0 +1,59 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="420" viewBox="0 0 1200 420" role="img" aria-labelledby="title desc">
<title id="title">OllaHub</title>
<desc id="desc">OllaHub: a desktop window with a chat sidebar, a local Ollama model download in progress, an answer backed by numbered web sources, and Web and MCP toggles in the message box.</desc>
<rect width="1200" height="420" rx="24" fill="#09090B"/>
<g id="title-block" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif">
<text x="64" y="170" font-size="64" font-weight="700" fill="#FAFAFA">OllaHub</text>
<text x="64" y="226" font-size="28" fill="#FAFAFA">Desktop chat for your local Ollama</text>
<text x="64" y="264" font-size="28" fill="#FAFAFA">models, with web search and MCP.</text>
<text x="64" y="322" font-size="20" fill="#9F9FA9" font-family="ui-monospace, 'SF Mono', Consolas, monospace">Tauri 2 · Rust · Next.js 16 · React 19</text>
</g>
<g id="window" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif">
<rect x="608" y="52" width="528" height="316" rx="14" fill="#09090B" stroke="#27272A" stroke-width="2"/>
<path d="M622 52 h500 a14 14 0 0 1 14 14 v26 h-528 v-26 a14 14 0 0 1 14 -14 z" fill="#18181B"/>
<text x="628" y="79" font-size="18" fill="#9F9FA9">OllaHub</text>
<g fill="none" stroke="#9F9FA9" stroke-width="2" stroke-linecap="round">
<path d="M1052 72 h14"/>
<rect x="1078" y="65" width="14" height="14" rx="2"/>
<path d="M1106 65 l14 14 M1120 65 l-14 14"/>
</g>
<path d="M608 92 h528" stroke="#27272A" stroke-width="2"/>
<path d="M608 92 h144 v276 h-130 a14 14 0 0 1 -14 -14 z" fill="#18181B"/>
<rect x="622" y="108" width="116" height="34" rx="8" fill="#1447E6"/>
<text x="680" y="131" font-size="18" fill="#FAFAFA" text-anchor="middle">New chat</text>
<rect x="622" y="166" width="100" height="10" rx="5" fill="#27272A"/>
<rect x="622" y="192" width="84" height="10" rx="5" fill="#27272A"/>
<rect x="622" y="218" width="94" height="10" rx="5" fill="#27272A"/>
<rect x="622" y="244" width="72" height="10" rx="5" fill="#27272A"/>
<text x="772" y="128" font-size="18" fill="#FAFAFA" font-family="ui-monospace, 'SF Mono', Consolas, monospace">qwen2.5:0.5b</text>
<rect x="772" y="140" width="344" height="10" rx="5" fill="#27272A"/>
<rect x="772" y="140" width="220" height="10" rx="5" fill="#1447E6"/>
<rect x="772" y="170" width="344" height="116" rx="12" fill="#201E25"/>
<rect x="790" y="190" width="290" height="10" rx="5" fill="#9F9FA9"/>
<rect x="790" y="212" width="300" height="10" rx="5" fill="#9F9FA9"/>
<rect x="790" y="234" width="180" height="10" rx="5" fill="#9F9FA9"/>
<text x="790" y="272" font-size="18" fill="#9F9FA9">Sources</text>
<g font-size="18" fill="#FAFAFA" text-anchor="middle">
<rect x="866" y="254" width="26" height="26" rx="13" fill="#27272A"/>
<text x="879" y="273">1</text>
<rect x="898" y="254" width="26" height="26" rx="13" fill="#27272A"/>
<text x="911" y="273">2</text>
<rect x="930" y="254" width="26" height="26" rx="13" fill="#27272A"/>
<text x="943" y="273">3</text>
</g>
<rect x="772" y="302" width="344" height="40" rx="20" fill="#18181B" stroke="#27272A" stroke-width="2"/>
<rect x="782" y="309" width="60" height="26" rx="13" fill="#27272A"/>
<text x="812" y="328" font-size="18" fill="#FAFAFA" text-anchor="middle">Web</text>
<rect x="850" y="309" width="62" height="26" rx="13" fill="#27272A"/>
<text x="881" y="328" font-size="18" fill="#FAFAFA" text-anchor="middle">MCP</text>
<circle cx="1096" cy="322" r="13" fill="#1447E6"/>
<path d="M1096 328 v-12 M1090 321 l6 -6 l6 6" fill="none" stroke="#FAFAFA" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.8 KiB

+140
View File
@@ -0,0 +1,140 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import { ChatInput } from './chat-input';
import { useSettingsStore } from '@/store/settings-store';
// Ramos só visuais (cor do texto inválido, ícone Globe/WifiOff, ícone por categoria) ficam mapeados sem teste.
const defaults = useSettingsStore.getState().queryPreprocessing;
const box = () => screen.getByPlaceholderText('Pergunte qualquer coisa...') as HTMLTextAreaElement;
const type = (text: string) => fireEvent.change(box(), { target: { value: text } });
beforeEach(() => {
localStorage.clear();
useSettingsStore.setState({ queryPreprocessing: defaults });
});
describe('ChatInput: envio', () => {
it('Enter com texto válido: envia e limpa a caixa', () => {
const onSend = vi.fn();
render(<ChatInput onSend={onSend} onStop={vi.fn()} isLoading={false} />);
type('qual a versão do node?');
fireEvent.keyDown(box(), { key: 'Enter' });
expect(onSend).toHaveBeenCalledWith('qual a versão do node?');
expect(box().value).toBe('');
});
it('Shift+Enter: não envia', () => {
const onSend = vi.fn();
render(<ChatInput onSend={onSend} onStop={vi.fn()} isLoading={false} />);
type('linha um');
fireEvent.keyDown(box(), { key: 'Enter', shiftKey: true });
expect(onSend).not.toHaveBeenCalled();
});
it('caixa em branco: botão de enviar desativado e Enter não envia', () => {
const onSend = vi.fn();
render(<ChatInput onSend={onSend} onStop={vi.fn()} isLoading={false} />);
type(' ');
expect(screen.getByRole('button')).toHaveProperty('disabled', true);
fireEvent.keyDown(box(), { key: 'Enter' });
expect(onSend).not.toHaveBeenCalled();
});
it('texto abaixo do mínimo: mostra o erro de validação e não envia', () => {
const onSend = vi.fn();
render(<ChatInput onSend={onSend} onStop={vi.fn()} isLoading={false} />);
type('ab');
expect(screen.getByText(/mínimo/i)).toBeTruthy();
expect(screen.getByRole('button')).toHaveProperty('disabled', true);
fireEvent.keyDown(box(), { key: 'Enter' });
expect(onSend).not.toHaveBeenCalled();
});
it('pré-processamento desligado: aceita texto curto', () => {
useSettingsStore.setState({ queryPreprocessing: { ...defaults, enabled: false } });
const onSend = vi.fn();
render(<ChatInput onSend={onSend} onStop={vi.fn()} isLoading={false} />);
type('ab');
fireEvent.click(screen.getByRole('button'));
expect(onSend).toHaveBeenCalledWith('ab');
});
it('settings sem queryPreprocessing: usa mínimo 3 padrão', () => {
useSettingsStore.setState({ queryPreprocessing: undefined as unknown as typeof defaults });
render(<ChatInput onSend={vi.fn()} onStop={vi.fn()} isLoading={false} />);
type('ab');
expect(screen.getByRole('button')).toHaveProperty('disabled', true);
type('abc');
expect(screen.getByRole('button')).toHaveProperty('disabled', false);
});
it('padrões irrelevantes vazios: só avisa, ainda envia', () => {
useSettingsStore.setState({ queryPreprocessing: { ...defaults, irrelevantPatterns: [] } });
const onSend = vi.fn();
render(<ChatInput onSend={onSend} onStop={vi.fn()} isLoading={false} />);
type('teste');
fireEvent.keyDown(box(), { key: 'Enter' });
expect(onSend).toHaveBeenCalledWith('teste');
});
it('carregando: Enter não envia e o botão vira parar', () => {
const onSend = vi.fn();
const onStop = vi.fn();
render(<ChatInput onSend={onSend} onStop={onStop} isLoading />);
type('qual a versão do node?');
fireEvent.keyDown(box(), { key: 'Enter' });
expect(onSend).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button'));
expect(onStop).toHaveBeenCalled();
});
});
describe('ChatInput: pesquisa web', () => {
it('desativada: um clique reativa sem confirmação', () => {
const toggle = vi.fn();
render(<ChatInput onSend={vi.fn()} onStop={vi.fn()} isLoading={false} webSearchEnabled={false} onWebSearchToggle={toggle} />);
fireEvent.click(screen.getAllByRole('button')[0]);
expect(toggle).toHaveBeenCalledWith(true);
expect(screen.queryByRole('dialog')).toBeNull();
});
it('ativada: pede confirmação e "Desativar" desliga', () => {
const toggle = vi.fn();
render(<ChatInput onSend={vi.fn()} onStop={vi.fn()} isLoading={false} onWebSearchToggle={toggle} />);
fireEvent.click(screen.getAllByRole('button')[0]);
expect(screen.getByRole('dialog', { name: 'Desativar pesquisa web?' })).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: 'Desativar' }));
expect(toggle).toHaveBeenCalledWith(false);
});
it('ativada e "Cancelar" na confirmação: mantém ligada', () => {
const toggle = vi.fn();
render(<ChatInput onSend={vi.fn()} onStop={vi.fn()} isLoading={false} onWebSearchToggle={toggle} />);
fireEvent.click(screen.getAllByRole('button')[0]);
fireEvent.click(screen.getByRole('button', { name: 'Cancelar' }));
expect(toggle).not.toHaveBeenCalled();
});
it('sem categorias: não oferece o menu de fontes', () => {
render(<ChatInput onSend={vi.fn()} onStop={vi.fn()} isLoading={false} onToggleCategory={vi.fn()} categories={[]} />);
expect(screen.queryByTitle('Gerenciar fontes')).toBeNull();
});
it('menu de fontes: marcar categoria chama onToggleCategory com o novo estado', () => {
const onToggleCategory = vi.fn();
render(
<ChatInput
onSend={vi.fn()}
onStop={vi.fn()}
isLoading={false}
onToggleCategory={onToggleCategory}
categories={[{ id: 'news', name: 'Notícias', baseSites: [], enabled: false }]}
/>,
);
const trigger = screen.getByTitle('Gerenciar fontes');
fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false, pointerType: 'mouse' });
fireEvent.click(screen.getByRole('menuitemcheckbox', { name: 'Notícias' }));
expect(onToggleCategory).toHaveBeenCalledWith('news', true);
});
});
+76
View File
@@ -0,0 +1,76 @@
import { describe, expect, it } from 'vitest';
import { render, screen } from '@testing-library/react';
import { ChatMessage } from './chat-message';
import type { Message } from '@/hooks/use-chat';
// Ramos só visuais (cor do <mark> atual, seleção ao clicar, ícone) ficam mapeados sem teste: dependem de classes CSS.
const user = (content: string): Message => ({ role: 'user', content });
const bot = (content: string, metadata?: unknown): Message => ({ role: 'assistant', content, metadata });
describe('ChatMessage', () => {
it('metadata de pensamento: renderiza a etapa em vez do balão', () => {
render(<ChatMessage message={bot('', { type: 'thinking', stepType: 'processing', status: 'running', label: 'Lendo fontes', timestamp: 0 })} />);
expect(screen.getByText('Lendo fontes')).toBeTruthy();
expect(screen.queryByTitle('Copiar Markdown')).toBeNull();
});
it('assistente finalizado: markdown renderizado e ações de cópia visíveis', () => {
render(<ChatMessage message={bot('Use **cargo build**')} />);
expect(screen.getByText('cargo build').tagName).toBe('STRONG');
expect(screen.getByTitle('Copiar Markdown')).toBeTruthy();
});
it('assistente em streaming: texto cru, sem markdown e sem ações', () => {
render(<ChatMessage message={bot('Use **cargo**')} isStreaming />);
expect(screen.getByText('Use **cargo**')).toBeTruthy();
expect(screen.queryByTitle('Copiar Markdown')).toBeNull();
});
it('assistente vazio em streaming: indicador "Gerando resposta..."', () => {
render(<ChatMessage message={bot(' ')} isStreaming />);
expect(screen.getByText('Gerando resposta...')).toBeTruthy();
});
it('bloco <metadata> e prefixo final: removidos do texto exibido', () => {
render(<ChatMessage message={user('Pergunta final\nMetadata:<metadata>{"a":1}</metadata>')} />);
expect(screen.getByText('Pergunta final')).toBeTruthy();
expect(screen.queryByText(/metadata/i)).toBeNull();
});
it('busca com termo presente: marca todas as ocorrências', () => {
const { container } = render(<ChatMessage message={user('rust e Rust e RUST')} highlightTerm=" rust " />);
expect([...container.querySelectorAll('mark')].map((m) => m.textContent)).toEqual(['rust', 'Rust', 'RUST']);
});
it('termo de busca com caractere especial de regex: casa literalmente', () => {
const { container } = render(<ChatMessage message={user('custa (R$ 10) hoje')} highlightTerm="(R$" />);
expect([...container.querySelectorAll('mark')].map((m) => m.textContent)).toEqual(['(R$']);
});
it.each([
['termo com menos de 2 caracteres', { highlightTerm: 'r' }],
['termo ausente no texto', { highlightTerm: 'python' }],
['durante o streaming', { highlightTerm: 'rust', isStreaming: true }],
])('%s: sem marcação', (_n, props) => {
const { container } = render(<ChatMessage message={user('rust aqui')} {...props} />);
expect(container.querySelector('mark')).toBeNull();
expect(screen.getByText('rust aqui')).toBeTruthy();
});
it('mensagem de sistema: não aplica destaque', () => {
const { container } = render(<ChatMessage message={{ role: 'system', content: 'rust' }} highlightTerm="rust" />);
expect(container.querySelector('mark')).toBeNull();
});
it('assistente com termo de busca: marca o termo no texto', () => {
const { container } = render(<ChatMessage message={bot('instale o rust')} highlightTerm="rust" />);
expect(container.querySelector('mark')?.textContent).toBe('rust');
});
it('destaque não interpreta HTML vindo do conteúdo da mensagem', () => {
render(<ChatMessage message={user('<img src="x" onerror="alert(1)"> rust')} highlightTerm="rust" />);
expect(screen.queryByRole('img')).toBeNull();
expect(screen.getByText(/<img src="x" onerror="alert\(1\)">/)).toBeTruthy();
});
});
+14 -4
View File
@@ -18,6 +18,16 @@ interface ChatMessageProps {
messageIndex?: number;
}
// O destaque de busca vira HTML (dangerouslySetInnerHTML): o texto da mensagem precisa ser escapado.
function escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
/**
* Componente de mensagem do chat otimizado com React.memo
*
@@ -96,7 +106,7 @@ function ChatMessageComponent({ message, isStreaming = false, highlightTerm, hig
matches.forEach((match, idx) => {
// Adicionar texto antes do match
highlighted += content.substring(lastIndex, match.start);
highlighted += escapeHtml(content.substring(lastIndex, match.start));
// Adicionar match com highlight (laranja para atual, amarelo para outros)
const isCurrent = highlightIndex !== undefined && idx === highlightIndex;
@@ -104,12 +114,12 @@ function ChatMessageComponent({ message, isStreaming = false, highlightTerm, hig
? 'bg-orange-400/60 dark:bg-orange-500/60 px-0.5 rounded'
: 'bg-yellow-200/50 dark:bg-yellow-800/50 px-0.5 rounded';
highlighted += `<mark class="${className}">${match.text}</mark>`;
highlighted += `<mark class="${className}">${escapeHtml(match.text)}</mark>`;
lastIndex = match.end;
});
// Adicionar texto restante
highlighted += content.substring(lastIndex);
highlighted += escapeHtml(content.substring(lastIndex));
return highlighted;
}, [processedContent, highlightTerm, highlightIndex, message.role, isStreaming]);
@@ -143,7 +153,7 @@ function ChatMessageComponent({ message, isStreaming = false, highlightTerm, hig
className="text-lg sm:text-xl font-medium tracking-tight text-foreground/90 leading-relaxed break-words whitespace-pre-wrap"
dangerouslySetInnerHTML={highlightedContent ? { __html: highlightedContent } : undefined}
>
{!highlightedContent && processedContent}
{highlightedContent ? null : processedContent}
</div>
) : (
// Estilo Assistant
+82
View File
@@ -0,0 +1,82 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { McpConfigPanel } from './mcp-config-panel';
// Comandos Tauri dos servidores MCP e o toast viram fakes; nenhum servidor MCP é iniciado.
const { invokeMock, toast } = vi.hoisted(() => ({ invokeMock: vi.fn(), toast: vi.fn() }));
vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));
vi.mock('@/hooks/use-toast', () => ({ useToast: () => ({ toast }) }));
let saveResult: () => Promise<void> = async () => {};
beforeEach(() => {
saveResult = async () => {};
toast.mockReset();
invokeMock.mockReset();
invokeMock.mockImplementation(async (cmd: string) => {
if (cmd === 'load_mcp_config') return { mcpServers: {} };
if (cmd === 'list_mcp_server_status') return [];
if (cmd === 'get_mcp_config_path_command') return '/cfg/mcp.json';
if (cmd === 'save_mcp_config') return saveResult();
throw new Error(`comando inesperado: ${cmd}`);
});
vi.spyOn(console, 'error').mockImplementation(() => {});
});
async function saveWith(json: string) {
render(<McpConfigPanel />);
const editor = await screen.findByRole('textbox'); // durante o carregamento só há o spinner
await waitFor(() => expect((editor as HTMLTextAreaElement).value).toContain('mcpServers'));
fireEvent.change(editor, { target: { value: json } });
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Salvar' })));
}
const saved = () => invokeMock.mock.calls.filter(([cmd]) => cmd === 'save_mcp_config').map(([, args]) => args);
const lastToast = () => toast.mock.calls[toast.mock.calls.length - 1][0];
describe('McpConfigPanel.saveConfig', () => {
it('JSON em branco: avisa e não salva', async () => {
await saveWith(' ');
expect(lastToast()).toMatchObject({ title: 'Erro', description: expect.stringContaining('JSON vazio') });
expect(saved()).toEqual([]);
});
it('JSON inválido: erro de JSON e não salva', async () => {
await saveWith('{ "mcpServers": ');
expect(lastToast()).toMatchObject({ title: 'Erro de JSON', description: expect.stringContaining('JSON inválido:') });
expect(saved()).toEqual([]);
});
it.each(['null', '"texto"'])('JSON %s (não objeto): avisa e não salva', async (json) => {
await saveWith(json);
expect(lastToast()).toMatchObject({ description: 'Configuração inválida: deve ser um objeto JSON.' });
expect(saved()).toEqual([]);
});
it.each([
['sem mcpServers', '{"outro": 1}'],
['mcpServers não objeto', '{"mcpServers": "x"}'],
])('%s: salva a estrutura mínima', async (_n, json) => {
await saveWith(json);
expect(saved()).toEqual([{ config: { mcpServers: {} } }]);
});
it('config válida: salva só mcpServers, avisa sucesso e recarrega o status', async () => {
const servers = { fs: { command: 'npx', args: ['-y', 'server-fs'] } };
await saveWith(JSON.stringify({ mcpServers: servers, extra: true }));
expect(saved()).toEqual([{ config: { mcpServers: servers } }]);
expect(lastToast()).toMatchObject({ title: 'Sucesso' });
expect(invokeMock.mock.calls.filter(([cmd]) => cmd === 'list_mcp_server_status')).toHaveLength(2);
expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe(JSON.stringify({ mcpServers: servers }, null, 2));
});
it.each([
['Error', new Error('permissão negada'), 'Falha ao salvar configuração MCP: permissão negada'],
['string do Rust', 'disco cheio', 'Falha ao salvar configuração MCP: Erro desconhecido'],
])('backend falha com %s: toast de erro', async (_n, error, description) => {
saveResult = async () => { throw error; };
await saveWith('{"mcpServers": {}}');
expect(lastToast()).toMatchObject({ title: 'Erro', description });
expect(screen.getByRole('button', { name: 'Salvar' })).toHaveProperty('disabled', false);
});
});
+75
View File
@@ -0,0 +1,75 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen } from '@testing-library/react';
import { useState } from 'react';
import { McpJsonEditor } from './mcp-json-editor';
// Tema claro/escuro do realce e o anel vermelho do textarea inválido são só visuais: mapeados sem teste.
function Controlled({ initial, onChange }: { initial: string; onChange?: (v: string) => void }) {
const [value, setValue] = useState(initial);
return <McpJsonEditor value={value} onChange={(v) => { setValue(v); onChange?.(v); }} />;
}
const editor = () => screen.getByRole('textbox') as HTMLTextAreaElement;
const formatButton = () => screen.getByRole('button', { name: 'Formatar' });
beforeEach(() => {
vi.useFakeTimers({ toFake: ['setTimeout'] });
});
afterEach(() => {
vi.useRealTimers();
});
describe('McpJsonEditor', () => {
it('vazio: sem erro nem "Válido" e Formatar desativado', () => {
render(<Controlled initial="" />);
expect(screen.queryByText('Válido')).toBeNull();
expect(formatButton()).toHaveProperty('disabled', true);
});
it('JSON válido: mostra "Válido" e a contagem de linhas no plural', () => {
render(<Controlled initial={'{\n"a": 1\n}'} />);
expect(screen.getByText('Válido')).toBeTruthy();
expect(screen.getByText('3 linhas')).toBeTruthy();
});
it('uma linha: contagem no singular', () => {
render(<Controlled initial='{"a":1}' />);
expect(screen.getByText('1 linha')).toBeTruthy();
});
it('digitar JSON inválido: mostra a mensagem do parser e repassa o texto', () => {
const onChange = vi.fn();
render(<Controlled initial="{}" onChange={onChange} />);
fireEvent.change(editor(), { target: { value: '{"a":' } });
expect(onChange).toHaveBeenCalledWith('{"a":');
expect(screen.queryByText('Válido')).toBeNull();
expect(screen.getByText(/JSON/)).toBeTruthy();
});
it('Formatar JSON válido: reindenta com 2 espaços e mostra "Formatado" por 2 s', () => {
render(<Controlled initial='{"a":{"b":1}}' />);
fireEvent.click(formatButton());
expect(editor().value).toBe('{\n "a": {\n "b": 1\n }\n}');
expect(screen.getByText('Formatado')).toBeTruthy();
act(() => vi.advanceTimersByTime(2000));
expect(screen.queryByText('Formatado')).toBeNull();
});
it('Formatar JSON inválido: não altera o texto', () => {
const onChange = vi.fn();
render(<Controlled initial="{oops" onChange={onChange} />);
fireEvent.click(formatButton());
expect(onChange).not.toHaveBeenCalled();
expect(editor().value).toBe('{oops');
expect(screen.queryByText('Formatado')).toBeNull();
});
it('editar depois de formatar: some o "Formatado"', () => {
render(<Controlled initial='{"a":1}' />);
fireEvent.click(formatButton());
fireEvent.change(editor(), { target: { value: '{"a":2}' } });
expect(screen.queryByText('Formatado')).toBeNull();
});
});
@@ -0,0 +1,64 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, within } from '@testing-library/react';
import { MessageStepThinking } from './message-step-thinking';
import type { ThinkingMessageMetadata } from '@/hooks/use-chat';
// getStepIcon só escolhe um ícone lucide sem rótulo acessível: caminho mapeado, sem teste (regra: sem classes CSS).
function step(extra: Partial<ThinkingMessageMetadata> = {}): ThinkingMessageMetadata {
return { type: 'thinking', stepType: 'web-research', status: 'completed', label: 'Pesquisando na web', timestamp: 0, ...extra };
}
beforeEach(() => {
vi.spyOn(console, 'error').mockImplementation(() => {});
});
describe('MessageStepThinking', () => {
it('sem detalhes, fontes ou erro: mostra o rótulo e nenhum botão de expandir', () => {
render(<MessageStepThinking metadata={step()} />);
expect(screen.getByText('Pesquisando na web')).toBeTruthy();
expect(screen.queryByRole('button')).toBeNull();
});
it('com detalhes: só aparecem depois de expandir e somem ao recolher', () => {
render(<MessageStepThinking metadata={step({ details: '3 páginas lidas' })} />);
expect(screen.queryByText('3 páginas lidas')).toBeNull();
fireEvent.click(screen.getByRole('button'));
expect(screen.getByText('3 páginas lidas')).toBeTruthy();
fireEvent.click(screen.getAllByRole('button')[0]);
expect(screen.queryByText('3 páginas lidas')).toBeNull();
});
it('fontes: link com título ou, sem título, com a própria URL', () => {
render(<MessageStepThinking metadata={step({ sources: [{ url: 'https://a.dev', title: 'Site A' }, { url: 'https://b.dev', title: '' }] })} />);
fireEvent.click(screen.getByRole('button'));
expect(screen.getByRole('link', { name: 'Site A' }).getAttribute('href')).toBe('https://a.dev');
expect(screen.getByRole('link', { name: 'https://b.dev' })).toBeTruthy();
});
it('erro: mostra a mensagem ao expandir', () => {
render(<MessageStepThinking metadata={step({ status: 'error', stepType: 'error', error: 'timeout na busca' })} />);
fireEvent.click(screen.getByRole('button'));
expect(screen.getByText('timeout na busca')).toBeTruthy();
});
it('copiar fonte: escreve a URL na área de transferência', async () => {
const writeText = vi.fn(async () => {});
vi.spyOn(navigator, 'clipboard', 'get').mockReturnValue({ writeText } as unknown as Clipboard);
render(<MessageStepThinking metadata={step({ sources: [{ url: 'https://a.dev', title: 'Site A' }] })} />);
fireEvent.click(screen.getByRole('button'));
const source = screen.getByRole('link', { name: 'Site A' }).parentElement!;
await act(async () => fireEvent.click(within(source).getByRole('button')));
expect(writeText).toHaveBeenCalledWith('https://a.dev');
});
it('cópia recusada pelo navegador: registra o erro sem quebrar', async () => {
vi.spyOn(navigator, 'clipboard', 'get').mockReturnValue({ writeText: vi.fn(async () => { throw new Error('negado'); }) } as unknown as Clipboard);
render(<MessageStepThinking metadata={step({ sources: [{ url: 'https://a.dev', title: 'Site A' }] })} />);
fireEvent.click(screen.getByRole('button'));
const source = screen.getByRole('link', { name: 'Site A' }).parentElement!;
await act(async () => fireEvent.click(within(source).getByRole('button')));
expect(console.error).toHaveBeenCalledWith('Failed to copy URL:', expect.any(Error));
expect(screen.getByRole('link', { name: 'Site A' })).toBeTruthy();
});
});
@@ -0,0 +1,286 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { ModelDownloadDialog } from './model-download-dialog';
// Comandos Tauri (pull_model, seletor nativo de arquivo, install_gguf_model) e o evento de progresso viram fakes.
const { invokeMock, listeners } = vi.hoisted(() => ({
invokeMock: vi.fn(),
listeners: {} as Record<string, (event: { payload: string }) => void>,
}));
vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));
vi.mock('@tauri-apps/api/event', () => ({
listen: vi.fn(async (name: string, cb: (event: { payload: string }) => void) => {
listeners[name] = cb;
return () => {};
}),
}));
const backend = {
installed: false,
pull: (): Promise<void> => Promise.withResolvers<void>().promise, // download em andamento
pickFile: async (): Promise<string | null> => null,
installGguf: async (_args: unknown): Promise<string> => 'modelo-local',
};
beforeEach(() => {
backend.installed = false;
backend.pull = () => Promise.withResolvers<void>().promise;
backend.pickFile = async () => null;
backend.installGguf = async () => 'modelo-local';
invokeMock.mockReset();
invokeMock.mockImplementation(async (cmd: string, args: unknown) => {
if (cmd === 'check_if_model_installed') return backend.installed;
if (cmd === 'pull_model') return backend.pull();
if (cmd === 'open_gguf_file_dialog') return backend.pickFile();
if (cmd === 'install_gguf_model') return backend.installGguf(args);
throw new Error(`comando inesperado: ${cmd}`);
});
vi.spyOn(console, 'error').mockImplementation(() => {});
});
async function open(onSuccess: ((name: string) => void) | undefined = vi.fn()) {
const onOpenChange = vi.fn();
render(<ModelDownloadDialog open onOpenChange={onOpenChange} onSuccess={onSuccess} />);
await waitFor(() => expect(listeners['download-progress']).toBeDefined());
return { onOpenChange, onSuccess };
}
const nameField = () => screen.getByLabelText('Nome do Modelo');
const progress = (payload: object | string) =>
act(() => listeners['download-progress']({ payload: typeof payload === 'string' ? payload : JSON.stringify(payload) }));
async function startDownload(name = 'llama3.2:1b') {
fireEvent.change(nameField(), { target: { value: name } });
fireEvent.click(screen.getByRole('button', { name: 'Baixar' }));
await screen.findByText('Iniciando download...');
}
describe('ModelDownloadDialog: baixar do Ollama', () => {
it('nome com caractere inválido: botão Baixar desativado e Enter não baixa', async () => {
await open();
fireEvent.change(nameField(), { target: { value: 'llama 3' } });
fireEvent.keyDown(nameField(), { key: 'Enter' });
expect(screen.getByRole('button', { name: 'Baixar' })).toHaveProperty('disabled', true);
expect(invokeMock).not.toHaveBeenCalledWith('pull_model', expect.anything());
});
it.each(['/llama', 'llama:', '-llama'])('nome "%s" com /, : ou - na ponta: botão desativado', async (name) => {
await open();
fireEvent.change(nameField(), { target: { value: name } });
expect(screen.getByRole('button', { name: 'Baixar' })).toHaveProperty('disabled', true);
});
it('Enter com nome válido: inicia o download do nome aparado', async () => {
await open();
fireEvent.change(nameField(), { target: { value: ' huihui_ai/qwen3:1.7b ' } });
fireEvent.keyDown(nameField(), { key: 'Enter' });
await waitFor(() => expect(invokeMock).toHaveBeenCalledWith('pull_model', { name: 'huihui_ai/qwen3:1.7b' }));
});
it('modelo já instalado: avisa e "Usar Modelo" notifica e fecha sem baixar', async () => {
backend.installed = true;
const { onOpenChange, onSuccess } = await open();
fireEvent.change(nameField(), { target: { value: 'mistral:latest' } });
expect(await screen.findByText('✓ Este modelo já está instalado')).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: 'Usar Modelo' }));
expect(onSuccess).toHaveBeenCalledWith('mistral:latest');
expect(onOpenChange).toHaveBeenCalledWith(false);
expect(invokeMock).not.toHaveBeenCalledWith('pull_model', expect.anything());
});
it('modelo já instalado e Enter: notifica sem baixar e sem fechar', async () => {
backend.installed = true;
const { onOpenChange, onSuccess } = await open();
fireEvent.change(nameField(), { target: { value: 'mistral:latest' } });
await screen.findByText('✓ Este modelo já está instalado');
fireEvent.keyDown(nameField(), { key: 'Enter' });
expect(onSuccess).toHaveBeenCalledWith('mistral:latest');
expect(onOpenChange).not.toHaveBeenCalled();
});
it('pull_model falha com Error: mostra a mensagem e volta ao botão Baixar', async () => {
const pending = Promise.withResolvers<void>();
backend.pull = () => pending.promise;
await open();
await startDownload();
await act(async () => pending.reject(new Error('manifest not found')));
expect(screen.getByText('manifest not found')).toBeTruthy();
expect(screen.getByRole('button', { name: 'Baixar' })).toHaveProperty('disabled', false);
});
it('pull_model falha sem mensagem: texto genérico', async () => {
backend.pull = async () => { throw 'erro do rust'; };
await open();
fireEvent.change(nameField(), { target: { value: 'llama3.2:1b' } });
fireEvent.click(screen.getByRole('button', { name: 'Baixar' }));
expect(await screen.findByText('Falha no download. Tente novamente.')).toBeTruthy();
});
});
describe('ModelDownloadDialog: evento download-progress', () => {
it('fora de um download: evento ignorado', async () => {
await open();
progress({ status: 'pulling', percent: 50, raw: '' });
expect(screen.queryByText('50%')).toBeNull();
});
it.each([
['pulling', 'Baixando modelo...', '10%'],
['verifying', 'Verificando...', '90%'],
['writing', 'Salvando...', '95%'],
['outro', 'Baixando...', '0%'],
])('status %s sem percent: "%s" e %s', async (status, text, pct) => {
await open();
await startDownload();
progress({ status, raw: '' });
expect(screen.getByText(text, { selector: 'span' })).toBeTruthy();
expect(screen.getByText(pct)).toBeTruthy();
});
it('pulling sem percent depois de 40%: não regride', async () => {
await open();
await startDownload();
progress({ status: 'pulling', percent: 40, raw: '' });
progress({ status: 'pulling', raw: '' });
expect(screen.getByText('40%')).toBeTruthy();
});
it('payload que não é JSON: status genérico', async () => {
await open();
await startDownload();
progress('pulling manifest');
expect(screen.getByText('Baixando...', { selector: 'span' })).toBeTruthy();
});
it('baixado, total e velocidade: mostra os três; só baixado: mostra só ele', async () => {
await open();
await startDownload();
progress({ status: 'pulling', percent: 20, downloaded: '1 GB', total: '4 GB', speed: '9 MB/s', raw: '' });
expect(screen.getByText('1 GB / 4 GB')).toBeTruthy();
expect(screen.getByText('9 MB/s')).toBeTruthy();
progress({ status: 'pulling', percent: 21, downloaded: '1.1 GB', raw: '' });
expect(screen.getByText('1.1 GB')).toBeTruthy();
});
it.each([
['percent 100', { status: 'pulling', percent: 100, raw: '' }],
['status success', { status: 'success', raw: '' }],
])('%s: após 500 ms notifica o modelo e fecha', async (_n, payload) => {
const { onOpenChange, onSuccess } = await open();
await startDownload('qwen:0.5b');
progress(payload);
expect(onOpenChange).not.toHaveBeenCalled();
await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));
expect(onSuccess).toHaveBeenCalledWith('qwen:0.5b');
});
it('concluído sem onSuccess: só fecha', async () => {
const { onOpenChange } = await open(undefined);
await startDownload();
progress({ status: 'success', raw: '' });
await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));
});
});
describe('ModelDownloadDialog: fechar e cancelar', () => {
it('cancelar sem download: fecha', async () => {
const { onOpenChange } = await open();
fireEvent.click(screen.getByRole('button', { name: 'Cancelar' }));
expect(onOpenChange).toHaveBeenCalledWith(false);
});
it.each([
[true, [[false]]],
[false, []],
])('cancelar durante download com confirmação %s', async (confirmed, calls) => {
vi.stubGlobal('confirm', vi.fn(() => confirmed)); // happy-dom não implementa window.confirm
const { onOpenChange } = await open();
await startDownload();
fireEvent.click(screen.getByRole('button', { name: 'Cancelar' }));
expect(onOpenChange.mock.calls).toEqual(calls);
});
it.each([
[true, [[false]]],
[false, []],
])('Esc durante download com confirmação %s', async (confirmed, calls) => {
vi.stubGlobal('confirm', vi.fn(() => confirmed));
const { onOpenChange } = await open();
await startDownload();
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
expect(onOpenChange.mock.calls).toEqual(calls);
});
it('Esc sem download: fecha sem perguntar', async () => {
const confirm = vi.fn(() => true);
vi.stubGlobal('confirm', confirm);
const { onOpenChange } = await open();
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
expect(onOpenChange).toHaveBeenCalledWith(false);
expect(confirm).not.toHaveBeenCalled();
});
});
describe('ModelDownloadDialog: instalar GGUF local', () => {
async function openLocal(onSuccess?: (name: string) => void) {
const r = await open(onSuccess);
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Instalar Local' }), { button: 0 });
await screen.findByRole('button', { name: 'Selecionar arquivo GGUF' });
return r;
}
it('seletor cancelado: não instala nada', async () => {
await openLocal();
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })));
expect(invokeMock).not.toHaveBeenCalledWith('install_gguf_model', expect.anything());
expect(screen.queryByText('Erro ao instalar modelo')).toBeNull();
});
it('arquivo .GGUF sem nome informado: usa o nome do arquivo sem extensão e fecha depois', async () => {
backend.pickFile = async () => 'C:\\modelos\\Phi-3.GGUF';
const { onOpenChange, onSuccess } = await openLocal(vi.fn());
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })));
expect(invokeMock).toHaveBeenCalledWith('install_gguf_model', { filePath: 'C:\\modelos\\Phi-3.GGUF', modelName: 'Phi-3' });
await waitFor(() => expect(onSuccess).toHaveBeenCalledWith('modelo-local'));
await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false), { timeout: 2000 });
});
it('nome informado: prevalece sobre o do arquivo; arquivo sem .gguf mantém o nome', async () => {
backend.pickFile = async () => '/home/u/modelo.bin';
await openLocal();
fireEvent.change(screen.getByLabelText('Nome do Modelo (opcional)'), { target: { value: ' meu-modelo ' } });
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })));
expect(invokeMock).toHaveBeenCalledWith('install_gguf_model', { filePath: '/home/u/modelo.bin', modelName: 'meu-modelo' });
});
it('caminho terminado em barra: usa "model" como nome', async () => {
backend.pickFile = async () => '/home/u/';
await openLocal();
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })));
expect(invokeMock).toHaveBeenCalledWith('install_gguf_model', { filePath: '/home/u/', modelName: 'model' });
});
it('instalação falha com Error: mostra a mensagem e volta ao seletor', async () => {
backend.pickFile = async () => '/m/a.gguf';
backend.installGguf = async () => { throw new Error('Ollama recusou o Modelfile'); };
await openLocal();
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })));
expect(await screen.findByText('Ollama recusou o Modelfile')).toBeTruthy();
expect(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })).toBeTruthy();
});
it('instalação falha sem mensagem: texto genérico', async () => {
backend.pickFile = async () => '/m/a.gguf';
backend.installGguf = async () => { throw 'falhou'; };
await openLocal();
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })));
expect(await screen.findByText('Erro ao instalar modelo GGUF')).toBeTruthy();
});
it('seletor nativo falha: avisa que não abriu', async () => {
backend.pickFile = async () => { throw new Error('sem portal xdg'); };
await openLocal();
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })));
expect(await screen.findByText('Erro ao abrir seletor de arquivo')).toBeTruthy();
});
});
+112
View File
@@ -0,0 +1,112 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { PromptGeneratorDialog } from './prompt-generator';
import type { LocalModel } from '@/hooks/use-local-models';
// Hooks que falam com o Ollama/Tauri viram fakes controlados pelo teste.
const state = vi.hoisted(() => ({
models: [] as LocalModel[],
loading: false,
generatePrompt: vi.fn(),
}));
vi.mock('@/hooks/use-local-models', () => ({ useLocalModels: () => ({ models: state.models, loading: state.loading }) }));
vi.mock('@/hooks/use-prompt-generator', () => ({
usePromptGenerator: () => ({ generatePrompt: state.generatePrompt, isGenerating: false }),
}));
const model = (name: string): LocalModel => ({ name, size: '1 GB', id: name, modified_at: '' });
function openWithGoal(defaultModel: string, onPromptGenerated = vi.fn()) {
render(<PromptGeneratorDialog defaultModel={defaultModel} onPromptGenerated={onPromptGenerated} />);
fireEvent.click(screen.getByTitle('Gerar com IA'));
fireEvent.change(screen.getByLabelText('Seu Objetivo'), { target: { value: 'assistente de Python' } });
return { onPromptGenerated, generate: screen.getByRole('button', { name: 'Gerar Prompt' }) };
}
beforeEach(() => {
state.models = [];
state.loading = false;
state.generatePrompt.mockReset();
state.generatePrompt.mockResolvedValue('PROMPT GERADO');
});
describe('PromptGeneratorDialog: escolha do modelo', () => {
it('modelo padrão instalado: gera com ele', async () => {
state.models = [model('mistral'), model('llama3')];
const { generate } = openWithGoal('llama3');
fireEvent.click(generate);
await waitFor(() => expect(state.generatePrompt).toHaveBeenCalledWith('assistente de Python', 'llama3'));
});
it('sem padrão e com o modelo preferido instalado: usa o preferido', async () => {
state.models = [model('mistral'), model('llama3.2-abliterate:3b')];
const { generate } = openWithGoal('');
fireEvent.click(generate);
await waitFor(() => expect(state.generatePrompt).toHaveBeenCalledWith('assistente de Python', 'llama3.2-abliterate:3b'));
});
it('sem padrão e sem o preferido: usa o primeiro modelo da lista', async () => {
state.models = [model('mistral'), model('qwen')];
const { generate } = openWithGoal(' ');
fireEvent.click(generate);
await waitFor(() => expect(state.generatePrompt).toHaveBeenCalledWith('assistente de Python', 'mistral'));
});
it('padrão não instalado, mesmo com o preferido presente: mantém o padrão', async () => {
state.models = [model('llama3.2-abliterate:3b')];
const { generate } = openWithGoal('removido');
fireEvent.click(generate);
await waitFor(() => expect(state.generatePrompt).toHaveBeenCalledWith('assistente de Python', 'removido'));
});
it('modelos carregando: não escolhe nenhum e o botão fica desativado', () => {
state.loading = true;
state.models = [model('mistral')];
const { generate } = openWithGoal('');
expect(screen.getByText('Carregando modelos...')).toBeTruthy();
expect(generate).toHaveProperty('disabled', true);
});
it('nenhum modelo instalado: avisa e o botão fica desativado', () => {
const { generate } = openWithGoal('');
expect(screen.getByText('Nenhum modelo disponível')).toBeTruthy();
expect(generate).toHaveProperty('disabled', true);
});
});
describe('PromptGeneratorDialog: geração', () => {
it('objetivo em branco: botão desativado', () => {
state.models = [model('mistral')];
render(<PromptGeneratorDialog defaultModel="mistral" onPromptGenerated={vi.fn()} />);
fireEvent.click(screen.getByTitle('Gerar com IA'));
expect(screen.getByRole('button', { name: 'Gerar Prompt' })).toHaveProperty('disabled', true);
});
it('sucesso: entrega o prompt e fecha o diálogo', async () => {
state.models = [model('mistral')];
const { generate, onPromptGenerated } = openWithGoal('mistral');
fireEvent.click(generate);
await waitFor(() => expect(onPromptGenerated).toHaveBeenCalledWith('PROMPT GERADO'));
await waitFor(() => expect(screen.queryByText('Gerador de Prompts')).toBeNull());
});
it('falha na geração: não entrega prompt e mantém o diálogo aberto com o objetivo', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
state.models = [model('mistral')];
state.generatePrompt.mockRejectedValue(new Error('ollama caiu'));
const { generate, onPromptGenerated } = openWithGoal('mistral');
fireEvent.click(generate);
await waitFor(() => expect(state.generatePrompt).toHaveBeenCalled());
expect(onPromptGenerated).not.toHaveBeenCalled();
expect((screen.getByLabelText('Seu Objetivo') as HTMLTextAreaElement).value).toBe('assistente de Python');
});
it('cancelar: fecha e limpa o objetivo', async () => {
state.models = [model('mistral')];
openWithGoal('mistral');
fireEvent.click(screen.getByRole('button', { name: 'Cancelar' }));
await waitFor(() => expect(screen.queryByText('Gerador de Prompts')).toBeNull());
fireEvent.click(screen.getByTitle('Gerar com IA'));
expect((screen.getByLabelText('Seu Objetivo') as HTMLTextAreaElement).value).toBe('');
});
});
+1 -1
View File
@@ -119,7 +119,7 @@ export function PromptGeneratorDialog({ defaultModel, onPromptGenerated }: Promp
</Tooltip>
<SelectContent className="max-w-[90vw]">
{models.length === 0 ? (
<SelectItem value="" disabled>Nenhum modelo disponível</SelectItem>
<SelectItem value="__sem-modelos__" disabled>Nenhum modelo disponível</SelectItem>
) : (
models.map(m => (
<Tooltip key={m.name}>
+172
View File
@@ -0,0 +1,172 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, within } from '@testing-library/react';
import { SidebarList } from './sidebar-list';
import type { SessionSummary } from '@/hooks/use-chat-storage';
// Destaque visual do item selecionado e tooltip de título longo ficam mapeados sem teste (CSS/hover).
const NOW = new Date('2026-06-15T12:00:00');
function session(id: string, extra: Partial<SessionSummary> = {}): SessionSummary {
return { id, title: `Conversa ${id}`, emoji: '🦀', updated_at: NOW.toISOString(), preview: '', platform: 'Linux', ...extra };
}
function renderList(props: Partial<Parameters<typeof SidebarList>[0]> = {}) {
const handlers = { onSelectSession: vi.fn(), onDeleteSession: vi.fn(), onNewChat: vi.fn(), onSearch: vi.fn(), onNavigateMatch: vi.fn() };
render(<SidebarList sessions={[]} currentSessionId={null} {...handlers} {...props} />);
return handlers;
}
const card = (title: string) => screen.getByRole('heading', { name: title }).closest('[role="button"]') as HTMLElement;
beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] });
vi.setSystemTime(NOW);
});
afterEach(() => {
vi.useRealTimers();
});
describe('SidebarList: lista', () => {
it('sem conversas e sem busca: convida a começar', () => {
renderList();
expect(screen.getByText('Nenhuma conversa salva')).toBeTruthy();
});
it('sem conversas durante busca: avisa que nada foi encontrado', () => {
renderList({ searchQuery: 'rust' });
expect(screen.getByText('Nenhuma conversa encontrada')).toBeTruthy();
});
it('clique, Enter e espaço no card: selecionam a conversa; outra tecla não', () => {
const h = renderList({ sessions: [session('a')] });
fireEvent.click(card('Conversa a'));
fireEvent.keyDown(card('Conversa a'), { key: 'Enter' });
fireEvent.keyDown(card('Conversa a'), { key: ' ' });
fireEvent.keyDown(card('Conversa a'), { key: 'a' });
expect(h.onSelectSession.mock.calls).toEqual([['a'], ['a'], ['a']]);
});
it('excluir: chama onDeleteSession sem selecionar a conversa', () => {
const h = renderList({ sessions: [session('a')] });
fireEvent.click(screen.getByRole('button', { name: 'Deletar conversa "Conversa a"' }));
expect(h.onDeleteSession).toHaveBeenCalledWith('a');
expect(h.onSelectSession).not.toHaveBeenCalled();
});
it('sem emoji: usa 💬', () => {
renderList({ sessions: [session('a', { emoji: '' })] });
expect(within(card('Conversa a')).getByText('💬')).toBeTruthy();
});
it.each([
[1, '1 ocorrência'],
[3, '3 ocorrências'],
])('busca com %i ocorrência(s): mostra "%s"', (count, text) => {
renderList({ sessions: [session('a', { match_count: count })], searchQuery: 'rust' });
expect(screen.getByText(text)).toBeTruthy();
});
it('ocorrências sem busca ativa: não mostra contagem', () => {
renderList({ sessions: [session('a', { match_count: 2 })] });
expect(screen.queryByText(/ocorrências/)).toBeNull();
});
it('selecionada com ocorrências: navegação anterior/próxima sem reselecionar', () => {
const h = renderList({ sessions: [session('a', { match_count: 2 })], searchQuery: 'rust', currentSessionId: 'a' });
fireEvent.click(screen.getByRole('button', { name: 'Ocorrência anterior' }));
fireEvent.click(screen.getByRole('button', { name: 'Próxima ocorrência' }));
expect(h.onNavigateMatch.mock.calls).toEqual([['a', 'prev'], ['a', 'next']]);
expect(h.onSelectSession).not.toHaveBeenCalled();
});
it.each([
['não selecionada', { currentSessionId: 'b' }],
['sem ocorrências', { currentSessionId: 'a', sessions: [session('a', { match_count: 0 })] }],
['sem onNavigateMatch', { currentSessionId: 'a', onNavigateMatch: undefined }],
])('%s: sem botões de navegação', (_n, extra) => {
renderList({ sessions: [session('a', { match_count: 2 })], searchQuery: 'rust', ...extra });
expect(screen.queryByRole('button', { name: 'Próxima ocorrência' })).toBeNull();
});
it.each([
['hoje', '2026-06-15T09:30:00', '09:30'],
['ontem', '2026-06-14T09:00:00', 'Ontem'],
['há 3 dias', '2026-06-12T09:00:00', 'sex.'],
['há 2 meses', '2026-04-10T09:00:00', '10/04'],
['há 2 anos', '2024-04-10T09:00:00', '10/04/2024'],
])('data %s: "%s"', (_n, iso, text) => {
renderList({ sessions: [session('a', { updated_at: new Date(iso).toISOString() })] });
expect(within(card('Conversa a')).getByText(text)).toBeTruthy();
});
});
describe('SidebarList: busca', () => {
const field = () => screen.getByPlaceholderText('Buscar conversas...');
it('digitar 2+ caracteres: busca após 300 ms com o texto aparado', () => {
const h = renderList();
h.onSearch.mockClear();
fireEvent.change(field(), { target: { value: ' ru ' } });
act(() => vi.advanceTimersByTime(299));
expect(h.onSearch).not.toHaveBeenCalled();
act(() => vi.advanceTimersByTime(1));
expect(h.onSearch).toHaveBeenCalledWith('ru');
});
it('digitar só 1 caractere: não busca', () => {
const h = renderList();
h.onSearch.mockClear();
fireEvent.change(field(), { target: { value: 'r' } });
act(() => vi.advanceTimersByTime(1000));
expect(h.onSearch).not.toHaveBeenCalled();
});
it('digitação rápida: só a última busca dispara', () => {
const h = renderList();
h.onSearch.mockClear();
fireEvent.change(field(), { target: { value: 'ru' } });
act(() => vi.advanceTimersByTime(200));
fireEvent.change(field(), { target: { value: 'rust' } });
act(() => vi.advanceTimersByTime(300));
expect(h.onSearch.mock.calls).toEqual([['rust']]);
});
it('apagar o texto: limpa a busca na hora', () => {
const h = renderList();
fireEvent.change(field(), { target: { value: 'rust' } });
h.onSearch.mockClear();
fireEvent.change(field(), { target: { value: '' } });
expect(h.onSearch).toHaveBeenCalledWith('');
});
it('botão limpar: esvazia o campo e a busca', () => {
const h = renderList();
fireEvent.change(field(), { target: { value: 'rust' } });
h.onSearch.mockClear();
fireEvent.click(screen.getByRole('button', { name: 'Limpar busca' }));
expect((field() as HTMLInputElement).value).toBe('');
expect(h.onSearch).toHaveBeenCalledWith('');
});
it('buscando: esconde o botão limpar', () => {
renderList({ isSearching: true });
fireEvent.change(field(), { target: { value: 'rust' } });
expect(screen.queryByRole('button', { name: 'Limpar busca' })).toBeNull();
});
it('sem onSearch: digitar e limpar não quebram a lista', () => {
renderList({ onSearch: undefined, sessions: [session('a')] });
fireEvent.change(field(), { target: { value: 'rust' } });
act(() => vi.advanceTimersByTime(300));
fireEvent.click(screen.getByRole('button', { name: 'Limpar busca' }));
expect(screen.getByRole('heading', { name: 'Conversa a' })).toBeTruthy();
});
it('nova conversa: chama onNewChat', () => {
const h = renderList();
fireEvent.click(screen.getByRole('button', { name: 'Nova Conversa' }));
expect(h.onNewChat).toHaveBeenCalled();
});
});
+134
View File
@@ -0,0 +1,134 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { ModelSelector } from './model-selector';
// Comandos Tauri (pull_model etc.) e o evento download-progress viram fakes.
const { invokeMock, emit } = vi.hoisted(() => {
const listeners: Record<string, (event: { payload: string }) => void> = {};
return {
invokeMock: vi.fn(),
emit: Object.assign((payload: unknown) => listeners['download-progress']({ payload: typeof payload === 'string' ? payload : JSON.stringify(payload) }), { listeners }),
};
});
vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));
vi.mock('@tauri-apps/api/event', () => ({
listen: vi.fn(async (name: string, cb: (event: { payload: string }) => void) => {
emit.listeners[name] = cb;
return () => {};
}),
}));
let installed = false;
let pull: () => Promise<void> = () => Promise.withResolvers<void>().promise; // download em andamento
beforeEach(() => {
installed = false;
pull = () => Promise.withResolvers<void>().promise;
invokeMock.mockReset();
invokeMock.mockImplementation(async (cmd: string) => {
if (cmd === 'check_if_model_installed') return installed;
if (cmd === 'pull_model') return pull();
throw new Error(`comando inesperado: ${cmd}`);
});
vi.spyOn(console, 'error').mockImplementation(() => {});
});
async function startDownload(modelId = 'llama3.2:3b') {
const onComplete = vi.fn();
render(<ModelSelector recommendation={{ modelId, reason: 'cabe na sua RAM', minRam: 8 }} onComplete={onComplete} />);
await waitFor(() => expect(emit.listeners['download-progress']).toBeDefined());
fireEvent.click(screen.getByRole('button', { name: /Baixar e Instalar/ }));
await screen.findByText('Iniciando download...');
return onComplete;
}
describe('ModelSelector', () => {
it('modelo já instalado: oferece ir para o chat e chama onComplete', async () => {
installed = true;
const onComplete = vi.fn();
render(<ModelSelector recommendation={{ modelId: 'llama3.2:1b', reason: 'r', minRam: 4 }} onComplete={onComplete} />);
fireEvent.click(await screen.findByRole('button', { name: /Ir para o Chat/ }));
expect(onComplete).toHaveBeenCalled();
});
it('recomendação fora da lista: botão usa o tamanho do primeiro modelo', async () => {
render(<ModelSelector recommendation={{ modelId: 'desconhecido', reason: 'r', minRam: 4 }} onComplete={vi.fn()} />);
expect(await screen.findByRole('button', { name: 'Baixar e Instalar (1.3GB)' })).toBeTruthy();
});
it('pull_model falha: volta ao botão de baixar habilitado e zera o progresso', async () => {
const { promise, reject: fail } = Promise.withResolvers<void>();
pull = () => promise;
await startDownload();
await act(async () => fail(new Error('sem rede')));
const button = await screen.findByRole('button', { name: /Baixar e Instalar/ });
expect(button).toHaveProperty('disabled', false);
expect(screen.queryByText('0%')).toBeNull();
});
});
describe('ModelSelector: evento download-progress', () => {
it.each([
['pulling', 'Baixando modelo...'],
['verifying', 'Verificando...'],
['writing', 'Salvando...'],
['outro', 'Baixando...'],
])('status %s sem percent: texto "%s"', async (status, text) => {
await startDownload();
act(() => emit({ status, raw: '' }));
expect(screen.getByText(text, { selector: 'span' })).toBeTruthy();
});
it('percent informado: mostra o percentual e tamanho/velocidade', async () => {
await startDownload();
act(() => emit({ status: 'pulling', percent: 42, downloaded: '1 GB', total: '2 GB', speed: '5 MB/s', raw: '' }));
expect(screen.getByText('42%')).toBeTruthy();
expect(screen.getByText('1 GB / 2 GB')).toBeTruthy();
expect(screen.getByText('5 MB/s')).toBeTruthy();
});
it('pulling sem percent: progresso sobe para no mínimo 10%', async () => {
await startDownload();
act(() => emit({ status: 'pulling', raw: '' }));
expect(screen.getByText('10%')).toBeTruthy();
});
it('pulling sem percent depois de 42%: não regride', async () => {
await startDownload();
act(() => emit({ status: 'pulling', percent: 42, raw: '' }));
act(() => emit({ status: 'pulling', raw: '' }));
expect(screen.getByText('42%')).toBeTruthy();
});
it('verifying sem percent: 90%; writing sem percent: 95%', async () => {
await startDownload();
act(() => emit({ status: 'verifying', raw: '' }));
expect(screen.getByText('90%')).toBeTruthy();
act(() => emit({ status: 'writing', raw: '' }));
expect(screen.getByText('95%')).toBeTruthy();
});
it('payload que não é JSON: trata como download em andamento sem mudar o progresso', async () => {
await startDownload();
act(() => emit('pulling manifest'));
expect(screen.getByText('Baixando...', { selector: 'span' })).toBeTruthy();
expect(screen.getByText('0%')).toBeTruthy();
});
it('downloaded sem total: mostra só o baixado', async () => {
await startDownload();
act(() => emit({ status: 'pulling', percent: 5, downloaded: '300 MB', raw: '' }));
expect(screen.getByText('300 MB')).toBeTruthy();
});
it.each([
['percent 100', { status: 'pulling', percent: 100, raw: '' }],
['status success', { status: 'success', raw: '' }],
])('%s: após 500 ms marca instalado e oferece ir para o chat', async (_n, payload) => {
await startDownload();
installed = true;
act(() => emit(payload));
expect(screen.queryByRole('button', { name: /Ir para o Chat/ })).toBeNull();
expect(await screen.findByRole('button', { name: /Ir para o Chat/ }, { timeout: 2000 })).toBeTruthy();
});
});
+276
View File
@@ -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([]);
});
});
+265
View File
@@ -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({});
});
});
+73
View File
@@ -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' });
});
});
+68
View File
@@ -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');
});
});
+61
View File
@@ -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);
});
});
+74
View File
@@ -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?');
});
});
+134
View File
@@ -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);
});
});
+109
View File
@@ -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([]);
});
});
+164
View File
@@ -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');
});
});
+1 -1
View File
@@ -206,7 +206,7 @@ export async function analyzeQueryContext(
complexity: analysis.complexity || 'moderate',
};
chatLog.success(`[ContextualAnalysis] Contexto extraído: ${context.intent}, ${context.entities.length} entidades, ${context.topics.length} tópicos`);
chatLog.info(`[ContextualAnalysis] Contexto extraído: ${context.intent}, ${context.entities.length} entidades, ${context.topics.length} tópicos`);
return context;
} catch (error) {
+68
View File
@@ -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);
});
});
+124
View File
@@ -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']);
});
});
+1 -1
View File
@@ -176,7 +176,7 @@ export async function enrichQueries(
result.expanded.length +
result.contextual.length;
chatLog.success(
chatLog.info(
`[QueryEnricher] ${totalQueries} queries geradas: ` +
`${result.literal.length} literal, ${result.semantic.length} semântica, ` +
`${result.related.length} relacionadas, ${result.expanded.length} expandidas, ` +
+61
View File
@@ -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]);
});
});
+127
View File
@@ -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);
});
});
+7 -7
View File
@@ -97,7 +97,7 @@ export function calculateSemanticSimilarity(
if (context.keywords.length > 0) {
let keywordMatches = 0;
for (const keyword of context.keywords) {
const keywordLower = keyword.toLowerCase();
const keywordLower = normalizeText(keyword);
if (normalizedChunk.includes(keywordLower)) {
keywordMatches++;
}
@@ -111,7 +111,7 @@ export function calculateSemanticSimilarity(
if (context.entities.length > 0) {
let entityMatches = 0;
for (const entity of context.entities) {
const entityLower = entity.value.toLowerCase();
const entityLower = normalizeText(entity.value);
// Buscar entidade completa (case-insensitive)
if (normalizedChunk.includes(entityLower)) {
entityMatches += entity.confidence; // Ponderar por confiança
@@ -126,7 +126,7 @@ export function calculateSemanticSimilarity(
if (context.topics.length > 0) {
let topicMatches = 0;
for (const topic of context.topics) {
const topicLower = topic.toLowerCase();
const topicLower = normalizeText(topic);
// Verificar se tópico aparece no chunk (pode ser parcial)
const topicWords = topicLower.split(/\s+/);
const matches = topicWords.filter(word =>
@@ -147,7 +147,7 @@ export function calculateSemanticSimilarity(
if (context.synonyms.length > 0) {
let synonymMatches = 0;
for (const synonym of context.synonyms) {
const synonymLower = synonym.toLowerCase();
const synonymLower = normalizeText(synonym);
if (normalizedChunk.includes(synonymLower)) {
synonymMatches++;
}
@@ -163,18 +163,18 @@ export function calculateSemanticSimilarity(
// Verificar se contexto temporal/geográfico aparece no chunk
let contextualScore = 0;
if (context.temporalContext?.period) {
if (normalizedChunk.includes(context.temporalContext.period)) {
if (normalizedChunk.includes(normalizeText(context.temporalContext.period))) {
contextualScore += 0.5;
}
}
if (context.temporalContext?.relative) {
const relativeTerms = ['recente', 'atual', 'novo', 'último', 'atualizado'];
const relativeTerms = ['recente', 'atual', 'novo', 'ultimo', 'atualizado'];
if (relativeTerms.some(term => normalizedChunk.includes(term))) {
contextualScore += 0.3;
}
}
if (context.geographicContext?.location) {
const locationLower = context.geographicContext.location.toLowerCase();
const locationLower = normalizeText(context.geographicContext.location);
if (normalizedChunk.includes(locationLower)) {
contextualScore += 0.5;
}
+184
View File
@@ -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 });
});
});
+5 -4
View File
@@ -363,16 +363,17 @@ export async function executeProgressiveSearch(
const timeoutPromise = new Promise<QueryResult[]>((_, reject) => {
setTimeout(() => reject(new Error(`Round ${round} timeout após ${actualRoundTimeout}ms`)), actualRoundTimeout);
});
// Guarda as queries que terminam antes do timeout; allSettled esperaria as travadas.
const completedResults: QueryResult[] = [];
queryPromises.forEach(p => p.then(r => completedResults.push(r)));
let queryResults: QueryResult[];
try {
queryResults = await Promise.race([roundPromise, timeoutPromise]);
} catch (error) {
chatLog.warn(`[Round ${round}] Timeout do round após ${actualRoundTimeout}ms, usando resultados parciais`);
// Tentar obter resultados parciais das promises que já completaram
queryResults = await Promise.allSettled(queryPromises).then(results =>
results.map(r => r.status === 'fulfilled' ? r.value : { query: '', results: [] })
);
// Resultados parciais: só as queries que já completaram
queryResults = [...completedResults];
}
// Agregar resultados de todas as queries do round
+6 -1
View File
@@ -7,6 +7,7 @@
"build": "next build",
"start": "next start",
"lint": "eslint",
"test": "vitest run",
"generate-changelog": "node scripts/generate-changelog.js",
"bump-version": "node scripts/bump-version.js"
},
@@ -47,14 +48,18 @@
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@tauri-apps/cli": "^2.9.4",
"@testing-library/dom": "^10.4.2",
"@testing-library/react": "^16.3.3",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.0.3",
"happy-dom": "^21.0.4",
"raw-loader": "^4.0.2",
"tailwindcss": "^4",
"tw-animate-css": "^1.4.0",
"typescript": "^5"
"typescript": "^5",
"vitest": "^5.1.0"
}
}
+985 -141
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -1,3 +1,6 @@
packages:
- '.'
onlyBuiltDependencies:
- sharp
- unrs-resolver
+166
View File
@@ -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);
});
});
+17
View File
@@ -0,0 +1,17 @@
// 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', '{app,components}/**/*.test.tsx'],
environment: 'happy-dom', // localStorage para o persist do zustand e DOM para renderHook
setupFiles: ['./vitest.setup.ts'],
restoreMocks: true,
unstubGlobals: true,
},
});
+5
View File
@@ -0,0 +1,5 @@
import { afterEach } from 'vitest';
import { cleanup } from '@testing-library/react';
// Sem `globals: true` o Testing Library não registra o cleanup sozinho.
afterEach(cleanup);