Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07b0eaadca |
No files matched your search
@@ -0,0 +1,82 @@
|
|||||||
|
# OllaHub — sistema visual
|
||||||
|
Derivado de `specs/DESIGN-familia.md` (família visual dos apps de IA local, 2026-11-16). Em caso de dúvida, a família manda.
|
||||||
|
|
||||||
|
Leitura: refino · Operate · web (Next 16 + Tailwind v4 + shadcn). Identidade, comportamento, copy e layout continuam os mesmos: muda o sistema, não a estrutura das telas.
|
||||||
|
|
||||||
|
## Princípios
|
||||||
|
1. Ferramenta local, sem cerimônia: o conteúdo (conversa, modelo) domina e o cromo some.
|
||||||
|
2. Acento num lugar só por tela: ação primária, foco, item ativo e o indicador de "gerando". Nunca em fundo grande, gradiente ou decoração.
|
||||||
|
3. Dados técnicos (modelo, endpoint, porta, tokens, tempo) em mono; todo o resto em sans.
|
||||||
|
|
||||||
|
## Cor (OKLCH)
|
||||||
|
Neutros com leve tom frio, matiz 265.
|
||||||
|
|
||||||
|
| Papel | Escuro (padrão) | Claro |
|
||||||
|
|---|---|---|
|
||||||
|
| `bg` | oklch(0.16 0.008 265) | oklch(0.99 0.003 265) |
|
||||||
|
| `surface` | oklch(0.20 0.009 265) | oklch(0.97 0.004 265) |
|
||||||
|
| `elevated` (menu, modal) | oklch(0.24 0.010 265) | oklch(1 0 0) |
|
||||||
|
| `hover` | oklch(0.28 0.010 265) | oklch(0.94 0.005 265) |
|
||||||
|
| `border` | oklch(0.32 0.010 265) | oklch(0.90 0.006 265) |
|
||||||
|
| `text` | oklch(0.96 0.004 265) | oklch(0.20 0.010 265) |
|
||||||
|
| `text-2` | oklch(0.76 0.008 265) | oklch(0.42 0.010 265) |
|
||||||
|
| `text-3` (rótulo, meta) | oklch(0.64 0.010 265) | oklch(0.54 0.010 265) |
|
||||||
|
| `success` | oklch(0.74 0.15 150) | oklch(0.52 0.14 150) |
|
||||||
|
| `warning` | oklch(0.82 0.15 85) | oklch(0.60 0.13 75) |
|
||||||
|
| `danger` | oklch(0.68 0.19 25) | oklch(0.55 0.20 25) |
|
||||||
|
|
||||||
|
Acento (`accent-fg` = texto sobre o acento; `accent-soft` = acento a 14% sobre `bg`, misturado em oklab para não desviar o matiz, usado em seleção e item ativo):
|
||||||
|
|
||||||
|
| `accent` escuro | `accent` claro | `accent-fg` | Origem |
|
||||||
|
|---|---|---|---|
|
||||||
|
| oklch(0.80 0.16 70) âmbar | oklch(0.62 0.15 60) | oklch(0.20 0.04 60) | o #FE9A00 do OllaHubBackend |
|
||||||
|
|
||||||
|
Contraste: `text-3` sobre `bg` e `surface` ≥ 4,5:1; `accent-fg` sobre `accent` ≥ 4,5:1.
|
||||||
|
|
||||||
|
## Tipografia
|
||||||
|
- Geist e Geist Mono, empacotadas localmente pelo pacote `geist` (usa `next/font/local`; o app roda offline). Fallback: system-ui / ui-monospace.
|
||||||
|
- Escala 1,2 com base 14 px: `text-xs` 12 · `text-sm` 14 · `text-lg` 17 · `text-xl` 20 · `text-2xl` 24 · `text-3xl` 29. Corpo 14; mensagem do usuário 17.
|
||||||
|
- Pesos: 400 corpo, 500 rótulo de controle, 600 título. Sem caixa alta em rótulo. Entrelinha 1,5 no corpo, 1,25 nos títulos. Mensagens até 72ch.
|
||||||
|
|
||||||
|
## Espaço, raio, sombra
|
||||||
|
- Espaçamento só da escala 4 · 8 · 12 · 16 · 20 · 24 · 32 · 40 · 48 · 64.
|
||||||
|
- Raio: `rounded-sm` 6 (chip, badge), `rounded-md` 8 (botão, input), `rounded-lg`/`rounded-xl` 12 (painel, card de mensagem, diálogo), `rounded-full` só em avatar, ponto e pill de status.
|
||||||
|
- Sombra só no que flutua (menu, popover, modal, toast): `shadow-float` = `0 1px 2px oklch(0.10 0.01 265 / 0.30), 0 8px 24px oklch(0.10 0.01 265 / 0.35)`. Cards e painéis usam borda.
|
||||||
|
|
||||||
|
## Estados
|
||||||
|
hover (`bg-hover`), foco visível (outline de 2 px em `accent` com 2 px de offset), ativo/selecionado (`bg-accent-soft` + `text-foreground`), desabilitado (opacidade 0,45, sem hover), carregando/gerando (spinner/barra em `text-primary`/`bg-primary`, `prefers-reduced-motion` respeitado), vazio (frase com o próximo passo), erro (`text-destructive` com causa e ação).
|
||||||
|
|
||||||
|
## Movimento
|
||||||
|
150–200 ms, ease-out (`--ease-out`), só opacidade e transform. Sem animação decorativa, sem `transition-all`, sem transição de largura.
|
||||||
|
|
||||||
|
## Fora
|
||||||
|
Gradiente decorativo, glow, glassmorphism (`backdrop-blur`), sombra em card, emoji como ícone, o mesmo raio em tudo, cinza neutro puro, cores de paleta fixas (`green-500`, `blue-500`…).
|
||||||
|
|
||||||
|
## Mapa de tokens (migração shadcn → família)
|
||||||
|
Os papéis da família são variáveis CSS em `app/globals.css`; os nomes do shadcn apontam para eles, sem alias extra.
|
||||||
|
|
||||||
|
| shadcn / antigo | Papel da família |
|
||||||
|
|---|---|
|
||||||
|
| `background` | `bg` |
|
||||||
|
| `foreground` | `text` |
|
||||||
|
| `card` | `surface` |
|
||||||
|
| `popover` | `elevated` |
|
||||||
|
| `primary` | `accent` |
|
||||||
|
| `primary-foreground` | `accent-fg` |
|
||||||
|
| `secondary` | `hover` |
|
||||||
|
| `muted` | `surface` |
|
||||||
|
| `muted-foreground` | `text-3` |
|
||||||
|
| `destructive` | `danger` |
|
||||||
|
| `border`, `input` | `border` |
|
||||||
|
| `ring` | `accent` |
|
||||||
|
| `accent` antigo (fundo de hover do shadcn) | `hover` (`bg-hover`); `accent` agora é o acento da família |
|
||||||
|
| `accent-foreground` | removido; usar `text-foreground` |
|
||||||
|
| `sidebar-*` | removidos; a lista usa `surface`/`border`/`hover`/`text` |
|
||||||
|
| `chart-*`, `message-*` | removidos (exceto `message-high-contrast`) |
|
||||||
|
| `--radius` | removido; `radius-sm/md/lg/xl` = 6/8/12/12 (lg era 10, xl era 14) |
|
||||||
|
| tamanhos de texto | ajustados à escala 12/14/17/20/24/29; `text-[10px]` → `text-xs` |
|
||||||
|
| fonte | `next/font/google` → pacote `geist` (local) |
|
||||||
|
| `green/red/yellow/orange/blue-*` | `success` / `danger` / `warning` / neutro ou `accent-soft` |
|
||||||
|
| `bg-black/50` em overlays | `bg-scrim` |
|
||||||
|
|
||||||
|
Utilitários novos do tema: `bg-surface`, `bg-elevated`, `bg-hover`, `text-text-2`, `text-success`, `text-warning`, `bg-accent-soft`, `text-accent-fg`, `bg-scrim`, `shadow-float`.
|
||||||
+35
-33
@@ -1051,12 +1051,12 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
defaultSize={4}
|
defaultSize={4}
|
||||||
minSize={4}
|
minSize={4}
|
||||||
maxSize={4}
|
maxSize={4}
|
||||||
className="border-r flex flex-col items-center py-4 gap-4 bg-muted/20 w-[60px] min-w-[60px] max-w-[60px] flex-shrink-0"
|
className="border-r flex flex-col items-center py-4 gap-2 bg-surface w-[60px] min-w-[60px] max-w-[60px] flex-shrink-0"
|
||||||
>
|
>
|
||||||
<Button variant="ghost" size="icon" className="rounded-lg bg-primary/10 text-primary">
|
<Button variant="ghost" size="icon" className="bg-accent-soft text-foreground hover:bg-accent-soft" aria-label="Chat" aria-current="page">
|
||||||
<MessageSquare className="w-5 h-5" />
|
<MessageSquare className="w-5 h-5" />
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="ghost" size="icon" className="rounded-lg text-muted-foreground hover:text-foreground">
|
<Button variant="ghost" size="icon" className="text-muted-foreground hover:text-foreground" aria-label="Servidor">
|
||||||
<Server className="w-5 h-5" />
|
<Server className="w-5 h-5" />
|
||||||
</Button>
|
</Button>
|
||||||
<div className="flex-1" />
|
<div className="flex-1" />
|
||||||
@@ -1064,14 +1064,16 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
|
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
|
||||||
className="rounded-lg text-muted-foreground hover:text-foreground"
|
className="text-muted-foreground hover:text-foreground"
|
||||||
|
aria-label="Alternar tema"
|
||||||
>
|
>
|
||||||
{mounted ? (theme === "dark" ? <Sun className="w-5 h-5" /> : <Moon className="w-5 h-5" />) : null}
|
{mounted ? (theme === "dark" ? <Sun className="w-5 h-5" /> : <Moon className="w-5 h-5" />) : null}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
className="rounded-lg text-muted-foreground hover:text-foreground"
|
className="text-muted-foreground hover:text-foreground"
|
||||||
|
aria-label="Configurações"
|
||||||
onClick={() => router.push('/settings')}
|
onClick={() => router.push('/settings')}
|
||||||
>
|
>
|
||||||
<Settings className="w-5 h-5" />
|
<Settings className="w-5 h-5" />
|
||||||
@@ -1119,10 +1121,10 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
<ResizableHandle className="hidden md:block" />
|
<ResizableHandle className="hidden md:block" />
|
||||||
|
|
||||||
{/* Main Chat Area */}
|
{/* Main Chat Area */}
|
||||||
<ResizablePanel defaultSize={100} minSize={75} className="transition-all duration-300">
|
<ResizablePanel defaultSize={100} minSize={75}>
|
||||||
<div className="h-full flex flex-col">
|
<div className="h-full flex flex-col">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="h-14 border-b flex items-center px-3 sm:px-4 justify-between bg-background/50 backdrop-blur gap-2 sm:gap-4 flex-shrink-0" style={{ paddingLeft: 'clamp(12px, 2vw, 16px)', paddingRight: 'clamp(12px, 2vw, 16px)' }}>
|
<div className="h-14 border-b flex items-center px-3 sm:px-4 justify-between bg-background gap-2 sm:gap-4 flex-shrink-0">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -1137,13 +1139,13 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
<PanelLeftClose className="w-4 h-4" />
|
<PanelLeftClose className="w-4 h-4" />
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
<div className="font-semibold flex items-center gap-2 text-sm sm:text-base">
|
<div className="font-semibold flex items-center gap-2 text-sm">
|
||||||
<span className="hidden sm:inline">Chat</span>
|
<span className="hidden sm:inline">Chat</span>
|
||||||
{isGeneratingTitle && <Loader2 className="w-3 h-3 animate-spin text-muted-foreground" />}
|
{isGeneratingTitle && <Loader2 className="w-3 h-3 animate-spin text-primary" />}
|
||||||
{isDownloading && (
|
{isDownloading && (
|
||||||
<span className="text-xs text-muted-foreground flex items-center gap-1">
|
<span className="text-xs text-muted-foreground flex items-center gap-1">
|
||||||
<Loader2 className="w-3 h-3 animate-spin" />
|
<Loader2 className="w-3 h-3 animate-spin text-primary" />
|
||||||
{progress}
|
<span className="font-mono">{progress}</span>
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -1197,7 +1199,7 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
)}
|
)}
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
))}
|
))}
|
||||||
<SelectItem value="__add_model__" className="text-primary font-medium">
|
<SelectItem value="__add_model__" className="font-medium">
|
||||||
<span className="flex items-center gap-2">
|
<span className="flex items-center gap-2">
|
||||||
<Plus className="h-4 w-4" />
|
<Plus className="h-4 w-4" />
|
||||||
Adicionar modelo...
|
Adicionar modelo...
|
||||||
@@ -1221,7 +1223,7 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
className="flex-1 overflow-y-auto scroll-smooth w-full min-h-0"
|
className="flex-1 overflow-y-auto scroll-smooth w-full min-h-0"
|
||||||
onScroll={handleScroll}
|
onScroll={handleScroll}
|
||||||
>
|
>
|
||||||
<div className="max-w-3xl mx-auto w-full px-3 sm:px-4 md:px-6 pt-4 sm:pt-6 pb-4 transition-all duration-300" style={{ paddingLeft: 'clamp(12px, 4vw, 24px)', paddingRight: 'clamp(12px, 4vw, 24px)' }}>
|
<div className="max-w-3xl mx-auto w-full px-3 sm:px-4 md:px-6 pt-4 sm:pt-6 pb-4">
|
||||||
{/* Indicador de carregamento de mensagens antigas */}
|
{/* Indicador de carregamento de mensagens antigas */}
|
||||||
{paginationState.isLoadingMore && (
|
{paginationState.isLoadingMore && (
|
||||||
<div className="flex items-center justify-center py-4 mb-4">
|
<div className="flex items-center justify-center py-4 mb-4">
|
||||||
@@ -1233,19 +1235,19 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
{/* Indicador de que há mais mensagens para carregar */}
|
{/* Indicador de que há mais mensagens para carregar */}
|
||||||
{paginationState.hasMore && !paginationState.isLoadingMore && messages.length > 0 && (
|
{paginationState.hasMore && !paginationState.isLoadingMore && messages.length > 0 && (
|
||||||
<div className="flex items-center justify-center py-2 mb-4">
|
<div className="flex items-center justify-center py-2 mb-4">
|
||||||
<span className="text-xs text-muted-foreground/60">
|
<span className="text-xs text-muted-foreground">
|
||||||
Role para cima para ver mensagens anteriores ({paginationState.totalCount - messages.length} restantes)
|
Role para cima para ver mensagens anteriores ({paginationState.totalCount - messages.length} restantes)
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{messages.length === 0 ? (
|
{messages.length === 0 ? (
|
||||||
<div className="min-h-[50vh] flex flex-col items-center justify-center text-muted-foreground space-y-6">
|
<div className="min-h-[50vh] flex flex-col items-center justify-center text-muted-foreground gap-6">
|
||||||
<div className="p-6 rounded-2xl bg-muted/30 ring-1 ring-border/50 shadow-sm">
|
<div className="p-4 rounded-lg border bg-surface">
|
||||||
<MessageSquare className="w-8 h-8 text-primary/60" />
|
<MessageSquare className="w-8 h-8 text-muted-foreground" />
|
||||||
</div>
|
</div>
|
||||||
<div className="text-center space-y-2">
|
<div className="text-center space-y-2">
|
||||||
<p className="text-lg font-medium text-primary/80">Como posso ajudar você hoje?</p>
|
<p className="text-lg font-medium text-foreground">Como posso ajudar você hoje?</p>
|
||||||
<p className="text-sm text-muted-foreground">Selecione um modelo e comece uma conversa.</p>
|
<p className="text-sm text-muted-foreground">Selecione um modelo e comece uma conversa.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -1392,7 +1394,7 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
|
|
||||||
{/* Debug Info (Moved inside scroll) */}
|
{/* Debug Info (Moved inside scroll) */}
|
||||||
{(deepResearch.state.logs.length > 0 || lastWebContext) && (
|
{(deepResearch.state.logs.length > 0 || lastWebContext) && (
|
||||||
<div className="mt-12 pt-6 border-t border-dashed border-muted/50 opacity-70 hover:opacity-100 transition-opacity">
|
<div className="mt-12 pt-6 border-t border-dashed border-border">
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{/* Process Log Toggle */}
|
{/* Process Log Toggle */}
|
||||||
{deepResearch.state.logs.length > 0 && (
|
{deepResearch.state.logs.length > 0 && (
|
||||||
@@ -1400,22 +1402,22 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setShowProcessDebug((prev) => !prev)}
|
onClick={() => setShowProcessDebug((prev) => !prev)}
|
||||||
className="flex items-center gap-2 text-xs font-medium text-muted-foreground hover:text-primary transition-colors"
|
className="flex items-center gap-2 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors duration-150"
|
||||||
>
|
>
|
||||||
<ScrollText className="w-3 h-3" />
|
<ScrollText className="w-3 h-3" />
|
||||||
Debug: Processo de Pensamento
|
Debug: Processo de Pensamento
|
||||||
<ChevronDown className={`w-3 h-3 transition-transform ${showProcessDebug ? 'rotate-180' : ''}`} />
|
<ChevronDown className={`w-3 h-3 transition-transform ${showProcessDebug ? 'rotate-180' : ''}`} />
|
||||||
</button>
|
</button>
|
||||||
{showProcessDebug && (
|
{showProcessDebug && (
|
||||||
<div className="mt-2 space-y-2 p-4 rounded-lg bg-muted/30 text-xs border border-muted/50 max-h-60 overflow-y-auto">
|
<div className="mt-2 space-y-2 p-4 rounded-lg bg-surface text-xs border max-h-60 overflow-y-auto">
|
||||||
<div className="flex justify-end mb-2">
|
<div className="flex justify-end mb-2">
|
||||||
<Button variant="ghost" size="sm" onClick={handleCopyLogs} className="h-6 px-2 text-[10px]">
|
<Button variant="ghost" size="sm" onClick={handleCopyLogs} className="h-8 px-2 text-xs">
|
||||||
{logsCopied ? <Check className="w-3 h-3 mr-1" /> : <Copy className="w-3 h-3 mr-1" />} Copiar Logs
|
{logsCopied ? <Check className="w-3 h-3 mr-1" /> : <Copy className="w-3 h-3 mr-1" />} Copiar Logs
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{deepResearch.state.logs.map((log, idx) => (
|
{deepResearch.state.logs.map((log, idx) => (
|
||||||
<div key={idx} className="grid grid-cols-[60px_1fr] gap-2 border-b border-muted/20 pb-2 last:border-0">
|
<div key={idx} className="grid grid-cols-[60px_1fr] gap-2 border-b border-border/60 pb-2 last:border-0">
|
||||||
<span className="text-muted-foreground uppercase text-[10px]">{log.stage}</span>
|
<span className="font-mono text-muted-foreground text-xs">{log.stage}</span>
|
||||||
<span>{log.input ? (log.input.length > 50 ? log.input.substring(0, 50) + '...' : log.input) : '-'}</span>
|
<span>{log.input ? (log.input.length > 50 ? log.input.substring(0, 50) + '...' : log.input) : '-'}</span>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
@@ -1430,22 +1432,22 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setShowContextDebug((prev) => !prev)}
|
onClick={() => setShowContextDebug((prev) => !prev)}
|
||||||
className="flex items-center gap-2 text-xs font-medium text-muted-foreground hover:text-primary transition-colors"
|
className="flex items-center gap-2 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors duration-150"
|
||||||
>
|
>
|
||||||
<Globe className="w-3 h-3" />
|
<Globe className="w-3 h-3" />
|
||||||
Debug: Contexto Web ({lastContextSources.length} fontes)
|
Debug: Contexto Web ({lastContextSources.length} fontes)
|
||||||
<ChevronDown className={`w-3 h-3 transition-transform ${showContextDebug ? 'rotate-180' : ''}`} />
|
<ChevronDown className={`w-3 h-3 transition-transform ${showContextDebug ? 'rotate-180' : ''}`} />
|
||||||
</button>
|
</button>
|
||||||
{showContextDebug && (
|
{showContextDebug && (
|
||||||
<div className="mt-2 p-4 rounded-lg bg-muted/30 text-xs border border-muted/50 space-y-3">
|
<div className="mt-2 p-4 rounded-lg bg-surface text-xs border space-y-3">
|
||||||
<div className="max-h-32 overflow-y-auto space-y-1">
|
<div className="max-h-32 overflow-y-auto space-y-1">
|
||||||
{lastContextSources.map((s, i) => (
|
{lastContextSources.map((s, i) => (
|
||||||
<a key={i} href={s.url} target="_blank" className="block hover:underline text-primary truncate">{s.title || s.url}</a>
|
<a key={i} href={s.url} target="_blank" className="block underline-offset-2 hover:underline text-foreground truncate">{s.title || s.url}</a>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<div className="border-t border-muted/20 pt-2">
|
<div className="border-t border-border pt-2">
|
||||||
<p className="mb-1 font-semibold">Preview Contexto:</p>
|
<p className="mb-1 font-semibold">Preview Contexto:</p>
|
||||||
<pre className="max-h-32 overflow-y-auto p-2 bg-background rounded border text-[10px]">{lastWebContext.substring(0, 500)}...</pre>
|
<pre className="max-h-32 overflow-y-auto p-2 bg-background rounded-sm border text-xs">{lastWebContext.substring(0, 500)}...</pre>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -1466,7 +1468,7 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
<div className="absolute inset-0 -top-20 bg-gradient-to-t from-background via-background/90 to-transparent pointer-events-none" />
|
<div className="absolute inset-0 -top-20 bg-gradient-to-t from-background via-background/90 to-transparent pointer-events-none" />
|
||||||
|
|
||||||
{/* Input Wrapper */}
|
{/* Input Wrapper */}
|
||||||
<div className="relative max-w-3xl mx-auto px-3 sm:px-4 md:px-6 pb-4 sm:pb-6 pt-4 pointer-events-auto transition-all duration-300" style={{ paddingLeft: 'clamp(12px, 4vw, 24px)', paddingRight: 'clamp(12px, 4vw, 24px)' }}>
|
<div className="relative max-w-3xl mx-auto px-3 sm:px-4 md:px-6 pb-4 sm:pb-6 pt-4 pointer-events-auto">
|
||||||
<ChatInput
|
<ChatInput
|
||||||
onSend={handleSend}
|
onSend={handleSend}
|
||||||
onStop={stop}
|
onStop={stop}
|
||||||
@@ -1481,7 +1483,7 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<div className="text-center mt-2">
|
<div className="text-center mt-2">
|
||||||
<p className="text-[10px] text-muted-foreground/60">OllaHub pode cometer erros. Verifique informações importantes.</p>
|
<p className="text-xs text-muted-foreground">OllaHub pode cometer erros. Verifique informações importantes.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -1495,13 +1497,13 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
{!isChatsSidebarCollapsed && (
|
{!isChatsSidebarCollapsed && (
|
||||||
<>
|
<>
|
||||||
<div
|
<div
|
||||||
className="fixed inset-0 bg-black/50 z-40 md:hidden transition-opacity"
|
className="fixed inset-0 bg-scrim z-40 md:hidden"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setIsChatsSidebarCollapsed(true);
|
setIsChatsSidebarCollapsed(true);
|
||||||
chatsSidebarRef.current?.collapse();
|
chatsSidebarRef.current?.collapse();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<div className="fixed left-0 top-0 bottom-0 w-[280px] min-w-[220px] max-w-[85vw] bg-background border-r z-50 md:hidden shadow-xl animate-in slide-in-from-left duration-300 overflow-y-auto">
|
<div className="fixed left-0 top-0 bottom-0 w-[280px] min-w-[220px] max-w-[85vw] bg-surface border-r z-50 md:hidden shadow-float animate-in slide-in-from-left duration-200 ease-out overflow-y-auto">
|
||||||
<SidebarList
|
<SidebarList
|
||||||
sessions={sessions}
|
sessions={sessions}
|
||||||
currentSessionId={currentSessionId}
|
currentSessionId={currentSessionId}
|
||||||
|
|||||||
+171
-195
@@ -4,33 +4,27 @@
|
|||||||
@custom-variant dark (&:is(.dark *));
|
@custom-variant dark (&:is(.dark *));
|
||||||
@custom-variant hc (&:is([data-high-contrast=true] *));
|
@custom-variant hc (&:is([data-high-contrast=true] *));
|
||||||
|
|
||||||
|
/* Família visual de IA local: ver DESIGN.md. Os tokens do shadcn apontam para os papéis da família. */
|
||||||
@theme inline {
|
@theme inline {
|
||||||
--color-background: var(--background);
|
--color-background: var(--background);
|
||||||
--color-foreground: var(--foreground);
|
--color-foreground: var(--foreground);
|
||||||
--font-sans: var(--font-geist-sans);
|
--color-surface: var(--surface);
|
||||||
--font-mono: var(--font-geist-mono);
|
--color-elevated: var(--elevated);
|
||||||
--color-sidebar-ring: var(--sidebar-ring);
|
--color-hover: var(--hover);
|
||||||
--color-sidebar-border: var(--sidebar-border);
|
--color-text-2: var(--text-2);
|
||||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
--color-success: var(--success);
|
||||||
--color-sidebar-accent: var(--sidebar-accent);
|
--color-warning: var(--warning);
|
||||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
--color-accent: var(--accent);
|
||||||
--color-sidebar-primary: var(--sidebar-primary);
|
--color-accent-fg: var(--accent-fg);
|
||||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
--color-accent-soft: var(--accent-soft);
|
||||||
--color-sidebar: var(--sidebar);
|
|
||||||
--color-chart-5: var(--chart-5);
|
|
||||||
--color-chart-4: var(--chart-4);
|
|
||||||
--color-chart-3: var(--chart-3);
|
|
||||||
--color-chart-2: var(--chart-2);
|
|
||||||
--color-chart-1: var(--chart-1);
|
|
||||||
--color-ring: var(--ring);
|
--color-ring: var(--ring);
|
||||||
--color-input: var(--input);
|
--color-input: var(--input);
|
||||||
--color-border: var(--border);
|
--color-border: var(--border);
|
||||||
--color-destructive: var(--destructive);
|
--color-destructive: var(--destructive);
|
||||||
--color-accent-foreground: var(--accent-foreground);
|
|
||||||
--color-accent: var(--accent);
|
|
||||||
--color-muted-foreground: var(--muted-foreground);
|
--color-muted-foreground: var(--muted-foreground);
|
||||||
--color-muted: var(--muted);
|
--color-muted: var(--muted);
|
||||||
--color-secondary-foreground: var(--secondary-foreground);
|
--color-secondary-foreground: var(--secondary-foreground);
|
||||||
|
--color-scrim: oklch(0.10 0.01 265 / 0.6);
|
||||||
--color-secondary: var(--secondary);
|
--color-secondary: var(--secondary);
|
||||||
--color-primary-foreground: var(--primary-foreground);
|
--color-primary-foreground: var(--primary-foreground);
|
||||||
--color-primary: var(--primary);
|
--color-primary: var(--primary);
|
||||||
@@ -38,160 +32,167 @@
|
|||||||
--color-popover: var(--popover);
|
--color-popover: var(--popover);
|
||||||
--color-card-foreground: var(--card-foreground);
|
--color-card-foreground: var(--card-foreground);
|
||||||
--color-card: var(--card);
|
--color-card: var(--card);
|
||||||
--color-message-user: var(--message-user);
|
|
||||||
--color-message-assistant: var(--message-assistant);
|
|
||||||
--color-message-highlight: var(--message-highlight);
|
|
||||||
--color-message-selected: var(--message-selected);
|
|
||||||
--color-message-high-contrast: var(--message-high-contrast);
|
--color-message-high-contrast: var(--message-high-contrast);
|
||||||
--radius-sm: calc(var(--radius) - 4px);
|
|
||||||
--radius-md: calc(var(--radius) - 2px);
|
--font-sans: var(--font-geist-sans), system-ui, sans-serif;
|
||||||
--radius-lg: var(--radius);
|
--font-mono: var(--font-geist-mono), ui-monospace, monospace;
|
||||||
--radius-xl: calc(var(--radius) + 4px);
|
|
||||||
--space-1: 8px;
|
/* Escala 1,2 com base 14: 12 · 14 · 17 · 20 · 24 · 29. Os nomes do Tailwind encaixam no passo mais próximo. */
|
||||||
--space-2: 16px;
|
--text-xs: 0.75rem;
|
||||||
--space-3: 24px;
|
--text-xs--line-height: 1.5;
|
||||||
--space-4: 32px;
|
--text-sm: 0.875rem;
|
||||||
--space-5: 40px;
|
--text-sm--line-height: 1.5;
|
||||||
--space-6: 48px;
|
--text-base: 1.0625rem;
|
||||||
--space-7: 56px;
|
--text-base--line-height: 1.5;
|
||||||
--space-8: 64px;
|
--text-lg: 1.0625rem;
|
||||||
|
--text-lg--line-height: 1.5;
|
||||||
|
--text-xl: 1.25rem;
|
||||||
|
--text-xl--line-height: 1.25;
|
||||||
|
--text-2xl: 1.5rem;
|
||||||
|
--text-2xl--line-height: 1.25;
|
||||||
|
--text-3xl: 1.8125rem;
|
||||||
|
--text-3xl--line-height: 1.25;
|
||||||
|
|
||||||
|
/* Raio por hierarquia: 6 chip/badge, 8 botão/input, 12 painel/card/diálogo. */
|
||||||
|
--radius-xs: 6px;
|
||||||
|
--radius-sm: 6px;
|
||||||
|
--radius-md: 8px;
|
||||||
|
--radius-lg: 12px;
|
||||||
|
--radius-xl: 12px;
|
||||||
|
|
||||||
|
/* Sombra só no que flutua (menu, popover, modal). */
|
||||||
|
--shadow-float: 0 1px 2px oklch(0.10 0.01 265 / 0.30), 0 8px 24px oklch(0.10 0.01 265 / 0.35);
|
||||||
|
|
||||||
|
--ease-out: cubic-bezier(0.16, 1, 0.3, 1);
|
||||||
|
--default-transition-duration: 150ms;
|
||||||
|
--default-transition-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
:root {
|
:root {
|
||||||
--radius: 0.625rem;
|
--bg: oklch(0.99 0.003 265);
|
||||||
--background: oklch(1 0 0);
|
--surface: oklch(0.97 0.004 265);
|
||||||
--foreground: oklch(0.141 0.005 285.823);
|
--elevated: oklch(1 0 0);
|
||||||
--card: oklch(1 0 0);
|
--hover: oklch(0.94 0.005 265);
|
||||||
--card-foreground: oklch(0.141 0.005 285.823);
|
--border: oklch(0.90 0.006 265);
|
||||||
--popover: oklch(1 0 0);
|
--text: oklch(0.20 0.010 265);
|
||||||
--popover-foreground: oklch(0.141 0.005 285.823);
|
--text-2: oklch(0.42 0.010 265);
|
||||||
--primary: oklch(0.21 0.006 285.885);
|
--text-3: oklch(0.54 0.010 265);
|
||||||
--primary-foreground: oklch(0.985 0 0);
|
--success: oklch(0.52 0.14 150);
|
||||||
--secondary: oklch(0.967 0.001 286.375);
|
--warning: oklch(0.60 0.13 75);
|
||||||
--secondary-foreground: oklch(0.21 0.006 285.885);
|
--danger: oklch(0.55 0.20 25);
|
||||||
--muted: oklch(0.967 0.001 286.375);
|
--accent: oklch(0.62 0.15 60);
|
||||||
--muted-foreground: oklch(0.552 0.016 285.938);
|
--accent-fg: oklch(0.20 0.04 60);
|
||||||
--accent: oklch(0.967 0.001 286.375);
|
--accent-soft: color-mix(in oklab, var(--accent) 14%, var(--bg));
|
||||||
--accent-foreground: oklch(0.21 0.006 285.885);
|
|
||||||
--destructive: oklch(0.577 0.245 27.325);
|
--background: var(--bg);
|
||||||
--border: oklch(0.92 0.004 286.32);
|
--foreground: var(--text);
|
||||||
--input: oklch(0.92 0.004 286.32);
|
--card: var(--surface);
|
||||||
--ring: oklch(0.705 0.015 286.067);
|
--card-foreground: var(--text);
|
||||||
--chart-1: oklch(0.646 0.222 41.116);
|
--popover: var(--elevated);
|
||||||
--chart-2: oklch(0.6 0.118 184.704);
|
--popover-foreground: var(--text);
|
||||||
--chart-3: oklch(0.398 0.07 227.392);
|
--primary: var(--accent);
|
||||||
--chart-4: oklch(0.828 0.189 84.429);
|
--primary-foreground: var(--accent-fg);
|
||||||
--chart-5: oklch(0.769 0.188 70.08);
|
--secondary: var(--hover);
|
||||||
--sidebar: oklch(0.985 0 0);
|
--secondary-foreground: var(--text);
|
||||||
--sidebar-foreground: oklch(0.141 0.005 285.823);
|
--muted: var(--surface);
|
||||||
--sidebar-primary: oklch(0.21 0.006 285.885);
|
--muted-foreground: var(--text-3);
|
||||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
--destructive: var(--danger);
|
||||||
--sidebar-accent: oklch(0.967 0.001 286.375);
|
--input: var(--border);
|
||||||
--sidebar-accent-foreground: oklch(0.21 0.006 285.885);
|
--ring: var(--accent);
|
||||||
--sidebar-border: oklch(0.92 0.004 286.32);
|
--message-high-contrast: oklch(1 0 0);
|
||||||
--sidebar-ring: oklch(0.705 0.015 286.067);
|
|
||||||
--message-user: oklch(0.965 0.02 245);
|
|
||||||
--message-assistant: oklch(0.972 0.012 300);
|
|
||||||
--message-highlight: oklch(0.94 0.02 250);
|
|
||||||
--message-selected: oklch(0.92 0.02 285);
|
|
||||||
--message-high-contrast: oklch(0.99 0 0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.dark {
|
.dark {
|
||||||
--background: oklch(0.141 0.005 285.823);
|
--bg: oklch(0.16 0.008 265);
|
||||||
--foreground: oklch(0.985 0 0);
|
--surface: oklch(0.20 0.009 265);
|
||||||
--card: oklch(0.21 0.006 285.885);
|
--elevated: oklch(0.24 0.010 265);
|
||||||
--card-foreground: oklch(0.985 0 0);
|
--hover: oklch(0.28 0.010 265);
|
||||||
--popover: oklch(0.21 0.006 285.885);
|
--border: oklch(0.32 0.010 265);
|
||||||
--popover-foreground: oklch(0.985 0 0);
|
--text: oklch(0.96 0.004 265);
|
||||||
--primary: oklch(0.92 0.004 286.32);
|
--text-2: oklch(0.76 0.008 265);
|
||||||
--primary-foreground: oklch(0.21 0.006 285.885);
|
--text-3: oklch(0.64 0.010 265);
|
||||||
--secondary: oklch(0.274 0.006 286.033);
|
--success: oklch(0.74 0.15 150);
|
||||||
--secondary-foreground: oklch(0.985 0 0);
|
--warning: oklch(0.82 0.15 85);
|
||||||
--muted: oklch(0.274 0.006 286.033);
|
--danger: oklch(0.68 0.19 25);
|
||||||
--muted-foreground: oklch(0.705 0.015 286.067);
|
--accent: oklch(0.80 0.16 70);
|
||||||
--accent: oklch(0.274 0.006 286.033);
|
--accent-fg: oklch(0.20 0.04 60);
|
||||||
--accent-foreground: oklch(0.985 0 0);
|
--message-high-contrast: oklch(0.12 0.008 265);
|
||||||
--destructive: oklch(0.704 0.191 22.216);
|
color-scheme: dark;
|
||||||
--border: oklch(1 0 0 / 10%);
|
|
||||||
--input: oklch(1 0 0 / 15%);
|
|
||||||
--ring: oklch(0.552 0.016 285.938);
|
|
||||||
--chart-1: oklch(0.488 0.243 264.376);
|
|
||||||
--chart-2: oklch(0.696 0.17 162.48);
|
|
||||||
--chart-3: oklch(0.769 0.188 70.08);
|
|
||||||
--chart-4: oklch(0.627 0.265 303.9);
|
|
||||||
--chart-5: oklch(0.645 0.246 16.439);
|
|
||||||
--sidebar: oklch(0.21 0.006 285.885);
|
|
||||||
--sidebar-foreground: oklch(0.985 0 0);
|
|
||||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
|
||||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
|
||||||
--sidebar-accent: oklch(0.274 0.006 286.033);
|
|
||||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
|
||||||
--sidebar-border: oklch(1 0 0 / 10%);
|
|
||||||
--sidebar-ring: oklch(0.552 0.016 285.938);
|
|
||||||
--message-user: oklch(0.23 0.02 245);
|
|
||||||
--message-assistant: oklch(0.24 0.015 300);
|
|
||||||
--message-highlight: oklch(0.34 0.02 250);
|
|
||||||
--message-selected: oklch(0.25 0.02 285);
|
|
||||||
--message-high-contrast: oklch(0.18 0.005 286);
|
|
||||||
}
|
|
||||||
|
|
||||||
:root[data-high-contrast="true"] {
|
|
||||||
--message-user: oklch(0.9 0 0);
|
|
||||||
--message-assistant: oklch(0.9 0 0);
|
|
||||||
--message-highlight: oklch(0.8 0 0);
|
|
||||||
--message-selected: oklch(0.7 0 0);
|
|
||||||
--message-high-contrast: oklch(0.99 0 0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@layer base {
|
@layer base {
|
||||||
*,
|
*,
|
||||||
*::before,
|
*::before,
|
||||||
*::after {
|
*::after {
|
||||||
@apply border-border outline-ring/50;
|
@apply border-border;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
html {
|
html {
|
||||||
overflow-x: hidden;
|
overflow-x: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
@apply bg-background text-foreground;
|
@apply bg-background text-foreground font-sans text-sm;
|
||||||
overflow-x: hidden;
|
overflow-x: hidden;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 100vw;
|
max-width: 100vw;
|
||||||
|
caret-color: var(--accent);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1,
|
||||||
|
h2,
|
||||||
|
h3,
|
||||||
|
h4 {
|
||||||
|
line-height: 1.25;
|
||||||
|
text-wrap: balance;
|
||||||
|
}
|
||||||
|
|
||||||
|
::selection {
|
||||||
|
background: var(--accent-soft);
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Foco visível: anel de 2 px no acento com 2 px de offset. */
|
||||||
|
:focus-visible {
|
||||||
|
outline: 2px solid var(--ring);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
text-underline-offset: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Custom Scrollbar Styles - Padronizado para toda interface */
|
/* Barras de rolagem no neutro da família */
|
||||||
::-webkit-scrollbar {
|
::-webkit-scrollbar {
|
||||||
width: 8px;
|
width: 8px;
|
||||||
height: 8px;
|
height: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
::-webkit-scrollbar-track {
|
::-webkit-scrollbar-track {
|
||||||
background: hsl(var(--muted));
|
background: transparent;
|
||||||
border-radius: 4px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
::-webkit-scrollbar-thumb {
|
::-webkit-scrollbar-thumb {
|
||||||
background: hsl(var(--primary));
|
background: var(--border);
|
||||||
border-radius: 4px;
|
border-radius: 999px;
|
||||||
transition: background 0.2s ease;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
::-webkit-scrollbar-thumb:hover {
|
::-webkit-scrollbar-thumb:hover {
|
||||||
background: hsl(var(--primary) / 0.8);
|
background: var(--text-3);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Firefox scrollbar */
|
|
||||||
* {
|
* {
|
||||||
scrollbar-width: thin;
|
scrollbar-width: thin;
|
||||||
scrollbar-color: hsl(var(--primary)) hsl(var(--muted));
|
scrollbar-color: var(--border) transparent;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Responsive adjustments */
|
|
||||||
@media (max-width: 640px) {
|
@media (max-width: 640px) {
|
||||||
::-webkit-scrollbar {
|
::-webkit-scrollbar {
|
||||||
width: 6px;
|
width: 6px;
|
||||||
@@ -205,7 +206,7 @@
|
|||||||
.sidebar-compact .sidebar-label {
|
.sidebar-compact .sidebar-label {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.sidebar-compact .sidebar-icon {
|
.sidebar-compact .sidebar-icon {
|
||||||
font-size: 24px;
|
font-size: 24px;
|
||||||
}
|
}
|
||||||
@@ -218,7 +219,7 @@
|
|||||||
min-width: 320px;
|
min-width: 320px;
|
||||||
max-width: 100vw;
|
max-width: 100vw;
|
||||||
}
|
}
|
||||||
|
|
||||||
.message-container {
|
.message-container {
|
||||||
padding-left: clamp(12px, 4vw, 24px);
|
padding-left: clamp(12px, 4vw, 24px);
|
||||||
padding-right: clamp(12px, 4vw, 24px);
|
padding-right: clamp(12px, 4vw, 24px);
|
||||||
@@ -247,7 +248,7 @@
|
|||||||
.sidebar-chat-item-content {
|
.sidebar-chat-item-content {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: flex-start;
|
align-items: flex-start;
|
||||||
gap: 0.625rem;
|
gap: 0.75rem;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
@@ -274,13 +275,6 @@
|
|||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Responsive font sizes */
|
|
||||||
@media (max-width: 640px) {
|
|
||||||
.responsive-text {
|
|
||||||
font-size: clamp(14px, 4vw, 16px);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Model name truncation - ensure long model names don't break layout */
|
/* Model name truncation - ensure long model names don't break layout */
|
||||||
.model-name {
|
.model-name {
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
@@ -294,7 +288,6 @@
|
|||||||
@media (max-width: 600px) {
|
@media (max-width: 600px) {
|
||||||
.model-name {
|
.model-name {
|
||||||
max-width: 54vw;
|
max-width: 54vw;
|
||||||
font-size: 15px;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -320,76 +313,29 @@
|
|||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Scrollbar específico para lista de chats - mais fino e discreto */
|
/* Scrollbar horizontal mínima para sources, some quando não há hover */
|
||||||
.sidebar-chat-list::-webkit-scrollbar {
|
|
||||||
width: 6px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar-chat-list::-webkit-scrollbar-track {
|
|
||||||
background: transparent;
|
|
||||||
border-radius: 3px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar-chat-list::-webkit-scrollbar-thumb {
|
|
||||||
background: hsl(var(--muted-foreground) / 0.3);
|
|
||||||
border-radius: 3px;
|
|
||||||
transition: background 0.2s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar-chat-list::-webkit-scrollbar-thumb:hover {
|
|
||||||
background: hsl(var(--primary) / 0.6);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Firefox scrollbar para lista de chats */
|
|
||||||
.sidebar-chat-list {
|
|
||||||
scrollbar-width: thin;
|
|
||||||
scrollbar-color: hsl(var(--muted-foreground) / 0.3) transparent;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Minimalista scrollbar para sources */
|
|
||||||
.sources-scrollbar {
|
|
||||||
scrollbar-width: thin;
|
|
||||||
scrollbar-color: hsl(var(--muted-foreground) / 0.2) transparent;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sources-scrollbar::-webkit-scrollbar {
|
.sources-scrollbar::-webkit-scrollbar {
|
||||||
height: 4px;
|
height: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.sources-scrollbar::-webkit-scrollbar-track {
|
|
||||||
background: transparent;
|
|
||||||
border-radius: 2px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sources-scrollbar::-webkit-scrollbar-thumb {
|
|
||||||
background: hsl(var(--muted-foreground) / 0.2);
|
|
||||||
border-radius: 2px;
|
|
||||||
transition: background 0.2s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sources-scrollbar::-webkit-scrollbar-thumb:hover {
|
|
||||||
background: hsl(var(--muted-foreground) / 0.35);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Ocultar scrollbar quando não há overflow */
|
|
||||||
.sources-scrollbar:not(:hover)::-webkit-scrollbar-thumb {
|
.sources-scrollbar:not(:hover)::-webkit-scrollbar-thumb {
|
||||||
background: transparent;
|
background: transparent;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Reasoning Chain animations */
|
/* Reasoning Chain animations */
|
||||||
@keyframes reasoning-fade-in {
|
@keyframes reasoning-fade-in {
|
||||||
from {
|
from {
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
transform: translateY(4px);
|
transform: translateY(4px);
|
||||||
}
|
}
|
||||||
to {
|
to {
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
transform: translateY(0);
|
transform: translateY(0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.reasoning-step {
|
.reasoning-step {
|
||||||
animation: reasoning-fade-in 0.3s ease-out forwards;
|
animation: reasoning-fade-in 200ms var(--ease-out) forwards;
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -402,4 +348,34 @@
|
|||||||
.reasoning-step:nth-child(6) { animation-delay: 500ms; }
|
.reasoning-step:nth-child(6) { animation-delay: 500ms; }
|
||||||
.reasoning-step:nth-child(7) { animation-delay: 600ms; }
|
.reasoning-step:nth-child(7) { animation-delay: 600ms; }
|
||||||
.reasoning-step:nth-child(8) { animation-delay: 700ms; }
|
.reasoning-step:nth-child(8) { animation-delay: 700ms; }
|
||||||
.reasoning-step:nth-child(n+9) { animation-delay: 800ms; }
|
.reasoning-step:nth-child(n+9) { animation-delay: 800ms; }
|
||||||
|
|
||||||
|
/* Movimento reduzido: sem deslocamento; indicadores de carregamento viram pulso de opacidade. */
|
||||||
|
@keyframes reduced-pulse {
|
||||||
|
50% {
|
||||||
|
opacity: 0.45;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.reasoning-step {
|
||||||
|
animation: none;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.animate-spin,
|
||||||
|
.animate-bounce,
|
||||||
|
.animate-ping {
|
||||||
|
animation: reduced-pulse 1.6s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.animate-in,
|
||||||
|
.animate-out {
|
||||||
|
--tw-enter-translate-x: 0;
|
||||||
|
--tw-enter-translate-y: 0;
|
||||||
|
--tw-enter-scale: 1;
|
||||||
|
--tw-exit-translate-x: 0;
|
||||||
|
--tw-exit-translate-y: 0;
|
||||||
|
--tw-exit-scale: 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-13
@@ -1,19 +1,10 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { Geist, Geist_Mono } from "next/font/google";
|
import { GeistSans } from "geist/font/sans";
|
||||||
|
import { GeistMono } from "geist/font/mono";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
import { ThemeProvider } from "@/components/theme-provider";
|
import { ThemeProvider } from "@/components/theme-provider";
|
||||||
import { AppUpdaterProvider } from "@/components/app-updater-provider";
|
import { AppUpdaterProvider } from "@/components/app-updater-provider";
|
||||||
|
|
||||||
const geistSans = Geist({
|
|
||||||
variable: "--font-geist-sans",
|
|
||||||
subsets: ["latin"],
|
|
||||||
});
|
|
||||||
|
|
||||||
const geistMono = Geist_Mono({
|
|
||||||
variable: "--font-geist-mono",
|
|
||||||
subsets: ["latin"],
|
|
||||||
});
|
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "OllaHub",
|
title: "OllaHub",
|
||||||
description: "Interface moderna para Ollama",
|
description: "Interface moderna para Ollama",
|
||||||
@@ -27,11 +18,11 @@ export default function RootLayout({
|
|||||||
return (
|
return (
|
||||||
<html lang="pt-BR" suppressHydrationWarning>
|
<html lang="pt-BR" suppressHydrationWarning>
|
||||||
<body
|
<body
|
||||||
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
className={`${GeistSans.variable} ${GeistMono.variable} antialiased`}
|
||||||
>
|
>
|
||||||
<ThemeProvider
|
<ThemeProvider
|
||||||
attribute="class"
|
attribute="class"
|
||||||
defaultTheme="system"
|
defaultTheme="dark"
|
||||||
enableSystem
|
enableSystem
|
||||||
disableTransitionOnChange
|
disableTransitionOnChange
|
||||||
>
|
>
|
||||||
|
|||||||
+6
-6
@@ -45,15 +45,15 @@ export default function Home() {
|
|||||||
|
|
||||||
if (status === 'checking') {
|
if (status === 'checking') {
|
||||||
return (
|
return (
|
||||||
<div className="flex h-screen w-full items-center justify-center bg-background">
|
<div className="flex h-screen w-full items-center justify-center gap-2 bg-background">
|
||||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
<Loader2 className="h-5 w-5 animate-spin text-primary" />
|
||||||
<span className="ml-2 text-muted-foreground">Verificando sistema...</span>
|
<span className="text-muted-foreground">Verificando sistema...</span>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="flex min-h-screen flex-col items-center justify-center p-4 bg-background text-foreground transition-colors duration-300">
|
<main className="flex min-h-screen flex-col items-center justify-center p-4 bg-background text-foreground">
|
||||||
{/* Notificação de boas-vindas */}
|
{/* Notificação de boas-vindas */}
|
||||||
<WelcomeNotification />
|
<WelcomeNotification />
|
||||||
|
|
||||||
@@ -64,9 +64,9 @@ export default function Home() {
|
|||||||
|
|
||||||
{/* Layout for Stopped State */}
|
{/* Layout for Stopped State */}
|
||||||
{status === 'installed_stopped' && (
|
{status === 'installed_stopped' && (
|
||||||
<div className="flex flex-col items-center gap-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
|
<div className="flex flex-col items-center gap-8 animate-in fade-in duration-200 ease-out">
|
||||||
<div className="text-center space-y-2">
|
<div className="text-center space-y-2">
|
||||||
<h1 className="text-3xl font-bold tracking-tighter">OllaHub</h1>
|
<h1 className="text-3xl font-semibold tracking-tight">OllaHub</h1>
|
||||||
<p className="text-muted-foreground">Detectamos o Ollama, mas ele não está rodando.</p>
|
<p className="text-muted-foreground">Detectamos o Ollama, mas ele não está rodando.</p>
|
||||||
</div>
|
</div>
|
||||||
<StoppedCard onCheckAgain={check} />
|
<StoppedCard onCheckAgain={check} />
|
||||||
|
|||||||
+19
-19
@@ -232,11 +232,11 @@ export default function SettingsPage() {
|
|||||||
<TitleBar />
|
<TitleBar />
|
||||||
<div className="flex-1 overflow-y-auto">
|
<div className="flex-1 overflow-y-auto">
|
||||||
<div className="container mx-auto py-4 sm:py-6 md:py-8 px-3 sm:px-4 md:px-6 max-w-4xl w-full overflow-x-hidden">
|
<div className="container mx-auto py-4 sm:py-6 md:py-8 px-3 sm:px-4 md:px-6 max-w-4xl w-full overflow-x-hidden">
|
||||||
<div className="mb-4 sm:mb-6">
|
<div className="mb-6">
|
||||||
<div className="flex items-start justify-between gap-3">
|
<div className="flex items-start justify-between gap-3">
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<h1 className="text-2xl sm:text-3xl font-bold truncate">Configurações</h1>
|
<h1 className="text-2xl font-semibold tracking-tight truncate">Configurações</h1>
|
||||||
<p className="text-muted-foreground mt-1 sm:mt-2 text-sm sm:text-base">
|
<p className="text-muted-foreground mt-1 text-sm">
|
||||||
Gerencie as preferências do OllaHub
|
Gerencie as preferências do OllaHub
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -244,7 +244,7 @@ export default function SettingsPage() {
|
|||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={() => router.push('/chat')}
|
onClick={() => router.push('/chat')}
|
||||||
className="rounded-lg shrink-0"
|
className="shrink-0 text-muted-foreground hover:text-foreground"
|
||||||
title="Fechar configurações"
|
title="Fechar configurações"
|
||||||
>
|
>
|
||||||
<X className="w-5 h-5" />
|
<X className="w-5 h-5" />
|
||||||
@@ -252,24 +252,24 @@ export default function SettingsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Tabs defaultValue="overview" className="space-y-4 sm:space-y-6">
|
<Tabs defaultValue="overview" className="space-y-6">
|
||||||
<TabsList className="grid w-full grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-1 sm:gap-2 h-auto">
|
<TabsList className="grid w-full grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-1 h-auto">
|
||||||
<TabsTrigger value="overview" className="text-xs sm:text-sm px-2 sm:px-3 py-1.5 sm:py-2 truncate">
|
<TabsTrigger value="overview" className="px-3 py-2 truncate">
|
||||||
Visão Geral
|
Visão Geral
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
<TabsTrigger value="general" className="text-xs sm:text-sm px-2 sm:px-3 py-1.5 sm:py-2 truncate">
|
<TabsTrigger value="general" className="px-3 py-2 truncate">
|
||||||
General
|
General
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
<TabsTrigger value="web" className="text-xs sm:text-sm px-2 sm:px-3 py-1.5 sm:py-2 truncate">
|
<TabsTrigger value="web" className="px-3 py-2 truncate">
|
||||||
Web Search
|
Web Search
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
<TabsTrigger value="sources" className="text-xs sm:text-sm px-2 sm:px-3 py-1.5 sm:py-2 truncate">
|
<TabsTrigger value="sources" className="px-3 py-2 truncate">
|
||||||
Sources
|
Sources
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
<TabsTrigger value="tasks" className="text-xs sm:text-sm px-2 sm:px-3 py-1.5 sm:py-2 truncate">
|
<TabsTrigger value="tasks" className="px-3 py-2 truncate">
|
||||||
Tasks
|
Tasks
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
<TabsTrigger value="system" className="text-xs sm:text-sm px-2 sm:px-3 py-1.5 sm:py-2 truncate">
|
<TabsTrigger value="system" className="px-3 py-2 truncate">
|
||||||
System
|
System
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
</TabsList>
|
</TabsList>
|
||||||
@@ -316,11 +316,11 @@ export default function SettingsPage() {
|
|||||||
className="shrink-0"
|
className="shrink-0"
|
||||||
>
|
>
|
||||||
{isCheckingConnection ? (
|
{isCheckingConnection ? (
|
||||||
<Loader2 className="w-4 h-4 animate-spin" />
|
<Loader2 className="w-4 h-4 animate-spin text-primary" />
|
||||||
) : connectionStatus === 'success' ? (
|
) : connectionStatus === 'success' ? (
|
||||||
<CheckCircle2 className="w-4 h-4 text-green-500" />
|
<CheckCircle2 className="w-4 h-4 text-success" />
|
||||||
) : connectionStatus === 'error' ? (
|
) : connectionStatus === 'error' ? (
|
||||||
<XCircle className="w-4 h-4 text-red-500" />
|
<XCircle className="w-4 h-4 text-destructive" />
|
||||||
) : (
|
) : (
|
||||||
'Verificar'
|
'Verificar'
|
||||||
)}
|
)}
|
||||||
@@ -561,7 +561,7 @@ export default function SettingsPage() {
|
|||||||
{settings.webSearch.engineOrder.map((engine, index) => (
|
{settings.webSearch.engineOrder.map((engine, index) => (
|
||||||
<div
|
<div
|
||||||
key={engine}
|
key={engine}
|
||||||
className="flex items-center justify-between p-2 rounded-md hover:bg-muted/50 transition-colors"
|
className="flex items-center justify-between p-2 rounded-md hover:bg-hover transition-colors duration-150"
|
||||||
>
|
>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Badge variant="outline" className="font-mono text-xs">
|
<Badge variant="outline" className="font-mono text-xs">
|
||||||
@@ -819,7 +819,7 @@ export default function SettingsPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card key={category.id} className={category.enabled ? 'border-primary' : ''}>
|
<Card key={category.id} className={category.enabled ? 'border-foreground/30' : ''}>
|
||||||
<CardContent className="pt-4 sm:pt-6">
|
<CardContent className="pt-4 sm:pt-6">
|
||||||
<div className="flex flex-col sm:flex-row items-start justify-between gap-3 sm:gap-0">
|
<div className="flex flex-col sm:flex-row items-start justify-between gap-3 sm:gap-0">
|
||||||
<div className="flex items-start gap-2 sm:gap-3 flex-1 min-w-0 w-full">
|
<div className="flex items-start gap-2 sm:gap-3 flex-1 min-w-0 w-full">
|
||||||
@@ -1044,7 +1044,7 @@ export default function SettingsPage() {
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<div className="bg-black text-green-400 font-mono text-xs p-4 rounded-lg h-[400px] overflow-y-auto">
|
<div className="bg-background border text-foreground font-mono text-xs p-4 rounded-md h-[400px] overflow-y-auto">
|
||||||
{isLoadingLogs ? (
|
{isLoadingLogs ? (
|
||||||
<div className="flex items-center gap-2 text-muted-foreground">
|
<div className="flex items-center gap-2 text-muted-foreground">
|
||||||
<Loader2 className="w-4 h-4 animate-spin" />
|
<Loader2 className="w-4 h-4 animate-spin" />
|
||||||
@@ -1138,7 +1138,7 @@ export default function SettingsPage() {
|
|||||||
{updater.updateAvailable && (
|
{updater.updateAvailable && (
|
||||||
<div className="flex items-center justify-between text-sm">
|
<div className="flex items-center justify-between text-sm">
|
||||||
<span className="text-muted-foreground">Nova Versão Disponível</span>
|
<span className="text-muted-foreground">Nova Versão Disponível</span>
|
||||||
<span className="font-mono font-medium text-primary">
|
<span className="font-mono font-semibold text-foreground">
|
||||||
{updater.updateInfo?.version}
|
{updater.updateInfo?.version}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+4
-4
@@ -19,22 +19,22 @@ export default function SetupPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="flex min-h-screen flex-col items-center justify-center p-4 bg-background text-foreground">
|
<main className="flex min-h-screen flex-col items-center justify-center p-4 bg-background text-foreground">
|
||||||
<div className="w-full max-w-2xl space-y-8 animate-in fade-in duration-700">
|
<div className="w-full max-w-2xl space-y-8 animate-in fade-in duration-200 ease-out">
|
||||||
<div className="text-center space-y-2">
|
<div className="text-center space-y-2">
|
||||||
<h1 className="text-3xl font-bold tracking-tighter">Configuração Inicial</h1>
|
<h1 className="text-3xl font-semibold tracking-tight">Configuração Inicial</h1>
|
||||||
<p className="text-muted-foreground">Vamos preparar o ambiente ideal para você.</p>
|
<p className="text-muted-foreground">Vamos preparar o ambiente ideal para você.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<HardwareScan specs={specs} loading={loading} />
|
<HardwareScan specs={specs} loading={loading} />
|
||||||
|
|
||||||
{!loading && specs && gpus.length > 0 && (
|
{!loading && specs && gpus.length > 0 && (
|
||||||
<div className="animate-in slide-in-from-bottom-8 duration-700 delay-200 fill-mode-backwards">
|
<div className="animate-in fade-in duration-200 ease-out">
|
||||||
<GpuSelector gpus={gpus} />
|
<GpuSelector gpus={gpus} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!loading && specs && (
|
{!loading && specs && (
|
||||||
<div className="animate-in slide-in-from-bottom-8 duration-700 delay-300 fill-mode-backwards">
|
<div className="animate-in fade-in duration-200 ease-out">
|
||||||
<ModelSelector
|
<ModelSelector
|
||||||
recommendation={getRecommendation(specs)}
|
recommendation={getRecommendation(specs)}
|
||||||
onComplete={handleComplete}
|
onComplete={handleComplete}
|
||||||
|
|||||||
+11
-9
@@ -107,11 +107,11 @@ export default function TasksPage() {
|
|||||||
<TitleBar />
|
<TitleBar />
|
||||||
<div className="flex-1 overflow-y-auto">
|
<div className="flex-1 overflow-y-auto">
|
||||||
<div className="container mx-auto p-4 sm:p-6 max-w-6xl w-full overflow-x-hidden">
|
<div className="container mx-auto p-4 sm:p-6 max-w-6xl w-full overflow-x-hidden">
|
||||||
<div className="mb-4 sm:mb-6">
|
<div className="mb-6">
|
||||||
<div className="flex items-start justify-between gap-3">
|
<div className="flex items-start justify-between gap-3">
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<h1 className="text-2xl sm:text-3xl font-bold truncate">Tarefas Agendadas</h1>
|
<h1 className="text-2xl font-semibold tracking-tight truncate">Tarefas Agendadas</h1>
|
||||||
<p className="text-muted-foreground mt-1 text-sm sm:text-base">
|
<p className="text-muted-foreground mt-1 text-sm">
|
||||||
Gerencie tarefas que executam automaticamente em segundo plano
|
Gerencie tarefas que executam automaticamente em segundo plano
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -119,7 +119,7 @@ export default function TasksPage() {
|
|||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={() => router.push('/chat')}
|
onClick={() => router.push('/chat')}
|
||||||
className="rounded-lg shrink-0"
|
className="shrink-0 text-muted-foreground hover:text-foreground"
|
||||||
title="Voltar para o chat"
|
title="Voltar para o chat"
|
||||||
>
|
>
|
||||||
<X className="w-5 h-5" />
|
<X className="w-5 h-5" />
|
||||||
@@ -140,7 +140,7 @@ export default function TasksPage() {
|
|||||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||||
<DialogTrigger asChild>
|
<DialogTrigger asChild>
|
||||||
<Button size="lg" className="w-full max-w-md">
|
<Button size="lg" className="w-full max-w-md">
|
||||||
<Plus className="w-5 h-5 mr-2" />
|
<Plus className="w-4 h-4" />
|
||||||
Criar Primeira Task
|
Criar Primeira Task
|
||||||
</Button>
|
</Button>
|
||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
@@ -167,7 +167,7 @@ export default function TasksPage() {
|
|||||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||||
<DialogTrigger asChild>
|
<DialogTrigger asChild>
|
||||||
<Button size="lg" className="w-full">
|
<Button size="lg" className="w-full">
|
||||||
<Plus className="w-5 h-5 mr-2" />
|
<Plus className="w-4 h-4" />
|
||||||
Nova Task
|
Nova Task
|
||||||
</Button>
|
</Button>
|
||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
@@ -196,13 +196,13 @@ export default function TasksPage() {
|
|||||||
<CardTitle className="flex items-center gap-2">
|
<CardTitle className="flex items-center gap-2">
|
||||||
{task.label}
|
{task.label}
|
||||||
{task.enabled ? (
|
{task.enabled ? (
|
||||||
<Badge variant="default" className="bg-green-500/10 text-green-500 border-green-500/20">
|
<Badge variant="outline" className="bg-success/10 text-success border-success/30">
|
||||||
<CheckCircle2 className="w-3 h-3 mr-1" />
|
<CheckCircle2 className="w-3 h-3" />
|
||||||
Ativa
|
Ativa
|
||||||
</Badge>
|
</Badge>
|
||||||
) : (
|
) : (
|
||||||
<Badge variant="secondary">
|
<Badge variant="secondary">
|
||||||
<XCircle className="w-3 h-3 mr-1" />
|
<XCircle className="w-3 h-3" />
|
||||||
Pausada
|
Pausada
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
@@ -232,6 +232,8 @@ export default function TasksPage() {
|
|||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={() => deleteTask(task.id)}
|
onClick={() => deleteTask(task.id)}
|
||||||
|
className="text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
|
||||||
|
aria-label="Excluir task"
|
||||||
>
|
>
|
||||||
<Trash2 className="w-4 h-4" />
|
<Trash2 className="w-4 h-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,140 +0,0 @@
|
|||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -105,21 +105,21 @@ export function ChatInput({
|
|||||||
return (
|
return (
|
||||||
<div className="w-full bg-transparent">
|
<div className="w-full bg-transparent">
|
||||||
<div className="relative w-full">
|
<div className="relative w-full">
|
||||||
<div className="flex-1 relative bg-background dark:bg-zinc-900/50 rounded-[2rem] border border-border/50 shadow-lg backdrop-blur-xl transition-all duration-200 focus-within:ring-2 focus-within:ring-primary/20 focus-within:border-primary/40 hover:border-primary/30">
|
<div className="flex-1 relative bg-surface rounded-lg border transition-colors duration-150 hover:border-muted-foreground/60 focus-within:border-ring focus-within:outline-2 focus-within:outline-offset-2 focus-within:outline-ring">
|
||||||
<Textarea
|
<Textarea
|
||||||
ref={textareaRef}
|
ref={textareaRef}
|
||||||
value={input}
|
value={input}
|
||||||
onChange={(e) => setInput(e.target.value)}
|
onChange={(e) => setInput(e.target.value)}
|
||||||
onKeyDown={handleKeyDown}
|
onKeyDown={handleKeyDown}
|
||||||
placeholder="Pergunte qualquer coisa..."
|
placeholder="Pergunte qualquer coisa..."
|
||||||
className={`min-h-[52px] sm:min-h-[56px] max-h-[200px] w-full resize-none bg-transparent py-3 sm:py-4 pl-4 sm:pl-6 pr-28 sm:pr-32 text-[16px] sm:text-lg rounded-[2rem] border-0 focus-visible:ring-0 shadow-none placeholder:text-muted-foreground/50 ${
|
className={`min-h-14 max-h-[200px] w-full resize-none bg-transparent py-4 pl-4 pr-28 sm:pr-32 text-sm rounded-lg border-0 focus-visible:ring-0 shadow-none placeholder:text-muted-foreground ${
|
||||||
input.trim() && !isValid ? 'text-destructive' : ''
|
input.trim() && !isValid ? 'text-destructive' : ''
|
||||||
}`}
|
}`}
|
||||||
rows={1}
|
rows={1}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Right Actions */}
|
{/* Right Actions */}
|
||||||
<div className="absolute right-2 sm:right-3 bottom-2 sm:bottom-2.5 flex items-center gap-1 sm:gap-1.5">
|
<div className="absolute right-2 bottom-2 flex items-center gap-1">
|
||||||
{onWebSearchToggle && (
|
{onWebSearchToggle && (
|
||||||
<TooltipProvider>
|
<TooltipProvider>
|
||||||
<Tooltip delayDuration={300}>
|
<Tooltip delayDuration={300}>
|
||||||
@@ -134,10 +134,10 @@ export function ChatInput({
|
|||||||
setWebDialogOpen(true);
|
setWebDialogOpen(true);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
className={`h-9 w-9 rounded-full transition-all ${
|
className={`h-9 w-9 transition-colors duration-150 ${
|
||||||
webSearchEnabled
|
webSearchEnabled
|
||||||
? "text-primary bg-primary/10 hover:bg-primary/20"
|
? "text-foreground bg-accent-soft hover:bg-accent-soft"
|
||||||
: "text-muted-foreground hover:text-foreground hover:bg-muted"
|
: "text-muted-foreground hover:text-foreground hover:bg-hover"
|
||||||
}`}
|
}`}
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
>
|
>
|
||||||
@@ -162,11 +162,11 @@ export function ChatInput({
|
|||||||
{onToggleCategory && categories && categories.length > 0 && (
|
{onToggleCategory && categories && categories.length > 0 && (
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<Button size="icon" variant="ghost" className="h-9 w-9 rounded-full text-muted-foreground hover:text-foreground hover:bg-muted" title="Gerenciar fontes">
|
<Button size="icon" variant="ghost" className="h-9 w-9 text-muted-foreground hover:text-foreground hover:bg-hover" title="Gerenciar fontes">
|
||||||
<ChevronUp className="h-4 w-4" />
|
<ChevronUp className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end" sideOffset={12} className="w-56 rounded-xl">
|
<DropdownMenuContent align="end" sideOffset={12} className="w-56">
|
||||||
<DropdownMenuLabel>Fontes de conhecimento</DropdownMenuLabel>
|
<DropdownMenuLabel>Fontes de conhecimento</DropdownMenuLabel>
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
{categories.map((cat) => {
|
{categories.map((cat) => {
|
||||||
@@ -188,7 +188,7 @@ export function ChatInput({
|
|||||||
onCheckedChange={(checked) => onToggleCategory(cat.id, !!checked)}
|
onCheckedChange={(checked) => onToggleCategory(cat.id, !!checked)}
|
||||||
className="pl-8"
|
className="pl-8"
|
||||||
>
|
>
|
||||||
<div className="flex items-center gap-2.5">
|
<div className="flex items-center gap-2">
|
||||||
{getCategoryIcon(cat.id)}
|
{getCategoryIcon(cat.id)}
|
||||||
<span>{cat.name}</span>
|
<span>{cat.name}</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -204,22 +204,20 @@ export function ChatInput({
|
|||||||
size="icon"
|
size="icon"
|
||||||
variant="destructive"
|
variant="destructive"
|
||||||
onClick={onStop}
|
onClick={onStop}
|
||||||
className="h-9 w-9 rounded-full shadow-sm animate-in fade-in zoom-in duration-200"
|
className="h-9 w-9 animate-in fade-in duration-150"
|
||||||
|
aria-label="Parar geração"
|
||||||
>
|
>
|
||||||
<Square className="h-3.5 w-3.5 fill-current" />
|
<Square className="h-4 w-4 fill-current" />
|
||||||
</Button>
|
</Button>
|
||||||
) : (
|
) : (
|
||||||
<Button
|
<Button
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={handleSend}
|
onClick={handleSend}
|
||||||
disabled={!input.trim() || !isValid}
|
disabled={!input.trim() || !isValid}
|
||||||
className={`h-9 w-9 rounded-full transition-all shadow-sm ${
|
className="h-9 w-9"
|
||||||
input.trim() && isValid
|
aria-label="Enviar mensagem"
|
||||||
? "bg-primary text-primary-foreground hover:bg-primary/90"
|
|
||||||
: "bg-muted text-muted-foreground cursor-not-allowed"
|
|
||||||
}`}
|
|
||||||
>
|
>
|
||||||
<Send className="h-4 w-4 ml-0.5" />
|
<Send className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -227,9 +225,9 @@ export function ChatInput({
|
|||||||
|
|
||||||
{/* Validation Errors */}
|
{/* Validation Errors */}
|
||||||
{input.trim() && !isValid && validation.errors.length > 0 && (
|
{input.trim() && !isValid && validation.errors.length > 0 && (
|
||||||
<div className="absolute -top-12 left-0 right-0 mx-auto w-max max-w-[90%] animate-in fade-in slide-in-from-bottom-2">
|
<div className="absolute -top-12 left-0 right-0 mx-auto w-max max-w-[90%] animate-in fade-in duration-150">
|
||||||
<div className="bg-destructive/90 text-destructive-foreground text-xs px-3 py-1.5 rounded-full shadow-lg flex items-center gap-2 backdrop-blur-sm">
|
<div className="bg-popover border border-destructive/40 text-destructive text-xs px-3 py-2 rounded-md shadow-float flex items-center gap-2">
|
||||||
<AlertCircle className="h-3.5 w-3.5" />
|
<AlertCircle className="h-4 w-4" />
|
||||||
<span>{validation.errors[0]}</span>
|
<span>{validation.errors[0]}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -237,19 +235,18 @@ export function ChatInput({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Dialog open={webDialogOpen} onOpenChange={setWebDialogOpen}>
|
<Dialog open={webDialogOpen} onOpenChange={setWebDialogOpen}>
|
||||||
<DialogContent className="sm:max-w-[425px] rounded-2xl">
|
<DialogContent className="sm:max-w-[425px]">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>Desativar pesquisa web?</DialogTitle>
|
<DialogTitle>Desativar pesquisa web?</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
Desativar a busca pode reduzir a qualidade em perguntas sobre fatos recentes.
|
Desativar a busca pode reduzir a qualidade em perguntas sobre fatos recentes.
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<DialogFooter className="gap-2 sm:gap-0">
|
<DialogFooter className="gap-2">
|
||||||
<Button variant="outline" onClick={() => setWebDialogOpen(false)} className="rounded-full">Cancelar</Button>
|
<Button variant="outline" onClick={() => setWebDialogOpen(false)}>Cancelar</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="destructive"
|
variant="destructive"
|
||||||
onClick={() => { onWebSearchToggle?.(false); setWebDialogOpen(false); }}
|
onClick={() => { onWebSearchToggle?.(false); setWebDialogOpen(false); }}
|
||||||
className="rounded-full"
|
|
||||||
>
|
>
|
||||||
Desativar
|
Desativar
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,76 +0,0 @@
|
|||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -18,16 +18,6 @@ interface ChatMessageProps {
|
|||||||
messageIndex?: number;
|
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, '&')
|
|
||||||
.replace(/</g, '<')
|
|
||||||
.replace(/>/g, '>')
|
|
||||||
.replace(/"/g, '"')
|
|
||||||
.replace(/'/g, ''');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Componente de mensagem do chat otimizado com React.memo
|
* Componente de mensagem do chat otimizado com React.memo
|
||||||
*
|
*
|
||||||
@@ -106,20 +96,20 @@ function ChatMessageComponent({ message, isStreaming = false, highlightTerm, hig
|
|||||||
|
|
||||||
matches.forEach((match, idx) => {
|
matches.forEach((match, idx) => {
|
||||||
// Adicionar texto antes do match
|
// Adicionar texto antes do match
|
||||||
highlighted += escapeHtml(content.substring(lastIndex, match.start));
|
highlighted += content.substring(lastIndex, match.start);
|
||||||
|
|
||||||
// Adicionar match com highlight (laranja para atual, amarelo para outros)
|
// Adicionar match com highlight (acento para o atual, acento suave para os outros)
|
||||||
const isCurrent = highlightIndex !== undefined && idx === highlightIndex;
|
const isCurrent = highlightIndex !== undefined && idx === highlightIndex;
|
||||||
const className = isCurrent
|
const className = isCurrent
|
||||||
? 'bg-orange-400/60 dark:bg-orange-500/60 px-0.5 rounded'
|
? 'bg-accent text-accent-fg px-1 rounded-sm'
|
||||||
: 'bg-yellow-200/50 dark:bg-yellow-800/50 px-0.5 rounded';
|
: 'bg-accent-soft text-foreground px-1 rounded-sm';
|
||||||
|
|
||||||
highlighted += `<mark class="${className}">${escapeHtml(match.text)}</mark>`;
|
highlighted += `<mark class="${className}">${match.text}</mark>`;
|
||||||
lastIndex = match.end;
|
lastIndex = match.end;
|
||||||
});
|
});
|
||||||
|
|
||||||
// Adicionar texto restante
|
// Adicionar texto restante
|
||||||
highlighted += escapeHtml(content.substring(lastIndex));
|
highlighted += content.substring(lastIndex);
|
||||||
return highlighted;
|
return highlighted;
|
||||||
}, [processedContent, highlightTerm, highlightIndex, message.role, isStreaming]);
|
}, [processedContent, highlightTerm, highlightIndex, message.role, isStreaming]);
|
||||||
|
|
||||||
@@ -128,62 +118,47 @@ function ChatMessageComponent({ message, isStreaming = false, highlightTerm, hig
|
|||||||
role={isUser ? 'user' : 'assistant'}
|
role={isUser ? 'user' : 'assistant'}
|
||||||
state={selected ? 'selected' : 'normal'}
|
state={selected ? 'selected' : 'normal'}
|
||||||
className={cn(
|
className={cn(
|
||||||
"cursor-default transition-colors rounded-xl",
|
"cursor-default transition-colors duration-150 rounded-lg",
|
||||||
selected && "bg-muted/40",
|
selected && "bg-surface",
|
||||||
isUser ? "mb-2" : "mb-8"
|
isUser ? "mb-2" : "mb-8"
|
||||||
)}
|
)}
|
||||||
onClick={() => setSelected((v) => !v)}
|
onClick={() => setSelected((v) => !v)}
|
||||||
tabIndex={0}
|
tabIndex={0}
|
||||||
>
|
>
|
||||||
<div className="flex-shrink-0 mt-0.5">
|
<div className="flex-shrink-0">
|
||||||
<div className={cn(
|
<div className="w-8 h-8 rounded-full flex items-center justify-center border bg-surface text-muted-foreground">
|
||||||
"w-8 h-8 rounded-full flex items-center justify-center shadow-sm ring-1 ring-border/50 backdrop-blur-sm",
|
{isUser ? <User className="w-4 h-4" /> : <Bot className="w-4 h-4 text-foreground" />}
|
||||||
isUser
|
|
||||||
? "bg-background text-muted-foreground"
|
|
||||||
: "bg-primary/10 text-primary ring-primary/20"
|
|
||||||
)}>
|
|
||||||
{isUser ? <User className="w-4 h-4" /> : <Bot className="w-5 h-5" />}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex-1 overflow-hidden min-w-0 pt-1" data-message-index={messageIndex}>
|
<div className="flex-1 overflow-hidden min-w-0 max-w-[72ch] pt-1" data-message-index={messageIndex}>
|
||||||
{isUser ? (
|
{isUser ? (
|
||||||
// Estilo específico para mensagem do usuário (mais destaque, fonte maior)
|
// Estilo específico para mensagem do usuário (mais destaque, fonte maior)
|
||||||
<div
|
<div
|
||||||
className="text-lg sm:text-xl font-medium tracking-tight text-foreground/90 leading-relaxed break-words whitespace-pre-wrap"
|
className="text-lg font-medium text-foreground break-words whitespace-pre-wrap"
|
||||||
dangerouslySetInnerHTML={highlightedContent ? { __html: highlightedContent } : undefined}
|
dangerouslySetInnerHTML={highlightedContent ? { __html: highlightedContent } : undefined}
|
||||||
>
|
>
|
||||||
{highlightedContent ? null : processedContent}
|
{!highlightedContent && processedContent}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
// Estilo Assistant
|
// Estilo Assistant
|
||||||
isEmpty && isStreaming ? (
|
isEmpty && isStreaming ? (
|
||||||
<div className="flex items-center gap-2 text-muted-foreground py-1">
|
<div className="flex items-center gap-2 text-muted-foreground py-1">
|
||||||
<div className="w-2 h-2 bg-primary rounded-full animate-pulse" />
|
<div className="w-2 h-2 bg-primary rounded-full animate-pulse" />
|
||||||
<span className="text-sm font-medium">Gerando resposta...</span>
|
<span className="text-sm">Gerando resposta...</span>
|
||||||
</div>
|
</div>
|
||||||
) : isStreaming ? (
|
) : isStreaming ? (
|
||||||
// Renderização LEVE durante streaming: texto simples com formatação básica
|
// Renderização LEVE durante streaming: texto simples com formatação básica
|
||||||
// Evita recálculo de ReactMarkdown e syntax highlight a cada token
|
// Evita recálculo de ReactMarkdown e syntax highlight a cada token
|
||||||
<div className={cn(
|
<div className="max-w-none break-words text-sm text-foreground relative">
|
||||||
"prose prose-neutral dark:prose-invert max-w-none break-words leading-7 text-base text-foreground/90",
|
|
||||||
"prose-headings:font-semibold prose-headings:tracking-tight",
|
|
||||||
"relative"
|
|
||||||
)}>
|
|
||||||
<div className="whitespace-pre-wrap font-sans">
|
<div className="whitespace-pre-wrap font-sans">
|
||||||
{processedContent}
|
{processedContent}
|
||||||
</div>
|
</div>
|
||||||
<span className="inline-block w-2 h-4 bg-primary ml-1 animate-pulse rounded-full align-middle" />
|
<span className="inline-block w-2 h-4 bg-primary ml-1 animate-pulse rounded-sm align-middle" />
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
// Renderização COMPLETA quando mensagem finalizada: ReactMarkdown com syntax highlight
|
// Renderização COMPLETA quando mensagem finalizada: ReactMarkdown com syntax highlight
|
||||||
<div className={cn(
|
<div className="max-w-none break-words text-sm text-foreground">
|
||||||
"prose prose-neutral dark:prose-invert max-w-none break-words leading-7 text-base text-foreground/90",
|
|
||||||
"prose-headings:font-semibold prose-headings:tracking-tight prose-h1:text-2xl prose-h2:text-xl prose-h3:text-lg",
|
|
||||||
"prose-p:leading-7 prose-li:leading-7",
|
|
||||||
"prose-pre:bg-muted/50 prose-pre:border prose-pre:border-border/50 prose-pre:rounded-xl",
|
|
||||||
"prose-mark:bg-yellow-200/50 prose-mark:dark:bg-yellow-800/50 prose-mark:px-0.5 prose-mark:rounded"
|
|
||||||
)}>
|
|
||||||
{highlightedContent ? (
|
{highlightedContent ? (
|
||||||
<div dangerouslySetInnerHTML={{ __html: highlightedContent }} />
|
<div dangerouslySetInnerHTML={{ __html: highlightedContent }} />
|
||||||
) : (
|
) : (
|
||||||
@@ -201,8 +176,8 @@ function ChatMessageComponent({ message, isStreaming = false, highlightTerm, hig
|
|||||||
|
|
||||||
{!isUser && !isStreaming && (
|
{!isUser && !isStreaming && (
|
||||||
<div className={cn(
|
<div className={cn(
|
||||||
"absolute -bottom-8 left-12 flex items-center gap-2 opacity-0 transition-opacity duration-200",
|
"absolute -bottom-8 left-12 flex items-center gap-2 opacity-0 transition-opacity duration-150",
|
||||||
"group-hover:opacity-100",
|
"group-hover:opacity-100 group-focus-within:opacity-100",
|
||||||
selected && "opacity-100"
|
selected && "opacity-100"
|
||||||
)}>
|
)}>
|
||||||
<MessageActions content={message.content} role={message.role} />
|
<MessageActions content={message.content} role={message.role} />
|
||||||
|
|||||||
@@ -17,22 +17,22 @@ export function CodeBlock({ language, children }: CodeBlockProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="my-4 rounded-lg border bg-muted/50 overflow-hidden">
|
<div className="my-4 rounded-lg border bg-surface overflow-hidden">
|
||||||
<div className="flex items-center justify-between px-4 py-2 bg-muted/80 border-b">
|
<div className="flex items-center justify-between px-4 py-2 border-b">
|
||||||
<span className="text-xs font-medium text-muted-foreground uppercase">
|
<span className="text-xs font-mono text-muted-foreground">
|
||||||
{language || "text"}
|
{language || "text"}
|
||||||
</span>
|
</span>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
className="h-6 w-6 hover:bg-background/50"
|
className="h-8 w-8 text-muted-foreground hover:text-foreground"
|
||||||
onClick={handleCopy}
|
onClick={handleCopy}
|
||||||
title="Copiar código"
|
title="Copiar código"
|
||||||
>
|
>
|
||||||
{copied ? (
|
{copied ? (
|
||||||
<Check className="h-3.5 w-3.5 text-green-500" />
|
<Check className="h-4 w-4 text-success" />
|
||||||
) : (
|
) : (
|
||||||
<Copy className="h-3.5 w-3.5 text-muted-foreground" />
|
<Copy className="h-4 w-4" />
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -17,17 +17,17 @@ export function ErrorDisplay({ error, onRetry, onDismiss, className }: ErrorDisp
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"mx-4 mb-3 px-4 py-3 rounded-lg border border-red-500/50 bg-red-500/10",
|
"mx-4 mb-3 px-4 py-3 rounded-lg border border-destructive/40 bg-destructive/10",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className="flex items-start gap-3">
|
<div className="flex items-start gap-3">
|
||||||
<AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
|
<AlertCircle className="w-5 h-5 text-destructive flex-shrink-0" />
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="text-sm font-medium text-red-600 dark:text-red-400 mb-1">
|
<div className="text-sm font-medium text-destructive mb-1">
|
||||||
Erro ao processar
|
Erro ao processar
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-red-700 dark:text-red-300 break-words">
|
<p className="text-sm text-foreground break-words">
|
||||||
{errorMessage}
|
{errorMessage}
|
||||||
</p>
|
</p>
|
||||||
{(onRetry || onDismiss) && (
|
{(onRetry || onDismiss) && (
|
||||||
@@ -37,9 +37,9 @@ export function ErrorDisplay({ error, onRetry, onDismiss, className }: ErrorDisp
|
|||||||
size="sm"
|
size="sm"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={onRetry}
|
onClick={onRetry}
|
||||||
className="h-7 text-xs border-red-500/50 text-red-600 dark:text-red-400 hover:bg-red-500/20"
|
className="h-8 text-xs"
|
||||||
>
|
>
|
||||||
<RefreshCw className="w-3 h-3 mr-1.5" />
|
<RefreshCw className="w-3 h-3" />
|
||||||
Tentar novamente
|
Tentar novamente
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
@@ -48,9 +48,9 @@ export function ErrorDisplay({ error, onRetry, onDismiss, className }: ErrorDisp
|
|||||||
size="sm"
|
size="sm"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
onClick={onDismiss}
|
onClick={onDismiss}
|
||||||
className="h-7 text-xs text-red-600 dark:text-red-400 hover:bg-red-500/10"
|
className="h-8 text-xs text-muted-foreground hover:text-foreground"
|
||||||
>
|
>
|
||||||
<X className="w-3 h-3 mr-1.5" />
|
<X className="w-3 h-3" />
|
||||||
Fechar
|
Fechar
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ export const markdownRenderers: Components = {
|
|||||||
h1: ({ className, ...props }) => (
|
h1: ({ className, ...props }) => (
|
||||||
<h1
|
<h1
|
||||||
className={cn(
|
className={cn(
|
||||||
"mt-2 scroll-m-20 text-2xl font-bold tracking-tight first:mt-0",
|
"mt-2 scroll-m-20 text-xl font-semibold tracking-tight first:mt-0",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -15,7 +15,7 @@ export const markdownRenderers: Components = {
|
|||||||
h2: ({ className, ...props }) => (
|
h2: ({ className, ...props }) => (
|
||||||
<h2
|
<h2
|
||||||
className={cn(
|
className={cn(
|
||||||
"mt-6 scroll-m-20 border-b pb-2 text-xl font-semibold tracking-tight first:mt-0",
|
"mt-6 scroll-m-20 border-b pb-2 text-lg font-semibold first:mt-0",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -24,7 +24,7 @@ export const markdownRenderers: Components = {
|
|||||||
h3: ({ className, ...props }) => (
|
h3: ({ className, ...props }) => (
|
||||||
<h3
|
<h3
|
||||||
className={cn(
|
className={cn(
|
||||||
"mt-4 scroll-m-20 text-lg font-semibold tracking-tight",
|
"mt-4 scroll-m-20 text-sm font-semibold",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -33,7 +33,7 @@ export const markdownRenderers: Components = {
|
|||||||
h4: ({ className, ...props }) => (
|
h4: ({ className, ...props }) => (
|
||||||
<h4
|
<h4
|
||||||
className={cn(
|
className={cn(
|
||||||
"mt-4 scroll-m-20 text-base font-semibold tracking-tight",
|
"mt-4 scroll-m-20 text-sm font-semibold text-muted-foreground",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -41,7 +41,7 @@ export const markdownRenderers: Components = {
|
|||||||
),
|
),
|
||||||
p: ({ className, ...props }) => (
|
p: ({ className, ...props }) => (
|
||||||
<p
|
<p
|
||||||
className={cn("leading-7 [&:not(:first-child)]:mt-4", className)}
|
className={cn("leading-normal [&:not(:first-child)]:mt-4", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
@@ -57,7 +57,7 @@ export const markdownRenderers: Components = {
|
|||||||
blockquote: ({ className, ...props }) => (
|
blockquote: ({ className, ...props }) => (
|
||||||
<blockquote
|
<blockquote
|
||||||
className={cn(
|
className={cn(
|
||||||
"mt-4 border-l-2 border-primary pl-6 italic text-muted-foreground",
|
"mt-4 border-l-2 border-border pl-4 italic text-muted-foreground",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -79,14 +79,14 @@ export const markdownRenderers: Components = {
|
|||||||
),
|
),
|
||||||
tr: ({ className, ...props }) => (
|
tr: ({ className, ...props }) => (
|
||||||
<tr
|
<tr
|
||||||
className={cn("m-0 border-t p-0 even:bg-muted", className)}
|
className={cn("m-0 border-t p-0 even:bg-surface", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
th: ({ className, ...props }) => (
|
th: ({ className, ...props }) => (
|
||||||
<th
|
<th
|
||||||
className={cn(
|
className={cn(
|
||||||
"border px-4 py-2 text-left font-bold [&[align=center]]:text-center [&[align=right]]:text-right",
|
"border px-4 py-2 text-left font-semibold [&[align=center]]:text-center [&[align=right]]:text-right",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -110,7 +110,7 @@ export const markdownRenderers: Components = {
|
|||||||
return (
|
return (
|
||||||
<code
|
<code
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",
|
"relative rounded-sm border bg-surface px-1 font-mono text-[0.9em]",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -128,7 +128,7 @@ export const markdownRenderers: Components = {
|
|||||||
},
|
},
|
||||||
a: ({ className, ...props }) => (
|
a: ({ className, ...props }) => (
|
||||||
<a
|
<a
|
||||||
className={cn("font-medium underline underline-offset-4 text-primary hover:text-primary/80", className)}
|
className={cn("font-medium underline underline-offset-4 decoration-muted-foreground hover:decoration-foreground text-foreground transition-colors duration-150", className)}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
{...props}
|
{...props}
|
||||||
|
|||||||
@@ -1,82 +0,0 @@
|
|||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -109,7 +109,7 @@ export function McpJsonEditor({ value, onChange, placeholder, className }: McpJs
|
|||||||
Formatar
|
Formatar
|
||||||
</Button>
|
</Button>
|
||||||
{isFormatted && (
|
{isFormatted && (
|
||||||
<div className="flex items-center gap-1 text-xs text-green-600 dark:text-green-400">
|
<div className="flex items-center gap-1 text-xs text-success">
|
||||||
<CheckCircle2 className="w-3 h-3" />
|
<CheckCircle2 className="w-3 h-3" />
|
||||||
Formatado
|
Formatado
|
||||||
</div>
|
</div>
|
||||||
@@ -124,7 +124,7 @@ export function McpJsonEditor({ value, onChange, placeholder, className }: McpJs
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{isValid && value.trim() && (
|
{isValid && value.trim() && (
|
||||||
<div className="flex items-center gap-1 text-green-600 dark:text-green-400">
|
<div className="flex items-center gap-1 text-success">
|
||||||
<CheckCircle2 className="w-3 h-3" />
|
<CheckCircle2 className="w-3 h-3" />
|
||||||
Válido
|
Válido
|
||||||
</div>
|
</div>
|
||||||
@@ -165,8 +165,8 @@ export function McpJsonEditor({ value, onChange, placeholder, className }: McpJs
|
|||||||
'relative w-full h-full min-h-[300px] p-3 font-mono text-sm leading-6',
|
'relative w-full h-full min-h-[300px] p-3 font-mono text-sm leading-6',
|
||||||
'bg-transparent text-transparent caret-foreground',
|
'bg-transparent text-transparent caret-foreground',
|
||||||
'resize-none border-none outline-none',
|
'resize-none border-none outline-none',
|
||||||
'selection:bg-primary/20',
|
'selection:bg-accent-soft',
|
||||||
'[&::placeholder]:text-muted-foreground/50',
|
'[&::placeholder]:text-muted-foreground',
|
||||||
!isValid && 'ring-1 ring-destructive'
|
!isValid && 'ring-1 ring-destructive'
|
||||||
)}
|
)}
|
||||||
spellCheck={false}
|
spellCheck={false}
|
||||||
|
|||||||
@@ -105,11 +105,11 @@ const runningServers = servers.filter(s => s.status === 'running');
|
|||||||
className="flex items-center justify-between"
|
className="flex items-center justify-between"
|
||||||
>
|
>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<CheckCircle2 className="h-3 w-3 text-green-600 dark:text-green-400" />
|
<CheckCircle2 className="h-3 w-3 text-success" />
|
||||||
<span>{server.name}</span>
|
<span>{server.name}</span>
|
||||||
</div>
|
</div>
|
||||||
{server.toolCount !== undefined && server.toolCount > 0 && (
|
{server.toolCount !== undefined && server.toolCount > 0 && (
|
||||||
<Badge variant="outline" className="ml-2 h-5 px-1.5 text-xs">
|
<Badge variant="outline" className="ml-2 h-5 px-1 text-xs">
|
||||||
{server.toolCount}
|
{server.toolCount}
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import {
|
|||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "@/components/ui/dropdown-menu";
|
} from "@/components/ui/dropdown-menu";
|
||||||
import { Copy, FileJson, FileText, MoreHorizontal, Contrast } from "lucide-react";
|
import { Check, Copy, FileJson, FileText, MoreHorizontal, Contrast } from "lucide-react";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
interface MessageActionsProps {
|
interface MessageActionsProps {
|
||||||
@@ -53,25 +53,25 @@ export function MessageActions({ content, role }: MessageActionsProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
|
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity duration-150">
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
className="h-6 w-6"
|
className="h-8 w-8"
|
||||||
onClick={copyMarkdown}
|
onClick={copyMarkdown}
|
||||||
title="Copiar Markdown"
|
title="Copiar Markdown"
|
||||||
>
|
>
|
||||||
{copied ? (
|
{copied ? (
|
||||||
<span className="text-green-500 text-xs font-bold">✓</span>
|
<Check className="h-4 w-4 text-success" />
|
||||||
) : (
|
) : (
|
||||||
<Copy className="h-3.5 w-3.5 text-muted-foreground" />
|
<Copy className="h-4 w-4 text-muted-foreground" />
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<Button variant="ghost" size="icon" className="h-6 w-6">
|
<Button variant="ghost" size="icon" className="h-8 w-8" aria-label="Mais ações">
|
||||||
<MoreHorizontal className="h-3.5 w-3.5 text-muted-foreground" />
|
<MoreHorizontal className="h-4 w-4 text-muted-foreground" />
|
||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ export function MessageBackground({
|
|||||||
children,
|
children,
|
||||||
...props
|
...props
|
||||||
}: MessageBackgroundProps) {
|
}: MessageBackgroundProps) {
|
||||||
const base = "group flex w-full gap-4 md:gap-6 relative transition-all duration-200";
|
const base = "group flex w-full gap-4 md:gap-6 relative transition-colors duration-150";
|
||||||
|
|
||||||
// User: Fundo sutil, alinhado à direita (se quiséssemos, mas o layout atual é lista).
|
// User: Fundo sutil, alinhado à direita (se quiséssemos, mas o layout atual é lista).
|
||||||
// Vamos manter layout lista mas com estilo clean.
|
// Vamos manter layout lista mas com estilo clean.
|
||||||
@@ -26,10 +26,10 @@ export function MessageBackground({
|
|||||||
|
|
||||||
const roleCl = role === "user"
|
const roleCl = role === "user"
|
||||||
? "bg-transparent text-foreground px-0 py-2" // Minimalista
|
? "bg-transparent text-foreground px-0 py-2" // Minimalista
|
||||||
: "bg-transparent text-foreground/90 px-0 py-2";
|
: "bg-transparent text-foreground px-0 py-2";
|
||||||
|
|
||||||
// Estado de seleção sutil
|
// Estado de seleção sutil
|
||||||
const stateCl = state === "selected" ? "bg-muted/30 -mx-4 px-4 rounded-lg" : "";
|
const stateCl = state === "selected" ? "bg-surface -mx-4 px-4 rounded-lg" : "";
|
||||||
|
|
||||||
const hc = highContrast ? "hc:bg-message-high-contrast hc:text-foreground" : "";
|
const hc = highContrast ? "hc:bg-message-high-contrast hc:text-foreground" : "";
|
||||||
|
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -32,21 +32,21 @@ export function MessageStepThinking({ metadata }: MessageStepThinkingProps) {
|
|||||||
|
|
||||||
switch (metadata.stepType) {
|
switch (metadata.stepType) {
|
||||||
case 'preprocessing':
|
case 'preprocessing':
|
||||||
return <Brain className={cn("w-4 h-4 text-muted-foreground/80", isSpinning && "animate-spin")} />;
|
return <Brain className={cn("w-4 h-4 text-muted-foreground", isSpinning && "animate-spin")} />;
|
||||||
case 'web-research':
|
case 'web-research':
|
||||||
return <Globe className={cn("w-4 h-4 text-muted-foreground/80", isSpinning && "animate-spin")} />;
|
return <Globe className={cn("w-4 h-4 text-muted-foreground", isSpinning && "animate-spin")} />;
|
||||||
case 'sources-found':
|
case 'sources-found':
|
||||||
return <Package className={cn("w-4 h-4 text-muted-foreground/80", isSpinning && "animate-spin")} />;
|
return <Package className={cn("w-4 h-4 text-muted-foreground", isSpinning && "animate-spin")} />;
|
||||||
case 'processing':
|
case 'processing':
|
||||||
return <Brain className={cn("w-4 h-4 text-muted-foreground/80", isSpinning && "animate-spin")} />;
|
return <Brain className={cn("w-4 h-4 text-muted-foreground", isSpinning && "animate-spin")} />;
|
||||||
case 'response-generation':
|
case 'response-generation':
|
||||||
return <Loader2 className={cn("w-4 h-4 text-muted-foreground/80", isSpinning && "animate-spin")} />;
|
return <Loader2 className={cn("w-4 h-4 text-muted-foreground", isSpinning && "animate-spin text-primary")} />;
|
||||||
case 'fallback':
|
case 'fallback':
|
||||||
return <AlertCircle className="w-4 h-4 text-muted-foreground/80" />;
|
return <AlertCircle className="w-4 h-4 text-warning" />;
|
||||||
case 'error':
|
case 'error':
|
||||||
return <XCircle className="w-4 h-4 text-destructive/80" />;
|
return <XCircle className="w-4 h-4 text-destructive" />;
|
||||||
default:
|
default:
|
||||||
return <Search className="w-4 h-4 text-muted-foreground/80" />;
|
return <Search className="w-4 h-4 text-muted-foreground" />;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -61,33 +61,34 @@ export function MessageStepThinking({ metadata }: MessageStepThinkingProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mb-4 ml-10 animate-in fade-in slide-in-from-bottom-2 duration-300">
|
<div className="mb-4 ml-10 animate-in fade-in duration-200 ease-out">
|
||||||
<div className="flex items-center gap-3 p-2 transition-all w-fit max-w-full">
|
<div className="flex items-center gap-3 p-2 w-fit max-w-full">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{getStepIcon()}
|
{getStepIcon()}
|
||||||
<span className={cn(
|
<span className={cn(
|
||||||
"text-sm font-medium",
|
"text-sm font-medium",
|
||||||
metadata.status === 'error'
|
metadata.status === 'error'
|
||||||
? "text-destructive/80"
|
? "text-destructive"
|
||||||
: "text-muted-foreground/80"
|
: "text-muted-foreground"
|
||||||
)}>
|
)}>
|
||||||
{metadata.label}
|
{metadata.label}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{metadata.status === 'running' && (
|
{metadata.status === 'running' && (
|
||||||
<Loader2 className="w-3 h-3 animate-spin text-muted-foreground/50" />
|
<Loader2 className="w-3 h-3 animate-spin text-primary" />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{(metadata.details || metadata.sources || metadata.error) && (
|
{(metadata.details || metadata.sources || metadata.error) && (
|
||||||
<button
|
<button
|
||||||
onClick={() => setIsExpanded(!isExpanded)}
|
onClick={() => setIsExpanded(!isExpanded)}
|
||||||
className="p-1 hover:bg-black/5 dark:hover:bg-white/10 rounded-full transition-colors"
|
className="p-1 rounded-sm text-muted-foreground hover:bg-hover hover:text-foreground transition-colors duration-150"
|
||||||
|
aria-expanded={isExpanded}
|
||||||
>
|
>
|
||||||
{isExpanded ? (
|
{isExpanded ? (
|
||||||
<ChevronUp className="w-3.5 h-3.5 opacity-50" />
|
<ChevronUp className="w-4 h-4" />
|
||||||
) : (
|
) : (
|
||||||
<ChevronDown className="w-3.5 h-3.5 opacity-50" />
|
<ChevronDown className="w-4 h-4" />
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
@@ -95,9 +96,9 @@ export function MessageStepThinking({ metadata }: MessageStepThinkingProps) {
|
|||||||
|
|
||||||
{/* Progress Bar Compacta */}
|
{/* Progress Bar Compacta */}
|
||||||
{metadata.progress !== undefined && metadata.progress < 100 && (
|
{metadata.progress !== undefined && metadata.progress < 100 && (
|
||||||
<div className="ml-1 mt-1 w-32 h-1 bg-muted/50 rounded-full overflow-hidden">
|
<div className="ml-1 mt-1 w-32 h-1 bg-hover rounded-full overflow-hidden">
|
||||||
<div
|
<div
|
||||||
className="h-full bg-primary/50 transition-all duration-300"
|
className="h-full bg-primary"
|
||||||
style={{ width: `${metadata.progress}%` }}
|
style={{ width: `${metadata.progress}%` }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -105,7 +106,7 @@ export function MessageStepThinking({ metadata }: MessageStepThinkingProps) {
|
|||||||
|
|
||||||
{/* Conteúdo Expandido */}
|
{/* Conteúdo Expandido */}
|
||||||
{isExpanded && (
|
{isExpanded && (
|
||||||
<div className="mt-2 ml-1 p-3 border-l-2 border-muted/30 space-y-2 text-sm text-muted-foreground animate-in fade-in">
|
<div className="mt-2 ml-1 p-3 border-l border-border space-y-2 text-sm text-muted-foreground animate-in fade-in duration-150">
|
||||||
{metadata.details && (
|
{metadata.details && (
|
||||||
<div className="whitespace-pre-wrap">{metadata.details}</div>
|
<div className="whitespace-pre-wrap">{metadata.details}</div>
|
||||||
)}
|
)}
|
||||||
@@ -113,11 +114,11 @@ export function MessageStepThinking({ metadata }: MessageStepThinkingProps) {
|
|||||||
{metadata.sources && metadata.sources.length > 0 && (
|
{metadata.sources && metadata.sources.length > 0 && (
|
||||||
<div className="flex flex-wrap gap-2 pt-1">
|
<div className="flex flex-wrap gap-2 pt-1">
|
||||||
{metadata.sources.map((source, idx) => (
|
{metadata.sources.map((source, idx) => (
|
||||||
<div key={idx} className="flex items-center gap-1 bg-background/50 border border-muted/50 px-2 py-1 rounded text-xs max-w-[200px]">
|
<div key={idx} className="flex items-center gap-1 bg-surface border px-2 py-1 rounded-sm text-xs max-w-[200px]">
|
||||||
<ExternalLink className="w-3 h-3 opacity-50" />
|
<ExternalLink className="w-3 h-3 shrink-0" />
|
||||||
<a href={source.url} target="_blank" className="truncate hover:underline flex-1">{source.title || source.url}</a>
|
<a href={source.url} target="_blank" className="truncate text-foreground hover:underline flex-1">{source.title || source.url}</a>
|
||||||
<button onClick={() => copyToClipboard(source.url, idx)} className="ml-1 opacity-50 hover:opacity-100">
|
<button onClick={() => copyToClipboard(source.url, idx)} className="ml-1 rounded-sm hover:text-foreground transition-colors duration-150" aria-label="Copiar URL">
|
||||||
{copiedIndex === idx ? <Check className="w-3 h-3 text-green-500" /> : <Copy className="w-3 h-3" />}
|
{copiedIndex === idx ? <Check className="w-3 h-3 text-success" /> : <Copy className="w-3 h-3" />}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
@@ -125,7 +126,7 @@ export function MessageStepThinking({ metadata }: MessageStepThinkingProps) {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{metadata.error && (
|
{metadata.error && (
|
||||||
<div className="text-red-500 font-medium flex items-center gap-2">
|
<div className="text-destructive font-medium flex items-center gap-2">
|
||||||
<XCircle className="w-4 h-4" />
|
<XCircle className="w-4 h-4" />
|
||||||
{metadata.error}
|
{metadata.error}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,286 +0,0 @@
|
|||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -4,7 +4,7 @@ import { Input } from "@/components/ui/input";
|
|||||||
import { Progress } from "@/components/ui/progress";
|
import { Progress } from "@/components/ui/progress";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import { Download, Loader2, X, Upload, Globe, AlertCircle, File } from "lucide-react";
|
import { Download, Loader2, X, Upload, Globe, AlertCircle, File, Info } from "lucide-react";
|
||||||
import { useState, useEffect, useRef } from "react";
|
import { useState, useEffect, useRef } from "react";
|
||||||
import { invoke } from "@tauri-apps/api/core";
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
import { listen } from "@tauri-apps/api/event";
|
import { listen } from "@tauri-apps/api/event";
|
||||||
@@ -368,7 +368,7 @@ export function ModelDownloadDialog({ open, onOpenChange, onSuccess }: ModelDown
|
|||||||
<p className="text-sm text-destructive">{error}</p>
|
<p className="text-sm text-destructive">{error}</p>
|
||||||
)}
|
)}
|
||||||
{isInstalled && !isDownloading && (
|
{isInstalled && !isDownloading && (
|
||||||
<p className="text-sm text-green-600 dark:text-green-400">
|
<p className="text-sm text-success">
|
||||||
✓ Este modelo já está instalado
|
✓ Este modelo já está instalado
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
@@ -397,7 +397,7 @@ export function ModelDownloadDialog({ open, onOpenChange, onSuccess }: ModelDown
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{isInstalled && !isDownloading && (
|
{isInstalled && !isDownloading && (
|
||||||
<div className="bg-muted/50 p-3 rounded-md text-sm">
|
<div className="bg-surface border p-3 rounded-md text-sm">
|
||||||
<p className="text-muted-foreground">
|
<p className="text-muted-foreground">
|
||||||
O modelo está instalado e pronto para uso.
|
O modelo está instalado e pronto para uso.
|
||||||
</p>
|
</p>
|
||||||
@@ -423,7 +423,7 @@ export function ModelDownloadDialog({ open, onOpenChange, onSuccess }: ModelDown
|
|||||||
|
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{isInstallingLocal ? (
|
{isInstallingLocal ? (
|
||||||
<div className="border rounded-xl p-6 bg-muted/30 space-y-4">
|
<div className="border rounded-lg p-6 bg-surface space-y-4">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Loader2 className="w-5 h-5 animate-spin text-primary" />
|
<Loader2 className="w-5 h-5 animate-spin text-primary" />
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
@@ -445,7 +445,7 @@ export function ModelDownloadDialog({ open, onOpenChange, onSuccess }: ModelDown
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<div className="border-2 border-dashed rounded-xl p-8 text-center bg-muted/30">
|
<div className="border-2 border-dashed rounded-lg p-8 text-center bg-surface">
|
||||||
<Upload className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
|
<Upload className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
|
||||||
<p className="text-sm text-muted-foreground mb-4">
|
<p className="text-sm text-muted-foreground mb-4">
|
||||||
Selecione um arquivo GGUF para instalar localmente
|
Selecione um arquivo GGUF para instalar localmente
|
||||||
@@ -475,8 +475,8 @@ export function ModelDownloadDialog({ open, onOpenChange, onSuccess }: ModelDown
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-muted/30 border border-border/50 rounded-lg p-3 text-xs text-muted-foreground">
|
<div className="bg-surface border rounded-md p-3 text-xs text-muted-foreground">
|
||||||
<p className="font-medium mb-1">ℹ️ Modelos instalados localmente</p>
|
<p className="flex items-center gap-1 font-medium text-foreground mb-1"><Info className="w-3 h-3" aria-hidden="true" />Modelos instalados localmente</p>
|
||||||
<p>Funcionam sem conexão à internet. O arquivo será copiado para o diretório do Ollama.</p>
|
<p>Funcionam sem conexão à internet. O arquivo será copiado para o diretório do Ollama.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -33,9 +33,9 @@ export function PostProcessingPanel({ steps, className }: PostProcessingPanelPro
|
|||||||
const getStepIcon = (step: ProcessStep) => {
|
const getStepIcon = (step: ProcessStep) => {
|
||||||
switch (step.status) {
|
switch (step.status) {
|
||||||
case 'completed':
|
case 'completed':
|
||||||
return <CheckCircle2 className="w-4 h-4 text-green-600 dark:text-green-400" />;
|
return <CheckCircle2 className="w-4 h-4 text-success" />;
|
||||||
case 'error':
|
case 'error':
|
||||||
return <XCircle className="w-4 h-4 text-red-600 dark:text-red-400" />;
|
return <XCircle className="w-4 h-4 text-destructive" />;
|
||||||
case 'running':
|
case 'running':
|
||||||
return <Loader2 className="w-4 h-4 text-primary animate-spin" />;
|
return <Loader2 className="w-4 h-4 text-primary animate-spin" />;
|
||||||
default:
|
default:
|
||||||
@@ -50,19 +50,20 @@ export function PostProcessingPanel({ steps, className }: PostProcessingPanelPro
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn("border-t border-muted bg-muted/20", className)}>
|
<div className={cn("border-t bg-surface", className)}>
|
||||||
<button
|
<button
|
||||||
onClick={() => setIsExpanded(!isExpanded)}
|
onClick={() => setIsExpanded(!isExpanded)}
|
||||||
className="w-full px-6 py-3 flex items-center justify-between hover:bg-muted/40 transition-colors"
|
className="w-full px-6 py-3 flex items-center justify-between hover:bg-hover transition-colors duration-150"
|
||||||
|
aria-expanded={isExpanded}
|
||||||
>
|
>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="flex items-center gap-1.5">
|
<div className="flex items-center gap-2">
|
||||||
{hasErrors ? (
|
{hasErrors ? (
|
||||||
<AlertCircle className="w-4 h-4 text-red-600 dark:text-red-400" />
|
<AlertCircle className="w-4 h-4 text-destructive" />
|
||||||
) : isRunning ? (
|
) : isRunning ? (
|
||||||
<Loader2 className="w-4 h-4 text-primary animate-spin" />
|
<Loader2 className="w-4 h-4 text-primary animate-spin" />
|
||||||
) : (
|
) : (
|
||||||
<CheckCircle2 className="w-4 h-4 text-green-600 dark:text-green-400" />
|
<CheckCircle2 className="w-4 h-4 text-success" />
|
||||||
)}
|
)}
|
||||||
<span className="text-sm font-medium">
|
<span className="text-sm font-medium">
|
||||||
Processo de Pensamento
|
Processo de Pensamento
|
||||||
@@ -85,11 +86,11 @@ export function PostProcessingPanel({ steps, className }: PostProcessingPanelPro
|
|||||||
<div
|
<div
|
||||||
key={step.id}
|
key={step.id}
|
||||||
className={cn(
|
className={cn(
|
||||||
"p-3 rounded-lg border transition-all",
|
"p-3 rounded-lg border",
|
||||||
step.status === 'completed' && "bg-green-500/5 border-green-500/20",
|
step.status === 'completed' && "bg-background",
|
||||||
step.status === 'error' && "bg-red-500/5 border-red-500/20",
|
step.status === 'error' && "bg-destructive/10 border-destructive/30",
|
||||||
step.status === 'running' && "bg-primary/5 border-primary/20",
|
step.status === 'running' && "bg-accent-soft border-transparent",
|
||||||
step.status === 'pending' && "bg-muted/50 border-muted"
|
step.status === 'pending' && "bg-background"
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className="flex items-start justify-between gap-3">
|
<div className="flex items-start justify-between gap-3">
|
||||||
@@ -110,7 +111,7 @@ export function PostProcessingPanel({ steps, className }: PostProcessingPanelPro
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{step.error && (
|
{step.error && (
|
||||||
<p className="text-xs text-red-600 dark:text-red-400 mt-1">
|
<p className="text-xs text-destructive mt-1">
|
||||||
{step.error}
|
{step.error}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -33,37 +33,31 @@ export function ProcessingIndicator({
|
|||||||
key: ProcessingStep;
|
key: ProcessingStep;
|
||||||
label: string;
|
label: string;
|
||||||
icon: React.ReactNode;
|
icon: React.ReactNode;
|
||||||
emoji: string;
|
|
||||||
}> = [
|
}> = [
|
||||||
{
|
{
|
||||||
key: 'collecting',
|
key: 'collecting',
|
||||||
label: 'Coletando Dados',
|
label: 'Coletando Dados',
|
||||||
icon: <Search className="w-4 h-4" />,
|
icon: <Search className="w-4 h-4" />,
|
||||||
emoji: '🔍',
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'processing',
|
key: 'processing',
|
||||||
label: 'Processando...',
|
label: 'Processando...',
|
||||||
icon: <Brain className="w-4 h-4" />,
|
icon: <Brain className="w-4 h-4" />,
|
||||||
emoji: '🤖',
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'searching',
|
key: 'searching',
|
||||||
label: sourcesCount > 0 ? `Buscando na Web (${sourcesCount} fontes)...` : 'Buscando na Web...',
|
label: sourcesCount > 0 ? `Buscando na Web (${sourcesCount} fontes)...` : 'Buscando na Web...',
|
||||||
icon: <Globe className="w-4 h-4" />,
|
icon: <Globe className="w-4 h-4" />,
|
||||||
emoji: '🌐',
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'preparing',
|
key: 'preparing',
|
||||||
label: 'Preparando Contexto',
|
label: 'Preparando Contexto',
|
||||||
icon: <Package className="w-4 h-4" />,
|
icon: <Package className="w-4 h-4" />,
|
||||||
emoji: '📦',
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'streaming',
|
key: 'streaming',
|
||||||
label: 'Gerando Resposta...',
|
label: 'Gerando Resposta...',
|
||||||
icon: <Loader2 className="w-4 h-4 animate-spin" />,
|
icon: <Loader2 className="w-4 h-4 animate-spin" />,
|
||||||
emoji: '💬',
|
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -73,24 +67,15 @@ export function ProcessingIndicator({
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"mx-4 mb-3 px-4 py-3 rounded-lg border border-muted/50 bg-muted/20 transition-all duration-300",
|
"mx-4 mb-3 px-4 py-3 rounded-lg border bg-surface transition-[opacity,transform] duration-200 ease-out",
|
||||||
isVisible ? "opacity-100 translate-y-0" : "opacity-0 -translate-y-2"
|
isVisible ? "opacity-100 translate-y-0" : "opacity-0 -translate-y-2"
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{/* Card de Status Atual */}
|
{/* Card de Status Atual */}
|
||||||
<div className="flex items-center gap-3 mb-3">
|
<div className="flex items-center gap-3 mb-3">
|
||||||
<div className="flex-shrink-0">
|
<div className="flex-shrink-0">
|
||||||
<div className="relative w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
|
<div className="w-10 h-10 rounded-full bg-accent-soft text-foreground flex items-center justify-center">
|
||||||
{currentStep === 'collecting' && (
|
{currentStepData.icon}
|
||||||
<div className="absolute inset-0 rounded-full border-2 border-primary/30 animate-ping" />
|
|
||||||
)}
|
|
||||||
{currentStep === 'processing' && (
|
|
||||||
<div className="absolute inset-0 rounded-full border-2 border-primary/30 animate-pulse" />
|
|
||||||
)}
|
|
||||||
{currentStep === 'searching' && (
|
|
||||||
<div className="absolute inset-0 rounded-full border-2 border-primary/30 animate-spin" style={{ animationDuration: '2s' }} />
|
|
||||||
)}
|
|
||||||
<span className="text-xl relative z-10">{currentStepData.emoji}</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
@@ -98,9 +83,9 @@ export function ProcessingIndicator({
|
|||||||
{currentStepData.label}
|
{currentStepData.label}
|
||||||
</div>
|
</div>
|
||||||
{progress > 0 && progress < 100 && (
|
{progress > 0 && progress < 100 && (
|
||||||
<div className="mt-1.5 h-1.5 bg-muted rounded-full overflow-hidden">
|
<div className="mt-2 h-1 bg-hover rounded-full overflow-hidden">
|
||||||
<div
|
<div
|
||||||
className="h-full bg-primary transition-all duration-300 ease-out"
|
className="h-full bg-primary"
|
||||||
style={{ width: `${progress}%` }}
|
style={{ width: `${progress}%` }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -115,13 +100,13 @@ export function ProcessingIndicator({
|
|||||||
const isPast = idx < currentStepIndex;
|
const isPast = idx < currentStepIndex;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={step.key} className="flex items-center gap-1.5">
|
<div key={step.key} className="flex items-center gap-1">
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex items-center justify-center w-6 h-6 rounded-full transition-all duration-300",
|
"flex items-center justify-center w-6 h-6 rounded-full transition-colors duration-150",
|
||||||
isPast && "bg-green-500/20 text-green-600 dark:text-green-400",
|
isPast && "bg-success/15 text-success",
|
||||||
isActive && "bg-primary/20 text-primary animate-pulse",
|
isActive && "bg-accent-soft text-foreground",
|
||||||
!isActive && !isPast && "bg-muted text-muted-foreground"
|
!isActive && !isPast && "bg-hover text-muted-foreground"
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{isPast ? (
|
{isPast ? (
|
||||||
@@ -134,15 +119,15 @@ export function ProcessingIndicator({
|
|||||||
</div>
|
</div>
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
"transition-colors duration-300",
|
"transition-colors duration-150",
|
||||||
isActive && "text-foreground font-medium",
|
isActive && "text-foreground font-medium",
|
||||||
isPast && "text-muted-foreground opacity-60"
|
isPast && "text-muted-foreground"
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{step.label.split(' ')[0]} {/* Mostrar apenas primeira palavra na timeline */}
|
{step.label.split(' ')[0]} {/* Mostrar apenas primeira palavra na timeline */}
|
||||||
</span>
|
</span>
|
||||||
{idx < currentStepIndex && (
|
{idx < currentStepIndex && (
|
||||||
<div className="w-6 h-px bg-muted mx-1" />
|
<div className="w-6 h-px bg-border mx-1" />
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -159,10 +144,10 @@ export function ProcessingIndicator({
|
|||||||
<div key={step.key} className="flex items-center gap-2">
|
<div key={step.key} className="flex items-center gap-2">
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex items-center justify-center w-5 h-5 rounded-full transition-all",
|
"flex items-center justify-center w-5 h-5 rounded-full transition-colors duration-150",
|
||||||
isPast && "bg-green-500/20 text-green-600 dark:text-green-400",
|
isPast && "bg-success/15 text-success",
|
||||||
isActive && "bg-primary/20 text-primary animate-pulse",
|
isActive && "bg-accent-soft text-foreground",
|
||||||
!isActive && !isPast && "bg-muted text-muted-foreground"
|
!isActive && !isPast && "bg-hover text-muted-foreground"
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{isPast ? (
|
{isPast ? (
|
||||||
@@ -175,9 +160,9 @@ export function ProcessingIndicator({
|
|||||||
</div>
|
</div>
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
"text-xs transition-colors",
|
"text-xs transition-colors duration-150",
|
||||||
isActive && "text-foreground font-medium",
|
isActive && "text-foreground font-medium",
|
||||||
isPast && "text-muted-foreground opacity-60"
|
isPast && "text-muted-foreground"
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{step.label}
|
{step.label}
|
||||||
|
|||||||
@@ -1,112 +0,0 @@
|
|||||||
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('');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -76,7 +76,7 @@ export function PromptGeneratorDialog({ defaultModel, onPromptGenerated }: Promp
|
|||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={setOpen}>
|
<Dialog open={open} onOpenChange={setOpen}>
|
||||||
<DialogTrigger asChild>
|
<DialogTrigger asChild>
|
||||||
<Button variant="ghost" size="icon" className="h-6 w-6 text-yellow-500 hover:text-yellow-600 hover:bg-yellow-100 dark:hover:bg-yellow-900/20" title="Gerar com IA">
|
<Button variant="ghost" size="icon" className="h-8 w-8 text-muted-foreground hover:text-foreground" title="Gerar com IA">
|
||||||
<Sparkles className="w-4 h-4" />
|
<Sparkles className="w-4 h-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
@@ -119,7 +119,7 @@ export function PromptGeneratorDialog({ defaultModel, onPromptGenerated }: Promp
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
<SelectContent className="max-w-[90vw]">
|
<SelectContent className="max-w-[90vw]">
|
||||||
{models.length === 0 ? (
|
{models.length === 0 ? (
|
||||||
<SelectItem value="__sem-modelos__" disabled>Nenhum modelo disponível</SelectItem>
|
<SelectItem value="" disabled>Nenhum modelo disponível</SelectItem>
|
||||||
) : (
|
) : (
|
||||||
models.map(m => (
|
models.map(m => (
|
||||||
<Tooltip key={m.name}>
|
<Tooltip key={m.name}>
|
||||||
|
|||||||
@@ -38,27 +38,27 @@ export function ReasoningChain({ steps, searchQueries = [], className }: Reasoni
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isCompleted) {
|
if (isCompleted) {
|
||||||
return <CheckCircle2 className="w-3.5 h-3.5 text-muted-foreground/60" />;
|
return <CheckCircle2 className="w-4 h-4 text-muted-foreground" />;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isRunning) {
|
if (isRunning) {
|
||||||
return <Loader2 className="w-3.5 h-3.5 text-muted-foreground/60 animate-spin" />;
|
return <Loader2 className="w-4 h-4 text-primary animate-spin" />;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ícone baseado no tipo de step
|
// Ícone baseado no tipo de step
|
||||||
switch (step.stepType) {
|
switch (step.stepType) {
|
||||||
case 'preprocessing':
|
case 'preprocessing':
|
||||||
return <Brain className="w-3.5 h-3.5 text-muted-foreground/60" />;
|
return <Brain className="w-4 h-4 text-muted-foreground" />;
|
||||||
case 'web-research':
|
case 'web-research':
|
||||||
return <Search className="w-3.5 h-3.5 text-muted-foreground/60" />;
|
return <Search className="w-4 h-4 text-muted-foreground" />;
|
||||||
case 'sources-found':
|
case 'sources-found':
|
||||||
return <Globe className="w-3.5 h-3.5 text-muted-foreground/60" />;
|
return <Globe className="w-4 h-4 text-muted-foreground" />;
|
||||||
case 'processing':
|
case 'processing':
|
||||||
return <Brain className="w-3.5 h-3.5 text-muted-foreground/60" />;
|
return <Brain className="w-4 h-4 text-muted-foreground" />;
|
||||||
case 'response-generation':
|
case 'response-generation':
|
||||||
return <Loader2 className="w-3.5 h-3.5 text-muted-foreground/60 animate-spin" />;
|
return <Loader2 className="w-4 h-4 text-primary animate-spin" />;
|
||||||
default:
|
default:
|
||||||
return <Search className="w-3.5 h-3.5 text-muted-foreground/60" />;
|
return <Search className="w-4 h-4 text-muted-foreground" />;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -66,12 +66,12 @@ export function ReasoningChain({ steps, searchQueries = [], className }: Reasoni
|
|||||||
<div className={cn("mb-6 space-y-3", className)}>
|
<div className={cn("mb-6 space-y-3", className)}>
|
||||||
{/* Header: "Working..." com spinner sutil */}
|
{/* Header: "Working..." com spinner sutil */}
|
||||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||||
<Circle className="w-2 h-2 fill-current animate-pulse" />
|
<Circle className="w-2 h-2 fill-current text-primary animate-pulse" />
|
||||||
<span>Working...</span>
|
<span>Working...</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Lista vertical de steps - texto simples */}
|
{/* Lista vertical de steps - texto simples */}
|
||||||
<div className="space-y-1.5 pl-6">
|
<div className="space-y-1 pl-6">
|
||||||
{steps.map((step, index) => {
|
{steps.map((step, index) => {
|
||||||
const isRunning = step.status === 'running';
|
const isRunning = step.status === 'running';
|
||||||
const isCompleted = step.status === 'completed';
|
const isCompleted = step.status === 'completed';
|
||||||
@@ -83,17 +83,17 @@ export function ReasoningChain({ steps, searchQueries = [], className }: Reasoni
|
|||||||
className={cn(
|
className={cn(
|
||||||
"reasoning-step flex items-center gap-2 text-sm",
|
"reasoning-step flex items-center gap-2 text-sm",
|
||||||
isError
|
isError
|
||||||
? "text-destructive/80"
|
? "text-destructive"
|
||||||
: isCompleted
|
: isCompleted
|
||||||
? "text-muted-foreground/60"
|
? "text-muted-foreground"
|
||||||
: "text-muted-foreground/80"
|
: "text-foreground"
|
||||||
)}
|
)}
|
||||||
style={{ animationDelay: `${index * 100}ms` }}
|
style={{ animationDelay: `${index * 50}ms` }}
|
||||||
>
|
>
|
||||||
{getStepIcon(step)}
|
{getStepIcon(step)}
|
||||||
<span>{step.label}</span>
|
<span>{step.label}</span>
|
||||||
{step.details && (
|
{step.details && (
|
||||||
<span className="text-xs text-muted-foreground/50 ml-1">
|
<span className="text-xs text-muted-foreground ml-1">
|
||||||
{step.details}
|
{step.details}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
@@ -105,11 +105,11 @@ export function ReasoningChain({ steps, searchQueries = [], className }: Reasoni
|
|||||||
{/* Pills de busca - cápsulas sutis */}
|
{/* Pills de busca - cápsulas sutis */}
|
||||||
{searchQueries.length > 0 && (
|
{searchQueries.length > 0 && (
|
||||||
<div className="flex flex-wrap gap-2 pl-6">
|
<div className="flex flex-wrap gap-2 pl-6">
|
||||||
<span className="text-xs text-muted-foreground/60">Searching:</span>
|
<span className="text-xs text-muted-foreground">Searching:</span>
|
||||||
{searchQueries.map((query, index) => (
|
{searchQueries.map((query, index) => (
|
||||||
<span
|
<span
|
||||||
key={index}
|
key={index}
|
||||||
className="text-xs font-mono px-2 py-1 bg-white/5 dark:bg-white/5 border border-white/10 dark:border-white/10 rounded-full text-muted-foreground/70"
|
className="text-xs font-mono px-2 py-1 bg-surface border rounded-sm text-muted-foreground"
|
||||||
>
|
>
|
||||||
{query}
|
{query}
|
||||||
</span>
|
</span>
|
||||||
@@ -121,7 +121,7 @@ export function ReasoningChain({ steps, searchQueries = [], className }: Reasoni
|
|||||||
{allSources.length > 0 && (
|
{allSources.length > 0 && (
|
||||||
<div className="pl-6">
|
<div className="pl-6">
|
||||||
<div className="flex items-center gap-2 mb-2">
|
<div className="flex items-center gap-2 mb-2">
|
||||||
<span className="text-xs text-muted-foreground/60">
|
<span className="text-xs text-muted-foreground">
|
||||||
Reviewing sources - {allSources.length}
|
Reviewing sources - {allSources.length}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -73,8 +73,8 @@ export function SearchProgress({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn(
|
<div className={cn(
|
||||||
"mx-6 mb-2 transition-all",
|
"mx-6 mb-2",
|
||||||
status === 'completed' && "opacity-70 hover:opacity-100",
|
status === 'completed' && "text-muted-foreground",
|
||||||
status === 'error' && "text-destructive"
|
status === 'error' && "text-destructive"
|
||||||
)}>
|
)}>
|
||||||
<div className="p-2 pl-3 border-l-2 border-muted flex items-center justify-between gap-2 text-xs">
|
<div className="p-2 pl-3 border-l-2 border-muted flex items-center justify-between gap-2 text-xs">
|
||||||
@@ -115,12 +115,12 @@ export function SearchProgress({
|
|||||||
{sources.map((source, idx) => (
|
{sources.map((source, idx) => (
|
||||||
<div
|
<div
|
||||||
key={idx}
|
key={idx}
|
||||||
className="flex items-start gap-2 p-2 rounded-md bg-muted/30 hover:bg-muted/50 transition-colors"
|
className="flex items-start gap-2 p-2 rounded-md bg-surface hover:bg-hover transition-colors duration-150"
|
||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
src={getFaviconUrl(source.url)}
|
src={getFaviconUrl(source.url)}
|
||||||
alt=""
|
alt=""
|
||||||
className="w-4 h-4 rounded mt-0.5 flex-shrink-0"
|
className="w-4 h-4 rounded-sm flex-shrink-0"
|
||||||
onError={(e) => {
|
onError={(e) => {
|
||||||
(e.target as HTMLImageElement).style.display = 'none';
|
(e.target as HTMLImageElement).style.display = 'none';
|
||||||
}}
|
}}
|
||||||
@@ -130,7 +130,7 @@ export function SearchProgress({
|
|||||||
href={source.url}
|
href={source.url}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="text-xs font-medium text-primary hover:underline line-clamp-1 flex items-center gap-1"
|
className="text-xs font-medium text-foreground hover:underline line-clamp-1 flex items-center gap-1"
|
||||||
>
|
>
|
||||||
{source.title || source.url}
|
{source.title || source.url}
|
||||||
<ExternalLink className="w-3 h-3 flex-shrink-0" />
|
<ExternalLink className="w-3 h-3 flex-shrink-0" />
|
||||||
|
|||||||
@@ -1,172 +0,0 @@
|
|||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -106,26 +106,26 @@ export function SidebarList({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<TooltipProvider delayDuration={300}>
|
<TooltipProvider delayDuration={300}>
|
||||||
<div className="flex flex-col h-full border-r border-sidebar-border bg-sidebar w-full overflow-x-hidden">
|
<div className="flex flex-col h-full border-r border-border bg-surface w-full overflow-x-hidden">
|
||||||
{/* Header com busca e botão Nova Conversa */}
|
{/* Header com busca e botão Nova Conversa */}
|
||||||
<div className="p-3 border-b border-sidebar-border flex-shrink-0 space-y-2.5">
|
<div className="p-3 border-b border-border flex-shrink-0 space-y-2">
|
||||||
{/* Campo de busca */}
|
{/* Campo de busca */}
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||||
<Input
|
<Input
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="Buscar conversas..."
|
placeholder="Buscar conversas..."
|
||||||
value={localSearchInput}
|
value={localSearchInput}
|
||||||
onChange={(e) => setLocalSearchInput(e.target.value)}
|
onChange={(e) => setLocalSearchInput(e.target.value)}
|
||||||
className="pl-8 pr-8 h-9 text-sm"
|
className="pl-9 pr-9 h-9 text-sm"
|
||||||
/>
|
/>
|
||||||
{isSearching && (
|
{isSearching && (
|
||||||
<Loader2 className="absolute right-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground animate-spin" />
|
<Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-primary animate-spin" />
|
||||||
)}
|
)}
|
||||||
{localSearchInput && !isSearching && (
|
{localSearchInput && !isSearching && (
|
||||||
<button
|
<button
|
||||||
onClick={handleClearSearch}
|
onClick={handleClearSearch}
|
||||||
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
|
className="absolute right-3 top-1/2 -translate-y-1/2 rounded-sm text-muted-foreground hover:text-foreground transition-colors duration-150"
|
||||||
aria-label="Limpar busca"
|
aria-label="Limpar busca"
|
||||||
>
|
>
|
||||||
<X className="w-4 h-4" />
|
<X className="w-4 h-4" />
|
||||||
@@ -145,15 +145,15 @@ export function SidebarList({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Lista de chats com scroll customizado */}
|
{/* Lista de chats com scroll customizado */}
|
||||||
<div className="flex-1 overflow-y-auto min-h-0 sidebar-chat-list">
|
<div className="flex-1 overflow-y-auto min-h-0">
|
||||||
<div className="p-2 space-y-1.5">
|
<div className="p-2 space-y-1">
|
||||||
{sessions.length === 0 && (
|
{sessions.length === 0 && (
|
||||||
<div className="flex flex-col items-center justify-center py-12 px-4 text-center">
|
<div className="flex flex-col items-center justify-center py-12 px-4 text-center">
|
||||||
<MessageSquare className="w-10 h-10 text-muted-foreground/40 mb-3" />
|
<MessageSquare className="w-8 h-8 text-muted-foreground mb-3" />
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
{searchQuery ? 'Nenhuma conversa encontrada' : 'Nenhuma conversa salva'}
|
{searchQuery ? 'Nenhuma conversa encontrada' : 'Nenhuma conversa salva'}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-xs text-muted-foreground/70 mt-1">
|
<p className="text-xs text-muted-foreground mt-1">
|
||||||
{searchQuery
|
{searchQuery
|
||||||
? 'Tente buscar por outro termo'
|
? 'Tente buscar por outro termo'
|
||||||
: 'Comece uma nova conversa para começar'}
|
: 'Comece uma nova conversa para começar'}
|
||||||
@@ -170,11 +170,8 @@ export function SidebarList({
|
|||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"sidebar-chat-item group relative bg-card border rounded-lg cursor-pointer transition-all duration-200",
|
"sidebar-chat-item group relative rounded-md cursor-pointer transition-colors duration-150",
|
||||||
"hover:shadow-md hover:border-primary/20 hover:-translate-y-0.5",
|
isSelected ? "bg-accent-soft" : "hover:bg-hover"
|
||||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
|
||||||
isSelected && "border-primary/40 shadow-sm bg-accent/50",
|
|
||||||
"active:scale-[0.98]"
|
|
||||||
)}
|
)}
|
||||||
onClick={() => onSelectSession(session.id)}
|
onClick={() => onSelectSession(session.id)}
|
||||||
role="button"
|
role="button"
|
||||||
@@ -187,15 +184,15 @@ export function SidebarList({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{/* Conteúdo do card */}
|
{/* Conteúdo do card */}
|
||||||
<div className="sidebar-chat-item-content p-2.5">
|
<div className="sidebar-chat-item-content p-2">
|
||||||
{/* Ícone/Emoji */}
|
{/* Ícone/Emoji */}
|
||||||
<div className="shrink-0 flex items-center justify-center w-8 h-8 rounded-md bg-muted/50 text-base">
|
<div className="shrink-0 flex items-center justify-center w-8 h-8 rounded-md bg-background/60 text-base text-muted-foreground">
|
||||||
{session.emoji || '💬'}
|
{session.emoji || <MessageSquare className="w-4 h-4" />}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Texto do card */}
|
{/* Texto do card */}
|
||||||
<div className="sidebar-chat-item-text flex-1 min-w-0">
|
<div className="sidebar-chat-item-text flex-1 min-w-0">
|
||||||
<h3 className="sidebar-chat-item-title text-sm font-medium text-card-foreground leading-tight mb-0.5">
|
<h3 className="sidebar-chat-item-title text-sm font-medium text-foreground leading-tight">
|
||||||
{session.title}
|
{session.title}
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
@@ -204,7 +201,7 @@ export function SidebarList({
|
|||||||
{formatDate(session.updated_at)}
|
{formatDate(session.updated_at)}
|
||||||
</p>
|
</p>
|
||||||
{searchQuery && session.match_count !== undefined && session.match_count > 0 && (
|
{searchQuery && session.match_count !== undefined && session.match_count > 0 && (
|
||||||
<span className="text-xs px-1.5 py-0.5 rounded bg-primary/10 text-primary font-medium">
|
<span className="text-xs px-1 rounded-sm bg-accent-soft text-foreground font-medium">
|
||||||
{session.match_count} {session.match_count === 1 ? 'ocorrência' : 'ocorrências'}
|
{session.match_count} {session.match_count === 1 ? 'ocorrência' : 'ocorrências'}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
@@ -213,7 +210,7 @@ export function SidebarList({
|
|||||||
|
|
||||||
{/* Navegação de matches - aparece apenas quando selecionado e há busca ativa */}
|
{/* Navegação de matches - aparece apenas quando selecionado e há busca ativa */}
|
||||||
{isSelected && searchQuery && session.match_count !== undefined && session.match_count > 0 && onNavigateMatch && (
|
{isSelected && searchQuery && session.match_count !== undefined && session.match_count > 0 && onNavigateMatch && (
|
||||||
<div className="flex flex-col gap-0.5 mr-1">
|
<div className="flex flex-col gap-1 mr-1">
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
@@ -248,10 +245,9 @@ export function SidebarList({
|
|||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
className={cn(
|
className={cn(
|
||||||
"h-7 w-7 shrink-0 transition-all duration-200",
|
"h-8 w-8 shrink-0 transition-opacity duration-150",
|
||||||
"opacity-0 group-hover:opacity-100",
|
"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100",
|
||||||
"hover:bg-destructive/10 hover:text-destructive",
|
"hover:bg-destructive/10 hover:text-destructive"
|
||||||
"active:scale-95"
|
|
||||||
)}
|
)}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
@@ -263,11 +259,6 @@ export function SidebarList({
|
|||||||
<Trash2 className="w-3.5 h-3.5" />
|
<Trash2 className="w-3.5 h-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Indicador de seleção */}
|
|
||||||
{isSelected && (
|
|
||||||
<div className="absolute left-0 top-0 bottom-0 w-1 bg-primary rounded-l-lg" />
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
{showTooltip && (
|
{showTooltip && (
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ export function SourcesCarousel({ sources }: SourcesCarouselProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full max-w-3xl mx-auto mb-4 mt-2">
|
<div className="w-full max-w-3xl mx-auto mb-4 mt-2">
|
||||||
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-3 px-1">
|
<h3 className="text-xs font-medium text-muted-foreground mb-3 px-1">
|
||||||
Fontes Analisadas
|
Fontes Analisadas
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
@@ -121,10 +121,10 @@ export function SourcesCarousel({ sources }: SourcesCarouselProps) {
|
|||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
onClick={handleLinkClick}
|
onClick={handleLinkClick}
|
||||||
className="flex-none w-40 group transition-all hover:-translate-y-1 block"
|
className="flex-none w-40 group block rounded-lg"
|
||||||
style={{ pointerEvents: (isDragging || hasMoved) ? 'none' : 'auto' }}
|
style={{ pointerEvents: (isDragging || hasMoved) ? 'none' : 'auto' }}
|
||||||
>
|
>
|
||||||
<Card className="h-24 p-3 flex flex-col justify-between hover:shadow-md hover:border-primary/20 transition-colors bg-card/50 backdrop-blur-sm cursor-pointer overflow-hidden">
|
<Card className="h-24 p-3 flex flex-col justify-between hover:bg-hover transition-colors duration-150 cursor-pointer overflow-hidden">
|
||||||
<div className="flex items-start justify-between min-h-0 flex-shrink-0">
|
<div className="flex items-start justify-between min-h-0 flex-shrink-0">
|
||||||
<img
|
<img
|
||||||
src={faviconUrl}
|
src={faviconUrl}
|
||||||
@@ -136,10 +136,10 @@ export function SourcesCarousel({ sources }: SourcesCarouselProps) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-1 min-w-0 flex-1 overflow-hidden flex flex-col justify-end">
|
<div className="space-y-1 min-w-0 flex-1 overflow-hidden flex flex-col justify-end">
|
||||||
<div className="text-xs font-medium leading-tight line-clamp-2 text-card-foreground/90 group-hover:text-primary transition-colors break-words overflow-hidden text-ellipsis">
|
<div className="text-xs font-medium leading-tight line-clamp-2 text-foreground break-words overflow-hidden text-ellipsis">
|
||||||
{source.title}
|
{source.title}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-[10px] text-muted-foreground truncate overflow-hidden text-ellipsis">
|
<div className="text-xs text-muted-foreground truncate overflow-hidden text-ellipsis">
|
||||||
{hostname}
|
{hostname}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -47,25 +47,25 @@ export function SourcesCompact({ sources, className }: SourcesCompactProps) {
|
|||||||
href={source.url}
|
href={source.url}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="group flex items-center gap-2 px-3 py-2 rounded-lg bg-muted/30 hover:bg-muted/50 border border-transparent hover:border-muted transition-all flex-shrink-0"
|
className="group flex items-center gap-2 px-3 py-2 rounded-md border bg-surface hover:bg-hover transition-colors duration-150 flex-shrink-0"
|
||||||
>
|
>
|
||||||
{faviconUrl ? (
|
{faviconUrl ? (
|
||||||
<img
|
<img
|
||||||
src={faviconUrl}
|
src={faviconUrl}
|
||||||
alt=""
|
alt=""
|
||||||
className="w-4 h-4 rounded flex-shrink-0"
|
className="w-4 h-4 rounded-sm flex-shrink-0"
|
||||||
onError={(e) => {
|
onError={(e) => {
|
||||||
(e.target as HTMLImageElement).style.display = 'none';
|
(e.target as HTMLImageElement).style.display = 'none';
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<ExternalLink className="w-4 h-4 text-muted-foreground/60 flex-shrink-0" />
|
<ExternalLink className="w-4 h-4 text-muted-foreground flex-shrink-0" />
|
||||||
)}
|
)}
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<div className="text-xs font-medium truncate max-w-[140px] text-foreground/90">
|
<div className="text-xs font-medium truncate max-w-[140px] text-foreground">
|
||||||
{source.title || domain}
|
{source.title || domain}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-[10px] text-muted-foreground truncate">
|
<div className="text-xs text-muted-foreground truncate">
|
||||||
{domain}
|
{domain}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -45,10 +45,10 @@ export function SourcesDisplay({ sources, className }: SourcesDisplayProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn("px-6 py-4 border-t border-muted/50", className)}>
|
<div className={cn("px-6 py-4 border-t", className)}>
|
||||||
<div className="flex items-center gap-2 mb-3">
|
<div className="flex items-center gap-2 mb-3">
|
||||||
<Globe className="w-4 h-4 text-muted-foreground/60" />
|
<Globe className="w-4 h-4 text-muted-foreground" />
|
||||||
<p className="text-xs font-medium text-muted-foreground/80">
|
<p className="text-xs font-medium text-muted-foreground">
|
||||||
Fontes consultadas ({sources.length}):
|
Fontes consultadas ({sources.length}):
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -65,7 +65,7 @@ export function SourcesDisplay({ sources, className }: SourcesDisplayProps) {
|
|||||||
href={source.url}
|
href={source.url}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="group flex items-center gap-2 px-3 py-2 rounded-lg bg-muted/30 hover:bg-muted/50 border border-transparent hover:border-muted transition-all flex-shrink-0"
|
className="group flex items-center gap-2 px-3 py-2 rounded-md border bg-surface hover:bg-hover transition-colors duration-150 flex-shrink-0"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
// Permitir que o botão de copiar funcione sem navegar
|
// Permitir que o botão de copiar funcione sem navegar
|
||||||
if ((e.target as HTMLElement).closest('button')) {
|
if ((e.target as HTMLElement).closest('button')) {
|
||||||
@@ -77,19 +77,19 @@ export function SourcesDisplay({ sources, className }: SourcesDisplayProps) {
|
|||||||
<img
|
<img
|
||||||
src={faviconUrl}
|
src={faviconUrl}
|
||||||
alt=""
|
alt=""
|
||||||
className="w-4 h-4 rounded flex-shrink-0"
|
className="w-4 h-4 rounded-sm flex-shrink-0"
|
||||||
onError={(e) => {
|
onError={(e) => {
|
||||||
(e.target as HTMLImageElement).style.display = 'none';
|
(e.target as HTMLImageElement).style.display = 'none';
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<Globe className="w-4 h-4 text-muted-foreground/60 flex-shrink-0" />
|
<Globe className="w-4 h-4 text-muted-foreground flex-shrink-0" />
|
||||||
)}
|
)}
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<div className="text-xs font-medium truncate max-w-[140px] text-foreground/90">
|
<div className="text-xs font-medium truncate max-w-[140px] text-foreground">
|
||||||
{source.title || domain}
|
{source.title || domain}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-[10px] text-muted-foreground truncate">
|
<div className="text-xs text-muted-foreground truncate">
|
||||||
{domain}
|
{domain}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -99,12 +99,12 @@ export function SourcesDisplay({ sources, className }: SourcesDisplayProps) {
|
|||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
copyToClipboard(source.url, idx);
|
copyToClipboard(source.url, idx);
|
||||||
}}
|
}}
|
||||||
className="ml-1 p-1 rounded hover:bg-muted/50 transition-colors opacity-0 group-hover:opacity-100"
|
className="ml-1 p-1 rounded-sm hover:bg-background transition-opacity duration-150 opacity-0 group-hover:opacity-100 focus-visible:opacity-100"
|
||||||
title="Copiar URL"
|
title="Copiar URL"
|
||||||
aria-label="Copiar URL"
|
aria-label="Copiar URL"
|
||||||
>
|
>
|
||||||
{isCopied ? (
|
{isCopied ? (
|
||||||
<Check className="w-3 h-3 text-green-600 dark:text-green-400" />
|
<Check className="w-3 h-3 text-success" />
|
||||||
) : (
|
) : (
|
||||||
<Copy className="w-3 h-3 text-muted-foreground" />
|
<Copy className="w-3 h-3 text-muted-foreground" />
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -32,10 +32,7 @@ export function StreamingIndicator({ isStreaming, className }: StreamingIndicato
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn("flex items-center gap-2 text-xs text-muted-foreground px-6 py-2", className)}>
|
<div className={cn("flex items-center gap-2 text-xs text-muted-foreground px-6 py-2", className)}>
|
||||||
<div className="relative">
|
<Sparkles className="w-3 h-3 text-primary animate-pulse" />
|
||||||
<Sparkles className="w-3 h-3 text-primary animate-pulse" />
|
|
||||||
<div className="absolute inset-0 bg-primary/20 rounded-full animate-ping" />
|
|
||||||
</div>
|
|
||||||
<span>Streaming{dots}</span>
|
<span>Streaming{dots}</span>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ export function SystemPanel() {
|
|||||||
<div className="h-full overflow-y-auto p-4 space-y-6">
|
<div className="h-full overflow-y-auto p-4 space-y-6">
|
||||||
{/* Hardware Stats */}
|
{/* Hardware Stats */}
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
|
<h3 className="text-xs font-medium text-muted-foreground">
|
||||||
Monitoramento
|
Monitoramento
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
@@ -65,7 +65,7 @@ export function SystemPanel() {
|
|||||||
{/* Models List */}
|
{/* Models List */}
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
|
<h3 className="text-xs font-medium text-muted-foreground">
|
||||||
Modelos Instalados
|
Modelos Instalados
|
||||||
</h3>
|
</h3>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
@@ -92,7 +92,7 @@ export function SystemPanel() {
|
|||||||
model.name.toLowerCase().endsWith('.gguf');
|
model.name.toLowerCase().endsWith('.gguf');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card key={model.id} className="overflow-hidden hover:bg-muted/50 transition-colors">
|
<Card key={model.id} className="overflow-hidden hover:bg-hover transition-colors duration-150">
|
||||||
<CardContent className="p-3 flex items-center justify-between gap-2">
|
<CardContent className="p-3 flex items-center justify-between gap-2">
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
<div className="flex items-center gap-2 mb-1">
|
<div className="flex items-center gap-2 mb-1">
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ export function ThinkingIndicator({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="px-6 py-4 border-b border-muted/50 bg-muted/20">
|
<div className="px-6 py-4 border-b bg-surface">
|
||||||
<div className="flex items-center gap-4 text-xs text-muted-foreground">
|
<div className="flex items-center gap-4 text-xs text-muted-foreground">
|
||||||
{steps.slice(0, currentStepIndex + 1).map((step, idx) => {
|
{steps.slice(0, currentStepIndex + 1).map((step, idx) => {
|
||||||
const isActive = idx === currentStepIndex;
|
const isActive = idx === currentStepIndex;
|
||||||
@@ -81,10 +81,10 @@ export function ThinkingIndicator({
|
|||||||
<div key={step.key} className="flex items-center gap-2">
|
<div key={step.key} className="flex items-center gap-2">
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex items-center justify-center w-5 h-5 rounded-full transition-colors",
|
"flex items-center justify-center w-5 h-5 rounded-full transition-colors duration-150",
|
||||||
isPast && "bg-green-500/20 text-green-600 dark:text-green-400",
|
isPast && "bg-success/15 text-success",
|
||||||
isActive && "bg-blue-500/20 text-blue-600 dark:text-blue-400 animate-pulse",
|
isActive && "bg-accent-soft text-foreground",
|
||||||
!isActive && !isPast && "bg-muted text-muted-foreground"
|
!isActive && !isPast && "bg-hover text-muted-foreground"
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{isPast ? (
|
{isPast ? (
|
||||||
|
|||||||
@@ -30,13 +30,13 @@ export function WebSearchStatus({
|
|||||||
const getStatusIcon = () => {
|
const getStatusIcon = () => {
|
||||||
switch (status) {
|
switch (status) {
|
||||||
case 'searching':
|
case 'searching':
|
||||||
return <Search className="w-4 h-4 animate-pulse" />;
|
return <Search className="w-4 h-4" />;
|
||||||
case 'scraping':
|
case 'scraping':
|
||||||
return <BookOpen className="w-4 h-4 animate-pulse" />;
|
return <BookOpen className="w-4 h-4" />;
|
||||||
case 'completed':
|
case 'completed':
|
||||||
return <CheckCircle2 className="w-4 h-4 text-green-500" />;
|
return <CheckCircle2 className="w-4 h-4 text-success" />;
|
||||||
case 'error':
|
case 'error':
|
||||||
return <AlertCircle className="w-4 h-4 text-red-500" />;
|
return <AlertCircle className="w-4 h-4 text-destructive" />;
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -45,13 +45,13 @@ export function WebSearchStatus({
|
|||||||
const getStatusText = () => {
|
const getStatusText = () => {
|
||||||
switch (status) {
|
switch (status) {
|
||||||
case 'searching':
|
case 'searching':
|
||||||
return `🔍 Pesquisando por: "${query}"...`;
|
return `Pesquisando por: "${query}"...`;
|
||||||
case 'scraping':
|
case 'scraping':
|
||||||
return `📖 Lendo ${sources.length || '...'} fonte${sources.length !== 1 ? 's' : ''}...`;
|
return `Lendo ${sources.length || '...'} fonte${sources.length !== 1 ? 's' : ''}...`;
|
||||||
case 'completed':
|
case 'completed':
|
||||||
return `✅ ${sources.length} fonte${sources.length !== 1 ? 's' : ''} encontrada${sources.length !== 1 ? 's' : ''}`;
|
return `${sources.length} fonte${sources.length !== 1 ? 's' : ''} encontrada${sources.length !== 1 ? 's' : ''}`;
|
||||||
case 'error':
|
case 'error':
|
||||||
return `❌ Erro: ${error || 'Falha ao buscar'}`;
|
return `Erro: ${error || 'Falha ao buscar'}`;
|
||||||
default:
|
default:
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
@@ -69,17 +69,15 @@ export function WebSearchStatus({
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Card className={cn(
|
<Card className={cn(
|
||||||
"mx-4 mb-2 border-l-4",
|
"mx-4 mb-2",
|
||||||
status === 'completed' && "border-l-green-500",
|
status === 'error' && "border-destructive/40"
|
||||||
status === 'error' && "border-l-red-500",
|
|
||||||
(status === 'searching' || status === 'scraping') && "border-l-blue-500"
|
|
||||||
)}>
|
)}>
|
||||||
<CardContent className="p-4">
|
<CardContent className="p-4">
|
||||||
<div className="flex items-center justify-between gap-2">
|
<div className="flex items-center justify-between gap-2">
|
||||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||||
<div className="flex-shrink-0">
|
<div className="flex-shrink-0">
|
||||||
{status === 'searching' || status === 'scraping' ? (
|
{status === 'searching' || status === 'scraping' ? (
|
||||||
<Loader2 className="w-4 h-4 animate-spin text-blue-500" />
|
<Loader2 className="w-4 h-4 animate-spin text-primary" />
|
||||||
) : (
|
) : (
|
||||||
getStatusIcon()
|
getStatusIcon()
|
||||||
)}
|
)}
|
||||||
@@ -98,7 +96,7 @@ export function WebSearchStatus({
|
|||||||
key={idx}
|
key={idx}
|
||||||
src={getFaviconUrl(source.url)}
|
src={getFaviconUrl(source.url)}
|
||||||
alt=""
|
alt=""
|
||||||
className="w-4 h-4 rounded"
|
className="w-4 h-4 rounded-sm"
|
||||||
onError={(e) => {
|
onError={(e) => {
|
||||||
(e.target as HTMLImageElement).style.display = 'none';
|
(e.target as HTMLImageElement).style.display = 'none';
|
||||||
}}
|
}}
|
||||||
@@ -111,7 +109,7 @@ export function WebSearchStatus({
|
|||||||
|
|
||||||
<Dialog open={isSourcesOpen} onOpenChange={setIsSourcesOpen}>
|
<Dialog open={isSourcesOpen} onOpenChange={setIsSourcesOpen}>
|
||||||
<DialogTrigger asChild>
|
<DialogTrigger asChild>
|
||||||
<Button variant="ghost" size="sm" className="h-7 text-xs">
|
<Button variant="ghost" size="sm" className="h-8 text-xs">
|
||||||
Ver Fontes
|
Ver Fontes
|
||||||
</Button>
|
</Button>
|
||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
@@ -135,7 +133,7 @@ export function WebSearchStatus({
|
|||||||
href={source.url}
|
href={source.url}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="text-xs text-muted-foreground hover:text-primary flex items-center gap-1 truncate"
|
className="text-xs text-muted-foreground hover:text-foreground transition-colors duration-150 flex items-center gap-1 truncate"
|
||||||
>
|
>
|
||||||
{source.url}
|
{source.url}
|
||||||
<ExternalLink className="w-3 h-3" />
|
<ExternalLink className="w-3 h-3" />
|
||||||
|
|||||||
@@ -3,21 +3,21 @@ import { ArrowRight, Cpu } from "lucide-react";
|
|||||||
|
|
||||||
export function Hero({ onStart }: { onStart: () => void }) {
|
export function Hero({ onStart }: { onStart: () => void }) {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col items-center justify-center min-h-[60vh] text-center px-4 space-y-6 animate-in fade-in zoom-in duration-500">
|
<div className="flex flex-col items-center justify-center min-h-[60vh] text-center px-4 space-y-6 animate-in fade-in duration-200 ease-out">
|
||||||
<div className="p-4 rounded-full bg-primary/10 animate-pulse">
|
<div className="p-4 rounded-lg border bg-surface">
|
||||||
<Cpu className="w-12 h-12 text-primary" />
|
<Cpu className="w-12 h-12 text-foreground" />
|
||||||
</div>
|
</div>
|
||||||
<h1 className="text-4xl md:text-6xl font-bold tracking-tighter bg-clip-text text-transparent bg-gradient-to-r from-primary to-primary/60">
|
<h1 className="text-3xl font-semibold tracking-tight text-foreground">
|
||||||
OllaHub
|
OllaHub
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-lg md:text-xl text-muted-foreground max-w-[600px]">
|
<p className="text-lg text-muted-foreground max-w-[60ch]">
|
||||||
Sua interface moderna e poderosa para interagir com Ollama e Modelos de Linguagem Locais.
|
Sua interface moderna e poderosa para interagir com Ollama e Modelos de Linguagem Locais.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div className="flex gap-4 pt-4">
|
<div className="flex gap-4 pt-4">
|
||||||
<Button size="lg" onClick={onStart} className="group text-lg px-8 h-12">
|
<Button size="lg" onClick={onStart} className="group">
|
||||||
Iniciar Chat
|
Iniciar Chat
|
||||||
<ArrowRight className="ml-2 w-5 h-5 transition-transform group-hover:translate-x-1" />
|
<ArrowRight className="w-4 h-4 transition-transform duration-150 group-hover:translate-x-1" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -31,9 +31,12 @@ export function StoppedCard({ onCheckAgain }: { onCheckAgain: () => void }) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="w-full max-w-md mx-auto border-yellow-500/50 bg-yellow-50/10 dark:bg-yellow-900/10">
|
<Card className="w-full max-w-md mx-auto border-warning/40">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-yellow-600 dark:text-yellow-500">Ollama está parado</CardTitle>
|
<CardTitle className="flex items-center gap-2">
|
||||||
|
<span className="h-2 w-2 shrink-0 rounded-full bg-warning" aria-hidden="true" />
|
||||||
|
Ollama está parado
|
||||||
|
</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
O Ollama está instalado mas não está rodando. Você pode iniciá-lo automaticamente ou executar o comando manualmente.
|
O Ollama está instalado mas não está rodando. Você pode iniciá-lo automaticamente ou executar o comando manualmente.
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
@@ -41,7 +44,7 @@ export function StoppedCard({ onCheckAgain }: { onCheckAgain: () => void }) {
|
|||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
<Button
|
<Button
|
||||||
onClick={handleStart}
|
onClick={handleStart}
|
||||||
className="w-full bg-yellow-600 hover:bg-yellow-700 text-white"
|
className="w-full"
|
||||||
disabled={starting}
|
disabled={starting}
|
||||||
>
|
>
|
||||||
{starting ? (
|
{starting ? (
|
||||||
@@ -59,15 +62,15 @@ export function StoppedCard({ onCheckAgain }: { onCheckAgain: () => void }) {
|
|||||||
|
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<div className="absolute inset-0 flex items-center">
|
<div className="absolute inset-0 flex items-center">
|
||||||
<span className="w-full border-t border-yellow-500/20" />
|
<span className="w-full border-t border-border" />
|
||||||
</div>
|
</div>
|
||||||
<div className="relative flex justify-center text-xs uppercase">
|
<div className="relative flex justify-center text-xs">
|
||||||
<span className="bg-background px-2 text-muted-foreground">Ou manualmente</span>
|
<span className="bg-card px-2 text-muted-foreground">Ou manualmente</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center space-x-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="bg-muted p-3 rounded-md font-mono text-sm flex-1 border">
|
<div className="bg-background p-3 rounded-md font-mono text-sm flex-1 border">
|
||||||
{command}
|
{command}
|
||||||
</div>
|
</div>
|
||||||
<Button size="icon" variant="outline" onClick={handleCopy}>
|
<Button size="icon" variant="outline" onClick={handleCopy}>
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { Progress } from "@/components/ui/progress"
|
import { Progress } from "@/components/ui/progress"
|
||||||
import { Download, Loader2, AlertCircle, CheckCircle2, Play } from "lucide-react"
|
import { Download, Loader2, AlertCircle, CheckCircle2, Play, Lightbulb } from "lucide-react"
|
||||||
import { useOllamaDownload } from "@/hooks/use-ollama-download"
|
import { useOllamaDownload } from "@/hooks/use-ollama-download"
|
||||||
import { useToast } from "@/hooks/use-toast"
|
import { useToast } from "@/hooks/use-toast"
|
||||||
import { useOperatingSystem } from "@/hooks/use-operating-system"
|
import { useOperatingSystem } from "@/hooks/use-operating-system"
|
||||||
@@ -163,13 +163,13 @@ export function InstallModal({ open, onCheckAgain }: InstallModalProps) {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{hasDownloaded && !isDownloading && (
|
{hasDownloaded && !isDownloading && (
|
||||||
<div className="flex items-start gap-2 p-3 bg-green-50 dark:bg-green-950/20 rounded-md">
|
<div className="flex items-start gap-2 p-3 border border-success/30 bg-success/10 rounded-md">
|
||||||
<CheckCircle2 className="h-4 w-4 mt-0.5 text-green-600 dark:text-green-400" />
|
<CheckCircle2 className="h-4 w-4 mt-0.5 shrink-0 text-success" />
|
||||||
<div className="text-sm flex-1">
|
<div className="text-sm flex-1">
|
||||||
<p className="font-medium text-green-900 dark:text-green-100">
|
<p className="font-medium text-foreground">
|
||||||
Download concluído
|
Download concluído
|
||||||
</p>
|
</p>
|
||||||
<p className="text-green-700 dark:text-green-300">
|
<p className="text-muted-foreground">
|
||||||
Clique em "Instalar Ollama" para iniciar a instalação.
|
Clique em "Instalar Ollama" para iniciar a instalação.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -203,20 +203,21 @@ export function InstallModal({ open, onCheckAgain }: InstallModalProps) {
|
|||||||
<DownloadProgress os="mac" />
|
<DownloadProgress os="mac" />
|
||||||
</div>
|
</div>
|
||||||
{downloadState.downloadError && activeTab === 'mac' && (
|
{downloadState.downloadError && activeTab === 'mac' && (
|
||||||
<div className="flex items-start gap-2 p-3 bg-red-50 dark:bg-red-950/20 rounded-md">
|
<div className="flex items-start gap-2 p-3 border border-destructive/30 bg-destructive/10 rounded-md">
|
||||||
<AlertCircle className="h-4 w-4 mt-0.5 text-red-600 dark:text-red-400" />
|
<AlertCircle className="h-4 w-4 mt-0.5 shrink-0 text-destructive" />
|
||||||
<div className="text-sm">
|
<div className="text-sm">
|
||||||
<p className="font-medium text-red-900 dark:text-red-100">Erro no download</p>
|
<p className="font-medium text-foreground">Erro no download</p>
|
||||||
<p className="text-red-700 dark:text-red-300">
|
<p className="text-muted-foreground">
|
||||||
{downloadState.downloadError}
|
{downloadState.downloadError}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="space-y-2 text-sm text-muted-foreground">
|
<div className="space-y-2 text-sm text-muted-foreground">
|
||||||
<p>Após instalar, o Ollama será iniciado automaticamente. Se necessário, abra o terminal e digite <code className="bg-muted px-1 rounded">ollama serve</code>.</p>
|
<p>Após instalar, o Ollama será iniciado automaticamente. Se necessário, abra o terminal e digite <code className="font-mono bg-surface border px-1 rounded-sm">ollama serve</code>.</p>
|
||||||
<p className="font-medium text-foreground">
|
<p className="flex gap-2 font-medium text-foreground">
|
||||||
💡 Dica: Após concluir a instalação, você pode fechar qualquer janela de chat aberta pelo Ollama e continuar aqui no OllaHub.
|
<Lightbulb className="h-4 w-4 mt-0.5 shrink-0 text-muted-foreground" aria-hidden="true" />
|
||||||
|
<span>Dica: Após concluir a instalação, você pode fechar qualquer janela de chat aberta pelo Ollama e continuar aqui no OllaHub.</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
@@ -224,8 +225,8 @@ export function InstallModal({ open, onCheckAgain }: InstallModalProps) {
|
|||||||
<TabsContent value="linux" className="space-y-4 py-4">
|
<TabsContent value="linux" className="space-y-4 py-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<h3 className="font-medium">Instalação via Terminal</h3>
|
<h3 className="font-medium">Instalação via Terminal</h3>
|
||||||
<div className="bg-muted p-4 rounded-md relative group">
|
<div className="bg-surface border p-4 rounded-md relative group">
|
||||||
<code className="text-sm break-all">curl -fsSL https://ollama.com/install.sh | sh</code>
|
<code className="font-mono text-sm break-all">curl -fsSL https://ollama.com/install.sh | sh</code>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@@ -234,11 +235,11 @@ export function InstallModal({ open, onCheckAgain }: InstallModalProps) {
|
|||||||
<DownloadProgress os="linux" />
|
<DownloadProgress os="linux" />
|
||||||
</div>
|
</div>
|
||||||
{downloadState.downloadError && activeTab === 'linux' && (
|
{downloadState.downloadError && activeTab === 'linux' && (
|
||||||
<div className="flex items-start gap-2 p-3 bg-red-50 dark:bg-red-950/20 rounded-md">
|
<div className="flex items-start gap-2 p-3 border border-destructive/30 bg-destructive/10 rounded-md">
|
||||||
<AlertCircle className="h-4 w-4 mt-0.5 text-red-600 dark:text-red-400" />
|
<AlertCircle className="h-4 w-4 mt-0.5 shrink-0 text-destructive" />
|
||||||
<div className="text-sm">
|
<div className="text-sm">
|
||||||
<p className="font-medium text-red-900 dark:text-red-100">Erro no download</p>
|
<p className="font-medium text-foreground">Erro no download</p>
|
||||||
<p className="text-red-700 dark:text-red-300">
|
<p className="text-muted-foreground">
|
||||||
{downloadState.downloadError}
|
{downloadState.downloadError}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -247,10 +248,11 @@ export function InstallModal({ open, onCheckAgain }: InstallModalProps) {
|
|||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<h3 className="font-medium">Comando Manual</h3>
|
<h3 className="font-medium">Comando Manual</h3>
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-sm text-muted-foreground">
|
||||||
Ou consulte <a href="https://ollama.com/download/linux" className="underline text-primary" target="_blank" rel="noopener noreferrer">ollama.com/download/linux</a> para instruções manuais.
|
Ou consulte <a href="https://ollama.com/download/linux" className="underline underline-offset-2 text-foreground" target="_blank" rel="noopener noreferrer">ollama.com/download/linux</a> para instruções manuais.
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm font-medium text-foreground">
|
<p className="flex gap-2 text-sm font-medium text-foreground">
|
||||||
💡 Dica: Após concluir a instalação, você pode fechar qualquer janela de chat aberta pelo Ollama e continuar aqui no OllaHub.
|
<Lightbulb className="h-4 w-4 mt-0.5 shrink-0 text-muted-foreground" aria-hidden="true" />
|
||||||
|
<span>Dica: Após concluir a instalação, você pode fechar qualquer janela de chat aberta pelo Ollama e continuar aqui no OllaHub.</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
@@ -262,11 +264,11 @@ export function InstallModal({ open, onCheckAgain }: InstallModalProps) {
|
|||||||
<DownloadProgress os="windows" />
|
<DownloadProgress os="windows" />
|
||||||
</div>
|
</div>
|
||||||
{downloadState.downloadError && activeTab === 'windows' && (
|
{downloadState.downloadError && activeTab === 'windows' && (
|
||||||
<div className="flex items-start gap-2 p-3 bg-red-50 dark:bg-red-950/20 rounded-md">
|
<div className="flex items-start gap-2 p-3 border border-destructive/30 bg-destructive/10 rounded-md">
|
||||||
<AlertCircle className="h-4 w-4 mt-0.5 text-red-600 dark:text-red-400" />
|
<AlertCircle className="h-4 w-4 mt-0.5 shrink-0 text-destructive" />
|
||||||
<div className="text-sm">
|
<div className="text-sm">
|
||||||
<p className="font-medium text-red-900 dark:text-red-100">Erro no download</p>
|
<p className="font-medium text-foreground">Erro no download</p>
|
||||||
<p className="text-red-700 dark:text-red-300">
|
<p className="text-muted-foreground">
|
||||||
{downloadState.downloadError}
|
{downloadState.downloadError}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -274,8 +276,9 @@ export function InstallModal({ open, onCheckAgain }: InstallModalProps) {
|
|||||||
)}
|
)}
|
||||||
<div className="space-y-2 text-sm text-muted-foreground">
|
<div className="space-y-2 text-sm text-muted-foreground">
|
||||||
<p>Após clicar em "Instalar Ollama", o instalador será aberto. Siga as instruções na tela para completar a instalação.</p>
|
<p>Após clicar em "Instalar Ollama", o instalador será aberto. Siga as instruções na tela para completar a instalação.</p>
|
||||||
<p className="font-medium text-foreground">
|
<p className="flex gap-2 font-medium text-foreground">
|
||||||
💡 Dica: Após concluir a instalação, você pode fechar qualquer janela de chat aberta pelo Ollama e continuar aqui no OllaHub.
|
<Lightbulb className="h-4 w-4 mt-0.5 shrink-0 text-muted-foreground" aria-hidden="true" />
|
||||||
|
<span>Dica: Após concluir a instalação, você pode fechar qualquer janela de chat aberta pelo Ollama e continuar aqui no OllaHub.</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
@@ -283,16 +286,16 @@ export function InstallModal({ open, onCheckAgain }: InstallModalProps) {
|
|||||||
|
|
||||||
{/* Status de verificação automática */}
|
{/* Status de verificação automática */}
|
||||||
{downloadState.isChecking && (
|
{downloadState.isChecking && (
|
||||||
<div className="flex items-start gap-2 p-3 bg-blue-50 dark:bg-blue-950/20 rounded-md mt-4">
|
<div className="flex items-start gap-2 p-3 border bg-surface rounded-md mt-4">
|
||||||
<Loader2 className="h-4 w-4 mt-0.5 text-blue-600 dark:text-blue-400 animate-spin" />
|
<Loader2 className="h-4 w-4 mt-0.5 shrink-0 text-primary animate-spin" />
|
||||||
<div className="text-sm flex-1">
|
<div className="text-sm flex-1">
|
||||||
<p className="font-medium text-blue-900 dark:text-blue-100">
|
<p className="font-medium text-foreground">
|
||||||
Verificando instalação do Ollama...
|
Verificando instalação do Ollama...
|
||||||
</p>
|
</p>
|
||||||
<p className="text-blue-700 dark:text-blue-300">
|
<p className="text-muted-foreground">
|
||||||
{downloadState.checkStatus || 'Aguardando instalação ser concluída...'}
|
{downloadState.checkStatus || 'Aguardando instalação ser concluída...'}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-xs text-blue-600 dark:text-blue-400 mt-1">
|
<p className="text-xs text-muted-foreground mt-1">
|
||||||
Esta verificação continuará em segundo plano até encontrar o Ollama.
|
Esta verificação continuará em segundo plano até encontrar o Ollama.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ export function UpdateDialog({ open, onOpenChange }: UpdateDialogProps) {
|
|||||||
<DialogContent className="sm:max-w-[500px]">
|
<DialogContent className="sm:max-w-[500px]">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle className="flex items-center gap-2">
|
<DialogTitle className="flex items-center gap-2">
|
||||||
<Sparkles className="h-5 w-5 text-primary" />
|
<Sparkles className="h-5 w-5 text-muted-foreground" />
|
||||||
Atualização Disponível
|
Atualização Disponível
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
@@ -75,14 +75,14 @@ export function UpdateDialog({ open, onOpenChange }: UpdateDialogProps) {
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex items-center justify-between text-sm">
|
<div className="flex items-center justify-between text-sm">
|
||||||
<span className="text-muted-foreground">Nova Versão</span>
|
<span className="text-muted-foreground">Nova Versão</span>
|
||||||
<span className="font-mono font-medium text-primary">
|
<span className="font-mono font-semibold text-foreground">
|
||||||
{updateInfo?.version}
|
{updateInfo?.version}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{updateInfo?.body && (
|
{updateInfo?.body && (
|
||||||
<div className="p-3 bg-muted rounded-lg">
|
<div className="p-3 bg-surface border rounded-md">
|
||||||
<p className="text-sm text-muted-foreground line-clamp-3">
|
<p className="text-sm text-muted-foreground line-clamp-3">
|
||||||
{updateInfo.body}
|
{updateInfo.body}
|
||||||
</p>
|
</p>
|
||||||
@@ -100,7 +100,7 @@ export function UpdateDialog({ open, onOpenChange }: UpdateDialogProps) {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<div className="p-3 bg-destructive/10 border border-destructive/20 rounded-lg">
|
<div className="p-3 bg-destructive/10 border border-destructive/30 rounded-md">
|
||||||
<p className="text-sm text-destructive">{error}</p>
|
<p className="text-sm text-destructive">{error}</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -33,24 +33,25 @@ export function WelcomeNotification() {
|
|||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed top-4 left-1/2 -translate-x-1/2 z-50 w-full max-w-md",
|
"fixed top-4 left-1/2 -translate-x-1/2 z-50 w-full max-w-md",
|
||||||
"animate-in slide-in-from-top-5 fade-in duration-500"
|
"animate-in slide-in-from-top-2 fade-in duration-200 ease-out"
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className="bg-primary text-primary-foreground rounded-lg shadow-lg p-4 mx-4">
|
<div className="bg-popover text-popover-foreground border rounded-lg shadow-float p-4 mx-4">
|
||||||
<div className="flex items-start gap-3">
|
<div className="flex items-start gap-3">
|
||||||
<Heart className="h-5 w-5 mt-0.5 flex-shrink-0" />
|
<Heart className="h-5 w-5 mt-0.5 flex-shrink-0 text-muted-foreground" />
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
<h3 className="font-semibold text-sm mb-1">
|
<h3 className="font-semibold text-sm mb-1">
|
||||||
Obrigado por usar o OllaHub! 🎉
|
Obrigado por usar o OllaHub! 🎉
|
||||||
</h3>
|
</h3>
|
||||||
<p className="text-xs text-primary-foreground/90">
|
<p className="text-xs text-muted-foreground">
|
||||||
Estamos felizes em tê-lo conosco. Comece a explorar e aproveite sua experiência!
|
Estamos felizes em tê-lo conosco. Comece a explorar e aproveite sua experiência!
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
className="h-6 w-6 text-primary-foreground hover:bg-primary-foreground/20 flex-shrink-0"
|
className="h-8 w-8 -mt-1 -mr-1 text-muted-foreground hover:text-foreground flex-shrink-0"
|
||||||
|
aria-label="Fechar"
|
||||||
onClick={() => setShow(false)}
|
onClick={() => setShow(false)}
|
||||||
>
|
>
|
||||||
<X className="h-4 w-4" />
|
<X className="h-4 w-4" />
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ export function PythonBootstrapProgress() {
|
|||||||
// Se houver erro, mostrar alerta
|
// Se houver erro, mostrar alerta
|
||||||
if (bootstrap.error) {
|
if (bootstrap.error) {
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-scrim">
|
||||||
<div className="w-full max-w-md mx-4">
|
<div className="w-full max-w-md mx-4">
|
||||||
<Card className="border-destructive">
|
<Card className="border-destructive">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
@@ -59,7 +59,7 @@ export function PythonBootstrapProgress() {
|
|||||||
const progressValue = bootstrap.progress ?? 0;
|
const progressValue = bootstrap.progress ?? 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-scrim">
|
||||||
<div className="w-full max-w-md mx-4">
|
<div className="w-full max-w-md mx-4">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { motion, AnimatePresence } from "framer-motion";
|
import { motion, AnimatePresence } from "framer-motion";
|
||||||
import { Loader2, Search, FileText } from "lucide-react";
|
import { Loader2, Search, FileText, AlertCircle } from "lucide-react";
|
||||||
import { useWebSearch } from "@/hooks/use-web-search";
|
import { useWebSearch } from "@/hooks/use-web-search";
|
||||||
|
|
||||||
export function ScrapingProgressIndicator() {
|
export function ScrapingProgressIndicator() {
|
||||||
@@ -15,25 +15,23 @@ export function ScrapingProgressIndicator() {
|
|||||||
return (
|
return (
|
||||||
<AnimatePresence>
|
<AnimatePresence>
|
||||||
<motion.div
|
<motion.div
|
||||||
initial={{ opacity: 0, y: 20, scale: 0.9 }}
|
initial={{ opacity: 0, y: 8, scale: 0.98 }}
|
||||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||||
exit={{ opacity: 0, y: 20, scale: 0.9 }}
|
exit={{ opacity: 0, y: 8, scale: 0.98 }}
|
||||||
transition={{ duration: 0.2, ease: "easeOut" }}
|
transition={{ duration: 0.2, ease: "easeOut" }}
|
||||||
className="fixed bottom-24 right-6 bg-card border border-primary/20 rounded-lg p-4 shadow-lg backdrop-blur-sm z-50 min-w-[280px]"
|
className="fixed bottom-24 right-6 bg-popover text-popover-foreground border rounded-lg p-4 shadow-float z-50 min-w-[280px]"
|
||||||
>
|
>
|
||||||
<div className="flex items-start gap-3">
|
<div className="flex items-start gap-3">
|
||||||
{/* Icon animado */}
|
{/* Icon animado */}
|
||||||
<div className="flex-shrink-0 mt-0.5">
|
<div className="flex-shrink-0">
|
||||||
{webSearch.status === 'searching' && (
|
{webSearch.status === 'searching' && (
|
||||||
<Search className="w-5 h-5 text-primary animate-pulse" />
|
<Search className="w-5 h-5 text-muted-foreground" />
|
||||||
)}
|
)}
|
||||||
{webSearch.status === 'scraping' && (
|
{webSearch.status === 'scraping' && (
|
||||||
<FileText className="w-5 h-5 text-primary animate-pulse" />
|
<FileText className="w-5 h-5 text-muted-foreground" />
|
||||||
)}
|
)}
|
||||||
{webSearch.status === 'error' && (
|
{webSearch.status === 'error' && (
|
||||||
<div className="w-5 h-5 rounded-full bg-destructive/20 flex items-center justify-center">
|
<AlertCircle className="w-5 h-5 text-destructive" />
|
||||||
<span className="text-destructive text-xs font-bold">!</span>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -64,7 +62,7 @@ export function ScrapingProgressIndicator() {
|
|||||||
|
|
||||||
{/* Barra de progresso simulada */}
|
{/* Barra de progresso simulada */}
|
||||||
{webSearch.status !== 'error' && (
|
{webSearch.status !== 'error' && (
|
||||||
<div className="w-full h-1 bg-muted rounded-full overflow-hidden">
|
<div className="w-full h-1 bg-hover rounded-full overflow-hidden">
|
||||||
<motion.div
|
<motion.div
|
||||||
className="h-full bg-primary"
|
className="h-full bg-primary"
|
||||||
initial={{ width: "0%" }}
|
initial={{ width: "0%" }}
|
||||||
|
|||||||
@@ -87,16 +87,16 @@ export function GpuDashboard({ gpuId, pollInterval = 2000 }: GpuDashboardProps)
|
|||||||
|
|
||||||
const getStatusColor = (value: number | null, thresholds: { good: number; warning: number }): string => {
|
const getStatusColor = (value: number | null, thresholds: { good: number; warning: number }): string => {
|
||||||
if (!value) return 'bg-muted';
|
if (!value) return 'bg-muted';
|
||||||
if (value < thresholds.good) return 'bg-green-500';
|
if (value < thresholds.good) return 'bg-success';
|
||||||
if (value < thresholds.warning) return 'bg-yellow-500';
|
if (value < thresholds.warning) return 'bg-warning';
|
||||||
return 'bg-red-500';
|
return 'bg-destructive';
|
||||||
};
|
};
|
||||||
|
|
||||||
const getTemperatureColor = (temp: number | null): string => {
|
const getTemperatureColor = (temp: number | null): string => {
|
||||||
if (!temp) return 'text-muted-foreground';
|
if (!temp) return 'text-muted-foreground';
|
||||||
if (temp < 60) return 'text-green-500';
|
if (temp < 60) return 'text-success';
|
||||||
if (temp < 80) return 'text-yellow-500';
|
if (temp < 80) return 'text-warning';
|
||||||
return 'text-red-500';
|
return 'text-destructive';
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -167,7 +167,7 @@ export function GpuDashboard({ gpuId, pollInterval = 2000 }: GpuDashboardProps)
|
|||||||
className="h-2"
|
className="h-2"
|
||||||
/>
|
/>
|
||||||
{stats.compute_usage_percent !== null && stats.graphics_usage_percent !== null && (
|
{stats.compute_usage_percent !== null && stats.graphics_usage_percent !== null && (
|
||||||
<div className="flex gap-2 text-[10px] text-muted-foreground">
|
<div className="flex gap-2 text-xs text-muted-foreground">
|
||||||
<span>Compute: {stats.compute_usage_percent.toFixed(1)}%</span>
|
<span>Compute: {stats.compute_usage_percent.toFixed(1)}%</span>
|
||||||
<span>Graphics: {stats.graphics_usage_percent.toFixed(1)}%</span>
|
<span>Graphics: {stats.graphics_usage_percent.toFixed(1)}%</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -190,7 +190,7 @@ export function GpuDashboard({ gpuId, pollInterval = 2000 }: GpuDashboardProps)
|
|||||||
</span>
|
</span>
|
||||||
<span className="text-xs text-muted-foreground">°C</span>
|
<span className="text-xs text-muted-foreground">°C</span>
|
||||||
{stats.temperature_max_celsius && (
|
{stats.temperature_max_celsius && (
|
||||||
<span className="text-[10px] text-muted-foreground">
|
<span className="text-xs text-muted-foreground">
|
||||||
/ {stats.temperature_max_celsius.toFixed(0)}°C
|
/ {stats.temperature_max_celsius.toFixed(0)}°C
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
@@ -211,7 +211,7 @@ export function GpuDashboard({ gpuId, pollInterval = 2000 }: GpuDashboardProps)
|
|||||||
</span>
|
</span>
|
||||||
<span className="text-xs text-muted-foreground">W</span>
|
<span className="text-xs text-muted-foreground">W</span>
|
||||||
{stats.power_max_watts && (
|
{stats.power_max_watts && (
|
||||||
<span className="text-[10px] text-muted-foreground">
|
<span className="text-xs text-muted-foreground">
|
||||||
/ {stats.power_max_watts.toFixed(1)}W
|
/ {stats.power_max_watts.toFixed(1)}W
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -74,15 +74,15 @@ export function HardwareDashboard() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const getCpuColor = (usage: number): string => {
|
const getCpuColor = (usage: number): string => {
|
||||||
if (usage < 50) return 'bg-green-500';
|
if (usage < 50) return 'bg-success';
|
||||||
if (usage < 80) return 'bg-yellow-500';
|
if (usage < 80) return 'bg-warning';
|
||||||
return 'bg-red-500';
|
return 'bg-destructive';
|
||||||
};
|
};
|
||||||
|
|
||||||
const getRamColor = (percent: number): string => {
|
const getRamColor = (percent: number): string => {
|
||||||
if (percent < 60) return 'bg-blue-500';
|
if (percent < 60) return 'bg-success';
|
||||||
if (percent < 85) return 'bg-yellow-500';
|
if (percent < 85) return 'bg-warning';
|
||||||
return 'bg-red-500';
|
return 'bg-destructive';
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -174,9 +174,9 @@ export function HardwareDashboard() {
|
|||||||
<span className="text-muted-foreground">Usado</span>
|
<span className="text-muted-foreground">Usado</span>
|
||||||
<span className="font-medium">{stats.ram_percent.toFixed(1)}%</span>
|
<span className="font-medium">{stats.ram_percent.toFixed(1)}%</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="relative h-24 bg-muted rounded-lg overflow-hidden">
|
<div className="relative h-24 bg-hover rounded-lg overflow-hidden">
|
||||||
<div
|
<div
|
||||||
className={`absolute bottom-0 left-0 right-0 ${getRamColor(stats.ram_percent)} transition-all duration-300`}
|
className={`absolute bottom-0 left-0 right-0 ${getRamColor(stats.ram_percent)} opacity-60`}
|
||||||
style={{ height: `${stats.ram_percent}%` }}
|
style={{ height: `${stats.ram_percent}%` }}
|
||||||
/>
|
/>
|
||||||
<div className="absolute inset-0 flex items-center justify-center text-xs font-medium">
|
<div className="absolute inset-0 flex items-center justify-center text-xs font-medium">
|
||||||
|
|||||||
@@ -37,13 +37,13 @@ export function GpuSelector({ gpus }: GpuSelectorProps) {
|
|||||||
const iconClass = "h-5 w-5";
|
const iconClass = "h-5 w-5";
|
||||||
switch (vendor?.toUpperCase()) {
|
switch (vendor?.toUpperCase()) {
|
||||||
case 'NVIDIA':
|
case 'NVIDIA':
|
||||||
return <Zap className={cn(iconClass, "text-green-500")} />;
|
return <Zap className={cn(iconClass, "text-muted-foreground")} />;
|
||||||
case 'AMD':
|
case 'AMD':
|
||||||
return <Zap className={cn(iconClass, "text-red-500")} />;
|
return <Zap className={cn(iconClass, "text-muted-foreground")} />;
|
||||||
case 'INTEL':
|
case 'INTEL':
|
||||||
return <Cpu className={cn(iconClass, "text-blue-500")} />;
|
return <Cpu className={cn(iconClass, "text-muted-foreground")} />;
|
||||||
case 'APPLE':
|
case 'APPLE':
|
||||||
return <Monitor className={cn(iconClass, "text-gray-500")} />;
|
return <Monitor className={cn(iconClass, "text-muted-foreground")} />;
|
||||||
default:
|
default:
|
||||||
return <Monitor className={cn(iconClass, "text-muted-foreground")} />;
|
return <Monitor className={cn(iconClass, "text-muted-foreground")} />;
|
||||||
}
|
}
|
||||||
@@ -58,10 +58,10 @@ export function GpuSelector({ gpus }: GpuSelectorProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="w-full max-w-2xl mx-auto bg-muted/30 animate-in fade-in slide-in-from-bottom-4">
|
<Card className="w-full max-w-2xl mx-auto">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="flex items-center gap-2 text-lg">
|
<CardTitle className="flex items-center gap-2 text-lg">
|
||||||
<Monitor className="text-primary" />
|
<Monitor className="text-muted-foreground" />
|
||||||
Placas de Vídeo Detectadas
|
Placas de Vídeo Detectadas
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
@@ -79,11 +79,10 @@ export function GpuSelector({ gpus }: GpuSelectorProps) {
|
|||||||
key={gpu.id}
|
key={gpu.id}
|
||||||
onClick={() => setSelectedGpu(gpu.id)}
|
onClick={() => setSelectedGpu(gpu.id)}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative p-4 rounded-lg border-2 transition-all text-left",
|
"relative p-4 rounded-lg border transition-colors duration-150 text-left",
|
||||||
"hover:border-primary/50 hover:bg-accent/50",
|
|
||||||
isSelected
|
isSelected
|
||||||
? "border-primary bg-primary/10 shadow-md"
|
? "border-primary bg-accent-soft"
|
||||||
: "border-border bg-background"
|
: "border-border bg-background hover:border-muted-foreground/60 hover:bg-hover"
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{isSelected && (
|
{isSelected && (
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ export function HardwareScan({ specs, loading }: HardwareScanProps) {
|
|||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
<Card className="w-full max-w-md mx-auto border-primary/20">
|
<Card className="w-full max-w-md mx-auto">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="flex items-center gap-2">
|
<CardTitle className="flex items-center gap-2">
|
||||||
<Cpu className="animate-pulse text-primary" />
|
<Cpu className="animate-pulse text-primary" />
|
||||||
@@ -47,22 +47,22 @@ export function HardwareScan({ specs, loading }: HardwareScanProps) {
|
|||||||
const ramGB = (specs.total_memory / (1024 * 1024 * 1024)).toFixed(1);
|
const ramGB = (specs.total_memory / (1024 * 1024 * 1024)).toFixed(1);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="w-full max-w-md mx-auto bg-muted/30 animate-in fade-in slide-in-from-bottom-4">
|
<Card className="w-full max-w-md mx-auto animate-in fade-in duration-200 ease-out">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="flex items-center gap-2 text-lg">
|
<CardTitle className="flex items-center gap-2 text-lg">
|
||||||
<Laptop className="text-primary" />
|
<Laptop className="text-muted-foreground" />
|
||||||
Sistema Detectado
|
Sistema Detectado
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="grid grid-cols-2 gap-4">
|
<CardContent className="grid grid-cols-2 gap-4">
|
||||||
<div className="flex flex-col items-center p-3 bg-background rounded-lg border">
|
<div className="flex flex-col items-center p-3 bg-background rounded-lg border">
|
||||||
<HardDrive className="w-6 h-6 mb-2 text-muted-foreground" />
|
<HardDrive className="w-6 h-6 mb-2 text-muted-foreground" />
|
||||||
<span className="text-xl font-bold">{ramGB} GB</span>
|
<span className="text-xl font-semibold">{ramGB} GB</span>
|
||||||
<span className="text-xs text-muted-foreground">RAM Total</span>
|
<span className="text-xs text-muted-foreground">RAM Total</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col items-center p-3 bg-background rounded-lg border">
|
<div className="flex flex-col items-center p-3 bg-background rounded-lg border">
|
||||||
<Cpu className="w-6 h-6 mb-2 text-muted-foreground" />
|
<Cpu className="w-6 h-6 mb-2 text-muted-foreground" />
|
||||||
<span className="text-xl font-bold">{specs.cpu_count}</span>
|
<span className="text-xl font-semibold">{specs.cpu_count}</span>
|
||||||
<span className="text-xs text-muted-foreground">Núcleos CPU</span>
|
<span className="text-xs text-muted-foreground">Núcleos CPU</span>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|||||||
@@ -1,134 +0,0 @@
|
|||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -120,7 +120,7 @@ export function ModelSelector({ recommendation, onComplete }: ModelSelectorProps
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="w-full max-w-md mx-auto mt-6 border-primary shadow-lg">
|
<Card className="w-full max-w-md mx-auto mt-6">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<div className="flex justify-between items-start">
|
<div className="flex justify-between items-start">
|
||||||
<div>
|
<div>
|
||||||
@@ -132,7 +132,7 @@ export function ModelSelector({ recommendation, onComplete }: ModelSelectorProps
|
|||||||
</CardDescription>
|
</CardDescription>
|
||||||
</div>
|
</div>
|
||||||
{selectedModelId === recommendation.modelId && (
|
{selectedModelId === recommendation.modelId && (
|
||||||
<Badge variant="secondary" className="bg-green-100 text-green-800 hover:bg-green-100 dark:bg-green-900 dark:text-green-100">
|
<Badge variant="outline" className="bg-success/10 text-success border-success/30">
|
||||||
Recomendado
|
Recomendado
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
@@ -144,7 +144,7 @@ export function ModelSelector({ recommendation, onComplete }: ModelSelectorProps
|
|||||||
onValueChange={setSelectedModelId}
|
onValueChange={setSelectedModelId}
|
||||||
disabled={isDownloading}
|
disabled={isDownloading}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="w-full h-14 text-lg">
|
<SelectTrigger className="w-full h-14">
|
||||||
<SelectValue placeholder="Selecione um modelo" />
|
<SelectValue placeholder="Selecione um modelo" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
@@ -159,7 +159,7 @@ export function ModelSelector({ recommendation, onComplete }: ModelSelectorProps
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
|
||||||
<div className="bg-muted/50 p-4 rounded-md text-sm">
|
<div className="bg-background border p-4 rounded-md text-sm">
|
||||||
<p className="font-medium mb-1">Sobre este modelo:</p>
|
<p className="font-medium mb-1">Sobre este modelo:</p>
|
||||||
<p className="text-muted-foreground">
|
<p className="text-muted-foreground">
|
||||||
{selectedModelId === recommendation.modelId
|
{selectedModelId === recommendation.modelId
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ export function TitleBar() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="h-8 bg-sidebar border-b border-sidebar-border flex items-center justify-between select-none z-50 shrink-0"
|
className="h-8 bg-background border-b border-border flex items-center justify-between select-none z-50 shrink-0"
|
||||||
data-tauri-drag-region
|
data-tauri-drag-region
|
||||||
>
|
>
|
||||||
{/* Área de arrasto com logo/título */}
|
{/* Área de arrasto com logo/título */}
|
||||||
@@ -85,7 +85,7 @@ export function TitleBar() {
|
|||||||
className="flex items-center gap-2 px-4 h-full flex-1"
|
className="flex items-center gap-2 px-4 h-full flex-1"
|
||||||
data-tauri-drag-region
|
data-tauri-drag-region
|
||||||
>
|
>
|
||||||
<span className="text-sm font-medium text-sidebar-foreground">
|
<span className="text-xs font-medium text-muted-foreground">
|
||||||
OllaHub
|
OllaHub
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -94,27 +94,27 @@ export function TitleBar() {
|
|||||||
<div className="flex items-center h-full">
|
<div className="flex items-center h-full">
|
||||||
<button
|
<button
|
||||||
onClick={handleMinimize}
|
onClick={handleMinimize}
|
||||||
className="h-full w-12 flex items-center justify-center hover:bg-sidebar-accent transition-colors"
|
className="h-full w-12 flex items-center justify-center text-muted-foreground hover:bg-hover hover:text-foreground focus-visible:-outline-offset-2 transition-colors duration-150"
|
||||||
title="Minimizar"
|
title="Minimizar"
|
||||||
>
|
>
|
||||||
<Minus className="w-4 h-4 text-sidebar-foreground" />
|
<Minus className="w-4 h-4" />
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={handleMaximize}
|
onClick={handleMaximize}
|
||||||
className="h-full w-12 flex items-center justify-center hover:bg-sidebar-accent transition-colors"
|
className="h-full w-12 flex items-center justify-center text-muted-foreground hover:bg-hover hover:text-foreground focus-visible:-outline-offset-2 transition-colors duration-150"
|
||||||
title={isMaximized ? "Restaurar" : "Maximizar"}
|
title={isMaximized ? "Restaurar" : "Maximizar"}
|
||||||
>
|
>
|
||||||
<Square className={cn(
|
<Square className={cn(
|
||||||
"w-3.5 h-3.5 text-sidebar-foreground",
|
"w-3.5 h-3.5",
|
||||||
isMaximized && "opacity-60"
|
isMaximized && "opacity-60"
|
||||||
)} />
|
)} />
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={handleClose}
|
onClick={handleClose}
|
||||||
className="h-full w-12 flex items-center justify-center hover:bg-destructive transition-colors"
|
className="h-full w-12 flex items-center justify-center text-muted-foreground hover:bg-destructive hover:text-background focus-visible:-outline-offset-2 transition-colors duration-150"
|
||||||
title="Fechar"
|
title="Fechar"
|
||||||
>
|
>
|
||||||
<X className="w-4 h-4 text-sidebar-foreground" />
|
<X className="w-4 h-4" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,18 +5,18 @@ import { cva, type VariantProps } from "class-variance-authority"
|
|||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
const badgeVariants = cva(
|
const badgeVariants = cva(
|
||||||
"inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
"inline-flex h-6 items-center justify-center rounded-sm border px-2 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none aria-invalid:border-destructive transition-colors duration-150 overflow-hidden",
|
||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default:
|
default:
|
||||||
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
"border-transparent bg-foreground text-background [a&]:hover:bg-foreground/90",
|
||||||
secondary:
|
secondary:
|
||||||
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/80",
|
||||||
destructive:
|
destructive:
|
||||||
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
"border-transparent bg-destructive text-background [a&]:hover:bg-destructive/90",
|
||||||
outline:
|
outline:
|
||||||
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
"text-foreground [a&]:hover:bg-hover",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
defaultVariants: {
|
defaultVariants: {
|
||||||
|
|||||||
@@ -5,25 +5,25 @@ import { cva, type VariantProps } from "class-variance-authority"
|
|||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
const buttonVariants = cva(
|
const buttonVariants = cva(
|
||||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-[color,background-color,border-color,opacity] duration-150 ease-out disabled:pointer-events-none disabled:opacity-45 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 aria-invalid:border-destructive",
|
||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||||
destructive:
|
destructive:
|
||||||
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
"bg-destructive text-background hover:bg-destructive/90",
|
||||||
outline:
|
outline:
|
||||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
"border border-border bg-transparent hover:bg-hover",
|
||||||
secondary:
|
secondary:
|
||||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||||
ghost:
|
ghost:
|
||||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
"hover:bg-hover",
|
||||||
link: "text-primary underline-offset-4 hover:underline",
|
link: "text-foreground underline-offset-4 hover:underline",
|
||||||
},
|
},
|
||||||
size: {
|
size: {
|
||||||
default: "h-10 px-4 py-2 has-[>svg]:px-3",
|
default: "h-10 px-4 py-2 has-[>svg]:px-3",
|
||||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
sm: "h-8 gap-2 px-3 has-[>svg]:px-2",
|
||||||
lg: "h-12 rounded-md px-6 has-[>svg]:px-4",
|
lg: "h-12 px-6 has-[>svg]:px-4",
|
||||||
icon: "size-10",
|
icon: "size-10",
|
||||||
"icon-sm": "size-8",
|
"icon-sm": "size-8",
|
||||||
"icon-lg": "size-12",
|
"icon-lg": "size-12",
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ function Card({ className, ...props }: React.ComponentProps<"div">) {
|
|||||||
<div
|
<div
|
||||||
data-slot="card"
|
data-slot="card"
|
||||||
className={cn(
|
className={cn(
|
||||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ const Checkbox = React.forwardRef<
|
|||||||
<CheckboxPrimitive.Root
|
<CheckboxPrimitive.Root
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
|
"peer h-4 w-4 shrink-0 rounded-sm border border-muted-foreground ring-offset-background transition-colors duration-150 hover:border-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-45 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ function DialogOverlay({
|
|||||||
<DialogPrimitive.Overlay
|
<DialogPrimitive.Overlay
|
||||||
data-slot="dialog-overlay"
|
data-slot="dialog-overlay"
|
||||||
className={cn(
|
className={cn(
|
||||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-scrim",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -60,7 +60,7 @@ function DialogContent({
|
|||||||
<DialogPrimitive.Content
|
<DialogPrimitive.Content
|
||||||
data-slot="dialog-content"
|
data-slot="dialog-content"
|
||||||
className={cn(
|
className={cn(
|
||||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-float duration-200 ease-out sm:max-w-lg",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -69,7 +69,7 @@ function DialogContent({
|
|||||||
{showCloseButton && (
|
{showCloseButton && (
|
||||||
<DialogPrimitive.Close
|
<DialogPrimitive.Close
|
||||||
data-slot="dialog-close"
|
data-slot="dialog-close"
|
||||||
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
className="text-muted-foreground absolute top-3 right-3 rounded-sm p-1 transition-colors duration-150 hover:bg-hover hover:text-foreground disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||||
>
|
>
|
||||||
<XIcon />
|
<XIcon />
|
||||||
<span className="sr-only">Close</span>
|
<span className="sr-only">Close</span>
|
||||||
@@ -110,7 +110,7 @@ function DialogTitle({
|
|||||||
return (
|
return (
|
||||||
<DialogPrimitive.Title
|
<DialogPrimitive.Title
|
||||||
data-slot="dialog-title"
|
data-slot="dialog-title"
|
||||||
className={cn("text-lg leading-none font-semibold", className)}
|
className={cn("text-lg leading-tight font-semibold", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ const DropdownMenuSubTrigger = React.forwardRef<
|
|||||||
<DropdownMenuPrimitive.SubTrigger
|
<DropdownMenuPrimitive.SubTrigger
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",
|
"flex cursor-default select-none items-center rounded-sm px-2 py-2 text-sm outline-none focus:bg-hover data-[state=open]:bg-hover",
|
||||||
inset && "pl-8",
|
inset && "pl-8",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
@@ -45,7 +45,7 @@ const DropdownMenuSubContent = React.forwardRef<
|
|||||||
<DropdownMenuPrimitive.SubContent
|
<DropdownMenuPrimitive.SubContent
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-float data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -63,7 +63,7 @@ const DropdownMenuContent = React.forwardRef<
|
|||||||
ref={ref}
|
ref={ref}
|
||||||
sideOffset={sideOffset}
|
sideOffset={sideOffset}
|
||||||
className={cn(
|
className={cn(
|
||||||
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-float data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -81,7 +81,7 @@ const DropdownMenuItem = React.forwardRef<
|
|||||||
<DropdownMenuPrimitive.Item
|
<DropdownMenuPrimitive.Item
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
"relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-2 text-sm outline-none transition-colors duration-150 focus:bg-hover data-[disabled]:pointer-events-none data-[disabled]:opacity-45",
|
||||||
inset && "pl-8",
|
inset && "pl-8",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
@@ -97,7 +97,7 @@ const DropdownMenuCheckboxItem = React.forwardRef<
|
|||||||
<DropdownMenuPrimitive.CheckboxItem
|
<DropdownMenuPrimitive.CheckboxItem
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
"relative flex cursor-default select-none items-center rounded-sm py-2 pl-8 pr-2 text-sm outline-none transition-colors duration-150 focus:bg-hover data-[disabled]:pointer-events-none data-[disabled]:opacity-45",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
checked={checked}
|
checked={checked}
|
||||||
@@ -121,7 +121,7 @@ const DropdownMenuRadioItem = React.forwardRef<
|
|||||||
<DropdownMenuPrimitive.RadioItem
|
<DropdownMenuPrimitive.RadioItem
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
"relative flex cursor-default select-none items-center rounded-sm py-2 pl-8 pr-2 text-sm outline-none transition-colors duration-150 focus:bg-hover data-[disabled]:pointer-events-none data-[disabled]:opacity-45",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -145,7 +145,7 @@ const DropdownMenuLabel = React.forwardRef<
|
|||||||
<DropdownMenuPrimitive.Label
|
<DropdownMenuPrimitive.Label
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
"px-2 py-1.5 text-sm font-semibold",
|
"px-2 py-2 text-xs font-medium text-muted-foreground",
|
||||||
inset && "pl-8",
|
inset && "pl-8",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
@@ -160,7 +160,7 @@ const DropdownMenuSeparator = React.forwardRef<
|
|||||||
>(({ className, ...props }, ref) => (
|
>(({ className, ...props }, ref) => (
|
||||||
<DropdownMenuPrimitive.Separator
|
<DropdownMenuPrimitive.Separator
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
className={cn("-mx-1 my-1 h-px bg-border", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
))
|
))
|
||||||
@@ -172,7 +172,7 @@ const DropdownMenuShortcut = ({
|
|||||||
}: React.HTMLAttributes<HTMLSpanElement>) => {
|
}: React.HTMLAttributes<HTMLSpanElement>) => {
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
|
className={cn("ml-auto font-mono text-xs text-muted-foreground", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
|||||||
<input
|
<input
|
||||||
type={type}
|
type={type}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background transition-colors duration-150 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground hover:border-muted-foreground/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-45 disabled:hover:border-input",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
|
|||||||
@@ -10,13 +10,13 @@ const Progress = React.forwardRef<
|
|||||||
<ProgressPrimitive.Root
|
<ProgressPrimitive.Root
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative h-4 w-full overflow-hidden rounded-full bg-secondary",
|
"relative h-2 w-full overflow-hidden rounded-full bg-secondary",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<ProgressPrimitive.Indicator
|
<ProgressPrimitive.Indicator
|
||||||
className="h-full w-full flex-1 bg-primary transition-all"
|
className="h-full w-full flex-1 bg-primary transition-transform duration-200 ease-out"
|
||||||
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
|
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
|
||||||
/>
|
/>
|
||||||
</ProgressPrimitive.Root>
|
</ProgressPrimitive.Root>
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ const ResizableHandle = ({
|
|||||||
}) => (
|
}) => (
|
||||||
<ResizablePrimitive.PanelResizeHandle
|
<ResizablePrimitive.PanelResizeHandle
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",
|
"relative flex w-px items-center justify-center bg-border transition-colors duration-150 data-[resize-handle-state=hover]:bg-muted-foreground/60 data-[resize-handle-state=drag]:bg-primary after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|||||||
@@ -17,14 +17,14 @@ const SelectTrigger = React.forwardRef<
|
|||||||
<SelectPrimitive.Trigger
|
<SelectPrimitive.Trigger
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 [&>span]:truncate [&>span]:min-w-0",
|
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background transition-colors duration-150 placeholder:text-muted-foreground hover:border-muted-foreground/60 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-45 disabled:hover:border-input [&>span]:line-clamp-1 [&>span]:truncate [&>span]:min-w-0",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
<SelectPrimitive.Icon asChild>
|
<SelectPrimitive.Icon asChild>
|
||||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
||||||
</SelectPrimitive.Icon>
|
</SelectPrimitive.Icon>
|
||||||
</SelectPrimitive.Trigger>
|
</SelectPrimitive.Trigger>
|
||||||
))
|
))
|
||||||
@@ -73,7 +73,7 @@ const SelectContent = React.forwardRef<
|
|||||||
<SelectPrimitive.Content
|
<SelectPrimitive.Content
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-float data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||||
position === "popper" &&
|
position === "popper" &&
|
||||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||||
className
|
className
|
||||||
@@ -103,7 +103,7 @@ const SelectLabel = React.forwardRef<
|
|||||||
>(({ className, ...props }, ref) => (
|
>(({ className, ...props }, ref) => (
|
||||||
<SelectPrimitive.Label
|
<SelectPrimitive.Label
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
|
className={cn("py-2 pl-8 pr-2 text-xs font-medium text-muted-foreground", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
))
|
))
|
||||||
@@ -116,7 +116,7 @@ const SelectItem = React.forwardRef<
|
|||||||
<SelectPrimitive.Item
|
<SelectPrimitive.Item
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
"relative flex w-full cursor-default select-none items-center rounded-sm py-2 pl-8 pr-2 text-sm outline-none transition-colors duration-150 focus:bg-hover data-[state=checked]:bg-accent-soft data-[disabled]:pointer-events-none data-[disabled]:opacity-45",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -138,7 +138,7 @@ const SelectSeparator = React.forwardRef<
|
|||||||
>(({ className, ...props }, ref) => (
|
>(({ className, ...props }, ref) => (
|
||||||
<SelectPrimitive.Separator
|
<SelectPrimitive.Separator
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
className={cn("-mx-1 my-1 h-px bg-border", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
))
|
))
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ const Slider = React.forwardRef<
|
|||||||
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
|
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
|
||||||
<SliderPrimitive.Range className="absolute h-full bg-primary" />
|
<SliderPrimitive.Range className="absolute h-full bg-primary" />
|
||||||
</SliderPrimitive.Track>
|
</SliderPrimitive.Track>
|
||||||
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
|
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors duration-150 hover:bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-45" />
|
||||||
</SliderPrimitive.Root>
|
</SliderPrimitive.Root>
|
||||||
))
|
))
|
||||||
Slider.displayName = SliderPrimitive.Root.displayName
|
Slider.displayName = SliderPrimitive.Root.displayName
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ const Switch = React.forwardRef<
|
|||||||
>(({ className, ...props }, ref) => (
|
>(({ className, ...props }, ref) => (
|
||||||
<SwitchPrimitives.Root
|
<SwitchPrimitives.Root
|
||||||
className={cn(
|
className={cn(
|
||||||
"peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
|
"peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-45 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input hover:data-[state=unchecked]:bg-muted-foreground/50",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -19,7 +19,7 @@ const Switch = React.forwardRef<
|
|||||||
>
|
>
|
||||||
<SwitchPrimitives.Thumb
|
<SwitchPrimitives.Thumb
|
||||||
className={cn(
|
className={cn(
|
||||||
"pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"
|
"pointer-events-none block h-4 w-4 rounded-full bg-foreground transition-transform duration-150 ease-out data-[state=checked]:translate-x-4 data-[state=checked]:bg-primary-foreground data-[state=unchecked]:translate-x-0"
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
</SwitchPrimitives.Root>
|
</SwitchPrimitives.Root>
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ function TabsList({
|
|||||||
<TabsPrimitive.List
|
<TabsPrimitive.List
|
||||||
data-slot="tabs-list"
|
data-slot="tabs-list"
|
||||||
className={cn(
|
className={cn(
|
||||||
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
|
"bg-muted text-muted-foreground inline-flex h-10 w-fit items-center justify-center rounded-lg p-1",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -42,7 +42,7 @@ function TabsTrigger({
|
|||||||
<TabsPrimitive.Trigger
|
<TabsPrimitive.Trigger
|
||||||
data-slot="tabs-trigger"
|
data-slot="tabs-trigger"
|
||||||
className={cn(
|
className={cn(
|
||||||
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
"text-muted-foreground hover:text-foreground hover:bg-hover data-[state=active]:bg-accent-soft data-[state=active]:text-foreground data-[state=active]:hover:bg-accent-soft inline-flex h-full flex-1 items-center justify-center gap-2 rounded-md px-2 py-1 text-sm font-medium whitespace-nowrap transition-colors duration-150 disabled:pointer-events-none disabled:opacity-45 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ const Textarea = React.forwardRef<
|
|||||||
return (
|
return (
|
||||||
<textarea
|
<textarea
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
"flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm transition-colors duration-150 placeholder:text-muted-foreground hover:border-muted-foreground/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-45 disabled:hover:border-input",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ const TooltipContent = React.forwardRef<
|
|||||||
ref={ref}
|
ref={ref}
|
||||||
sideOffset={sideOffset}
|
sideOffset={sideOffset}
|
||||||
className={cn(
|
className={cn(
|
||||||
"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
"z-50 overflow-hidden rounded-sm border bg-popover px-2 py-1 text-xs text-popover-foreground shadow-float animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|||||||
@@ -1,276 +0,0 @@
|
|||||||
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([]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,265 +0,0 @@
|
|||||||
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({});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
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' });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
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');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
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?');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,134 +0,0 @@
|
|||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
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([]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,164 +0,0 @@
|
|||||||
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');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -206,7 +206,7 @@ export async function analyzeQueryContext(
|
|||||||
complexity: analysis.complexity || 'moderate',
|
complexity: analysis.complexity || 'moderate',
|
||||||
};
|
};
|
||||||
|
|
||||||
chatLog.info(`[ContextualAnalysis] Contexto extraído: ${context.intent}, ${context.entities.length} entidades, ${context.topics.length} tópicos`);
|
chatLog.success(`[ContextualAnalysis] Contexto extraído: ${context.intent}, ${context.entities.length} entidades, ${context.topics.length} tópicos`);
|
||||||
|
|
||||||
return context;
|
return context;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -1,68 +0,0 @@
|
|||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,124 +0,0 @@
|
|||||||
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']);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -176,7 +176,7 @@ export async function enrichQueries(
|
|||||||
result.expanded.length +
|
result.expanded.length +
|
||||||
result.contextual.length;
|
result.contextual.length;
|
||||||
|
|
||||||
chatLog.info(
|
chatLog.success(
|
||||||
`[QueryEnricher] ${totalQueries} queries geradas: ` +
|
`[QueryEnricher] ${totalQueries} queries geradas: ` +
|
||||||
`${result.literal.length} literal, ${result.semantic.length} semântica, ` +
|
`${result.literal.length} literal, ${result.semantic.length} semântica, ` +
|
||||||
`${result.related.length} relacionadas, ${result.expanded.length} expandidas, ` +
|
`${result.related.length} relacionadas, ${result.expanded.length} expandidas, ` +
|
||||||
|
|||||||
@@ -1,61 +0,0 @@
|
|||||||
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]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,127 +0,0 @@
|
|||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -97,7 +97,7 @@ export function calculateSemanticSimilarity(
|
|||||||
if (context.keywords.length > 0) {
|
if (context.keywords.length > 0) {
|
||||||
let keywordMatches = 0;
|
let keywordMatches = 0;
|
||||||
for (const keyword of context.keywords) {
|
for (const keyword of context.keywords) {
|
||||||
const keywordLower = normalizeText(keyword);
|
const keywordLower = keyword.toLowerCase();
|
||||||
if (normalizedChunk.includes(keywordLower)) {
|
if (normalizedChunk.includes(keywordLower)) {
|
||||||
keywordMatches++;
|
keywordMatches++;
|
||||||
}
|
}
|
||||||
@@ -111,7 +111,7 @@ export function calculateSemanticSimilarity(
|
|||||||
if (context.entities.length > 0) {
|
if (context.entities.length > 0) {
|
||||||
let entityMatches = 0;
|
let entityMatches = 0;
|
||||||
for (const entity of context.entities) {
|
for (const entity of context.entities) {
|
||||||
const entityLower = normalizeText(entity.value);
|
const entityLower = entity.value.toLowerCase();
|
||||||
// Buscar entidade completa (case-insensitive)
|
// Buscar entidade completa (case-insensitive)
|
||||||
if (normalizedChunk.includes(entityLower)) {
|
if (normalizedChunk.includes(entityLower)) {
|
||||||
entityMatches += entity.confidence; // Ponderar por confiança
|
entityMatches += entity.confidence; // Ponderar por confiança
|
||||||
@@ -126,7 +126,7 @@ export function calculateSemanticSimilarity(
|
|||||||
if (context.topics.length > 0) {
|
if (context.topics.length > 0) {
|
||||||
let topicMatches = 0;
|
let topicMatches = 0;
|
||||||
for (const topic of context.topics) {
|
for (const topic of context.topics) {
|
||||||
const topicLower = normalizeText(topic);
|
const topicLower = topic.toLowerCase();
|
||||||
// Verificar se tópico aparece no chunk (pode ser parcial)
|
// Verificar se tópico aparece no chunk (pode ser parcial)
|
||||||
const topicWords = topicLower.split(/\s+/);
|
const topicWords = topicLower.split(/\s+/);
|
||||||
const matches = topicWords.filter(word =>
|
const matches = topicWords.filter(word =>
|
||||||
@@ -147,7 +147,7 @@ export function calculateSemanticSimilarity(
|
|||||||
if (context.synonyms.length > 0) {
|
if (context.synonyms.length > 0) {
|
||||||
let synonymMatches = 0;
|
let synonymMatches = 0;
|
||||||
for (const synonym of context.synonyms) {
|
for (const synonym of context.synonyms) {
|
||||||
const synonymLower = normalizeText(synonym);
|
const synonymLower = synonym.toLowerCase();
|
||||||
if (normalizedChunk.includes(synonymLower)) {
|
if (normalizedChunk.includes(synonymLower)) {
|
||||||
synonymMatches++;
|
synonymMatches++;
|
||||||
}
|
}
|
||||||
@@ -163,18 +163,18 @@ export function calculateSemanticSimilarity(
|
|||||||
// Verificar se contexto temporal/geográfico aparece no chunk
|
// Verificar se contexto temporal/geográfico aparece no chunk
|
||||||
let contextualScore = 0;
|
let contextualScore = 0;
|
||||||
if (context.temporalContext?.period) {
|
if (context.temporalContext?.period) {
|
||||||
if (normalizedChunk.includes(normalizeText(context.temporalContext.period))) {
|
if (normalizedChunk.includes(context.temporalContext.period)) {
|
||||||
contextualScore += 0.5;
|
contextualScore += 0.5;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (context.temporalContext?.relative) {
|
if (context.temporalContext?.relative) {
|
||||||
const relativeTerms = ['recente', 'atual', 'novo', 'ultimo', 'atualizado'];
|
const relativeTerms = ['recente', 'atual', 'novo', 'último', 'atualizado'];
|
||||||
if (relativeTerms.some(term => normalizedChunk.includes(term))) {
|
if (relativeTerms.some(term => normalizedChunk.includes(term))) {
|
||||||
contextualScore += 0.3;
|
contextualScore += 0.3;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (context.geographicContext?.location) {
|
if (context.geographicContext?.location) {
|
||||||
const locationLower = normalizeText(context.geographicContext.location);
|
const locationLower = context.geographicContext.location.toLowerCase();
|
||||||
if (normalizedChunk.includes(locationLower)) {
|
if (normalizedChunk.includes(locationLower)) {
|
||||||
contextualScore += 0.5;
|
contextualScore += 0.5;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,184 +0,0 @@
|
|||||||
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 });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -363,17 +363,16 @@ export async function executeProgressiveSearch(
|
|||||||
const timeoutPromise = new Promise<QueryResult[]>((_, reject) => {
|
const timeoutPromise = new Promise<QueryResult[]>((_, reject) => {
|
||||||
setTimeout(() => reject(new Error(`Round ${round} timeout após ${actualRoundTimeout}ms`)), actualRoundTimeout);
|
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[];
|
let queryResults: QueryResult[];
|
||||||
try {
|
try {
|
||||||
queryResults = await Promise.race([roundPromise, timeoutPromise]);
|
queryResults = await Promise.race([roundPromise, timeoutPromise]);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
chatLog.warn(`[Round ${round}] Timeout do round após ${actualRoundTimeout}ms, usando resultados parciais`);
|
chatLog.warn(`[Round ${round}] Timeout do round após ${actualRoundTimeout}ms, usando resultados parciais`);
|
||||||
// Resultados parciais: só as queries que já completaram
|
// Tentar obter resultados parciais das promises que já completaram
|
||||||
queryResults = [...completedResults];
|
queryResults = await Promise.allSettled(queryPromises).then(results =>
|
||||||
|
results.map(r => r.status === 'fulfilled' ? r.value : { query: '', results: [] })
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Agregar resultados de todas as queries do round
|
// Agregar resultados de todas as queries do round
|
||||||
|
|||||||
+2
-6
@@ -7,7 +7,6 @@
|
|||||||
"build": "next build",
|
"build": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"lint": "eslint",
|
"lint": "eslint",
|
||||||
"test": "vitest run",
|
|
||||||
"generate-changelog": "node scripts/generate-changelog.js",
|
"generate-changelog": "node scripts/generate-changelog.js",
|
||||||
"bump-version": "node scripts/bump-version.js"
|
"bump-version": "node scripts/bump-version.js"
|
||||||
},
|
},
|
||||||
@@ -32,6 +31,7 @@
|
|||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"emoji-regex": "^10.6.0",
|
"emoji-regex": "^10.6.0",
|
||||||
"framer-motion": "^12.23.24",
|
"framer-motion": "^12.23.24",
|
||||||
|
"geist": "^1.9.2",
|
||||||
"lucide-react": "^0.554.0",
|
"lucide-react": "^0.554.0",
|
||||||
"next": "16.0.3",
|
"next": "16.0.3",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
@@ -48,18 +48,14 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/postcss": "^4",
|
"@tailwindcss/postcss": "^4",
|
||||||
"@tauri-apps/cli": "^2.9.4",
|
"@tauri-apps/cli": "^2.9.4",
|
||||||
"@testing-library/dom": "^10.4.2",
|
|
||||||
"@testing-library/react": "^16.3.3",
|
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
"eslint": "^9",
|
"eslint": "^9",
|
||||||
"eslint-config-next": "16.0.3",
|
"eslint-config-next": "16.0.3",
|
||||||
"happy-dom": "^21.0.4",
|
|
||||||
"raw-loader": "^4.0.2",
|
"raw-loader": "^4.0.2",
|
||||||
"tailwindcss": "^4",
|
"tailwindcss": "^4",
|
||||||
"tw-animate-css": "^1.4.0",
|
"tw-animate-css": "^1.4.0",
|
||||||
"typescript": "^5",
|
"typescript": "^5"
|
||||||
"vitest": "^5.1.0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Generated
+12
-804
File diff suppressed because it is too large.
Load diff
@@ -1,166 +0,0 @@
|
|||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
// 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,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
import { afterEach } from 'vitest';
|
|
||||||
import { cleanup } from '@testing-library/react';
|
|
||||||
|
|
||||||
// Sem `globals: true` o Testing Library não registra o cleanup sozinho.
|
|
||||||
afterEach(cleanup);
|
|
||||||
Reference in new issue
Block a user