Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07b0eaadca | ||
|
|
f0b7db8c12 | ||
|
|
2835957e40 | ||
|
|
3e57b78aa7 | ||
|
|
cde8e5ac00 | ||
|
|
6fdbd4bfe6 | ||
|
|
d01d26e74f | ||
|
|
e51a54c568 | ||
|
|
a319a9cf8d | ||
|
|
1daa6c77ee | ||
|
|
3e5727ffc7 | ||
|
|
162a6f37f7 | ||
|
|
6c366eecb0 | ||
|
|
6cdc8d4294 | ||
|
|
0d19f496bb | ||
|
|
e53e49c8f8 | ||
|
|
ba03131a78 | ||
|
|
1a64f5aa18 | ||
|
|
7d169d8a61 |
No files matched your search
@@ -1,569 +0,0 @@
|
|||||||
---
|
|
||||||
name: Integração llama.cpp nativo e download Hugging Face
|
|
||||||
overview: Implementar download direto de modelos GGUF do Hugging Face, integração com llama.cpp nativo via Rust, listagem de modelos locais e UI experimental para alternar entre Ollama e llama.cpp nativo.
|
|
||||||
todos:
|
|
||||||
- id: hf-download-module
|
|
||||||
content: Criar módulo huggingface_download.rs com download_gguf_model() e streaming de progresso
|
|
||||||
status: pending
|
|
||||||
- id: hf-list-models
|
|
||||||
content: Implementar list_huggingface_gguf_models() com cache de metadados (TTL 1h)
|
|
||||||
status: pending
|
|
||||||
- id: hf-validation
|
|
||||||
content: Adicionar validação SHA256 obrigatória quando disponível, retry logic com resume e rate limiting (429)
|
|
||||||
status: pending
|
|
||||||
- id: hf-rate-limiting
|
|
||||||
content: Implementar tratamento de rate limiting com Retry-After header e backoff exponencial
|
|
||||||
status: pending
|
|
||||||
- id: llama-cpp-deps
|
|
||||||
content: Adicionar llama_cpp 0.4 no Cargo.toml com features condicionais por OS + feature flag dev-no-llama
|
|
||||||
status: pending
|
|
||||||
- id: llama-deps-parsing
|
|
||||||
content: Adicionar dependências gguf 0.1 e lru 0.12 para parsing de metadados e cache LRU
|
|
||||||
status: pending
|
|
||||||
- id: llama-state
|
|
||||||
content: Criar LlamaCppState com LRU cache (limite 3 modelos) para prevenir memory leaks
|
|
||||||
status: pending
|
|
||||||
- id: models-dir-structure
|
|
||||||
content: Implementar get_models_dir() com estrutura hierárquica cross-platform (repo_owner/repo_name/quantization)
|
|
||||||
status: pending
|
|
||||||
- id: llama-chat-stream
|
|
||||||
content: Implementar chat_stream_native() com streaming de tokens via llama-cpp-rs
|
|
||||||
status: pending
|
|
||||||
- id: llama-params
|
|
||||||
content: Adicionar configuração de parâmetros (n_gpu_layers, n_ctx, threads) no settings store
|
|
||||||
status: pending
|
|
||||||
- id: local-scan
|
|
||||||
content: Implementar list_local_gguf_models() com scan recursivo e parsing de metadados via crate gguf
|
|
||||||
status: pending
|
|
||||||
- id: local-cache
|
|
||||||
content: Adicionar cache de metadados de modelos locais para evitar re-scan frequente
|
|
||||||
status: pending
|
|
||||||
- id: quantization-regex
|
|
||||||
content: "Implementar regex corrigido para extração de quantização: [._-](Q\\d+_?[KM]?_?[MS]?|[FI]P?\\d+)[._-]"
|
|
||||||
status: pending
|
|
||||||
- id: vram-detection
|
|
||||||
content: Adicionar detecção de VRAM disponível via sysinfo antes de carregar modelos grandes
|
|
||||||
status: pending
|
|
||||||
- id: concurrent-downloads
|
|
||||||
content: Implementar semáforo para limitar downloads paralelos a 2 simultâneos
|
|
||||||
status: pending
|
|
||||||
- id: ui-runtime-toggle
|
|
||||||
content: Criar toggle de runtime (Ollama/llama.cpp) nas configurações com indicador visual
|
|
||||||
status: pending
|
|
||||||
- id: ui-hf-selector
|
|
||||||
content: Implementar seletor de modelos Hugging Face com busca e filtros de quantização
|
|
||||||
status: pending
|
|
||||||
- id: ui-integration
|
|
||||||
content: Integrar runtime selection no use-chat.ts para alternar entre chat_stream e chat_stream_native
|
|
||||||
status: pending
|
|
||||||
isProject: false
|
|
||||||
---
|
|
||||||
|
|
||||||
# Plano de Implementação: Integração llama.cpp e Download Hugging Face
|
|
||||||
|
|
||||||
## Contexto Arquitetural
|
|
||||||
|
|
||||||
O projeto atualmente usa Ollama como runtime de modelos via HTTP (`http://localhost:11434`). O chat streaming é feito através de `chat_stream` que chama `OllamaClient`. Modelos são baixados via `pull_model` que usa a API do Ollama. Existe suporte básico para instalar modelos GGUF locais via `install_gguf_model`.
|
|
||||||
|
|
||||||
**Decisão arquitetural:** Implementar runtime dual (Ollama + llama.cpp nativo) com abstração no backend Rust para permitir alternância transparente no frontend.
|
|
||||||
|
|
||||||
## Estrutura de Armazenamento
|
|
||||||
|
|
||||||
- **Modelos Ollama:** `~/.ollama/models` (Linux/Mac) ou `%USERPROFILE%\.ollama\models` (Windows)
|
|
||||||
- **Modelos llama.cpp nativo:** Estrutura hierárquica em `{app_data_dir}/models/gguf/{repo_owner}/{repo_name}/{quantization}/model.gguf`
|
|
||||||
- Exemplo: `~/.local/share/OllaHub/models/gguf/TheBloke/Mistral-7B-Instruct-v0.2-GGUF/Q4_K_M/mistral-7b-instruct-v0.2.Q4_K_M.gguf`
|
|
||||||
- **Cache de metadados:** `{app_data_dir}/cache/huggingface_models.json`
|
|
||||||
- **Cross-platform paths:**
|
|
||||||
- Windows: `%APPDATA%\Roaming\com.ollahub.app\models\gguf`
|
|
||||||
- Linux: `~/.local/share/com.ollahub.app/models/gguf`
|
|
||||||
- macOS: `~/Library/Application Support/com.ollahub.app/models/gguf`
|
|
||||||
|
|
||||||
## Fase 1: Backend - Download Direto Hugging Face
|
|
||||||
|
|
||||||
### 1.1 Módulo de Download (`src-tauri/src/huggingface_download.rs`)
|
|
||||||
|
|
||||||
**Contrato técnico:**
|
|
||||||
|
|
||||||
```rust
|
|
||||||
pub struct HuggingFaceModel {
|
|
||||||
pub id: String,
|
|
||||||
pub filename: String,
|
|
||||||
pub size: u64,
|
|
||||||
pub quantization: String, // Q4_K_M, Q5_K_S, etc.
|
|
||||||
pub sha256: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn download_gguf_model(
|
|
||||||
app_handle: AppHandle,
|
|
||||||
model_id: String,
|
|
||||||
filename: String,
|
|
||||||
quantization_filter: Option<String>,
|
|
||||||
window: Option<Window>,
|
|
||||||
) -> Result<PathBuf, String>
|
|
||||||
```
|
|
||||||
|
|
||||||
**Implementação:**
|
|
||||||
|
|
||||||
- Usar `reqwest` com streaming (já presente no `Cargo.toml`)
|
|
||||||
- API Hugging Face: `https://huggingface.co/api/models/{model_id}/tree/main`
|
|
||||||
- Download direto: `https://huggingface.co/{model_id}/resolve/main/{filename}`
|
|
||||||
- Emitir eventos `download-progress` (reutilizar estrutura existente de `pull_model_impl_window`)
|
|
||||||
- **Validação SHA256 obrigatória** quando disponível no Hugging Face (usar `sha2` já presente)
|
|
||||||
- Retry logic com backoff exponencial (3 tentativas)
|
|
||||||
- **Rate limiting:** Tratar 429 Too Many Requests com `Retry-After` header
|
|
||||||
- **Resume de download:** Verificar arquivo parcial e continuar de onde parou
|
|
||||||
|
|
||||||
**Arquivos:**
|
|
||||||
|
|
||||||
- Criar `src-tauri/src/huggingface_download.rs`
|
|
||||||
- Adicionar comando `download_gguf_model` em `lib.rs`
|
|
||||||
|
|
||||||
### 1.2 Busca de Modelos (`list_huggingface_gguf_models`)
|
|
||||||
|
|
||||||
**Contrato:**
|
|
||||||
|
|
||||||
```rust
|
|
||||||
pub async fn list_huggingface_gguf_models(
|
|
||||||
query: Option<String>,
|
|
||||||
quantization: Option<String>,
|
|
||||||
) -> Result<Vec<HuggingFaceModel>, String>
|
|
||||||
```
|
|
||||||
|
|
||||||
**Implementação:**
|
|
||||||
|
|
||||||
- Usar API pública do Hugging Face: `https://huggingface.co/api/models?search={query}&filter=gguf`
|
|
||||||
- Filtrar por arquivos `.gguf` no tree
|
|
||||||
- Cache local com TTL de 1 hora (evitar requests repetidos)
|
|
||||||
- **Extrair quantização do filename** (regex corrigido: `[._-](Q\d+_?[KM]?_?[MS]?|[FI]P?\d+)[._-]`)
|
|
||||||
- Suporta: `Q4_K_M`, `Q5_0`, `F16`, `FP32`, etc.
|
|
||||||
|
|
||||||
**Arquivos:**
|
|
||||||
|
|
||||||
- Adicionar função em `huggingface_download.rs`
|
|
||||||
- Comando `list_huggingface_gguf_models` em `lib.rs`
|
|
||||||
|
|
||||||
### 1.3 Cache de Metadados
|
|
||||||
|
|
||||||
**Estrutura:**
|
|
||||||
|
|
||||||
- Arquivo JSON em `{app_data_dir}/cache/huggingface_models.json`
|
|
||||||
- Estrutura: `{ "models": [...], "last_updated": "ISO8601" }`
|
|
||||||
- Atualizar cache apenas se `last_updated` > 1 hora
|
|
||||||
|
|
||||||
## Fase 2: Backend - Integração llama.cpp
|
|
||||||
|
|
||||||
### 2.1 Dependências (`Cargo.toml`)
|
|
||||||
|
|
||||||
**Correção crítica:** Usar `llama_cpp` (edgenai) versão 0.4 em vez de `llama-cpp-rs` 0.2
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[features]
|
|
||||||
default = ["llama-cpp"]
|
|
||||||
llama-cpp = ["dep:llama_cpp"]
|
|
||||||
dev-no-llama = [] # Skip llama.cpp em dev builds (builds 30-45 min podem ser lentos)
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
llama_cpp = { version = "0.4", optional = true }
|
|
||||||
|
|
||||||
# Features condicionais por OS (Metal/CUDA são mutuamente exclusivos)
|
|
||||||
[target.'cfg(target_os = "macos")'.dependencies]
|
|
||||||
llama_cpp = { version = "0.4", features = ["metal"], optional = true }
|
|
||||||
|
|
||||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
|
||||||
llama_cpp = { version = "0.4", features = ["cuda"], optional = true }
|
|
||||||
|
|
||||||
[target.'cfg(target_os = "windows")'.dependencies]
|
|
||||||
llama_cpp = { version = "0.4", features = ["cuda"], optional = true }
|
|
||||||
|
|
||||||
# Dependência para parsing de metadados GGUF
|
|
||||||
gguf = "0.1"
|
|
||||||
lru = "0.12" # Para LRU cache de modelos carregados
|
|
||||||
```
|
|
||||||
|
|
||||||
**Build considerations:**
|
|
||||||
|
|
||||||
- `llama_cpp` compila `llama.cpp` via build script
|
|
||||||
- **Tempo de build:** 30-45 min em máquinas mais fracas (não 10-15 min)
|
|
||||||
- Feature flag `dev-no-llama` permite builds rápidos em desenvolvimento
|
|
||||||
- Requer CMake/Ninja instalados (documentar no README)
|
|
||||||
|
|
||||||
### 2.2 Gerenciamento de Estado (`AppState`)
|
|
||||||
|
|
||||||
**Estrutura (com LRU cache para prevenir memory leaks):**
|
|
||||||
|
|
||||||
```rust
|
|
||||||
use lru::LruCache;
|
|
||||||
|
|
||||||
pub struct LlamaCppState {
|
|
||||||
models: Arc<Mutex<LruCache<String, LlamaModel>>>, // Limite de 3 modelos
|
|
||||||
default_params: LlamaParams,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LlamaCppState {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
models: Arc::new(Mutex::new(LruCache::new(3.try_into().unwrap()))),
|
|
||||||
default_params: LlamaParams::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct LlamaModel {
|
|
||||||
path: PathBuf,
|
|
||||||
context: Option<LlamaContext>, // Lazy loading
|
|
||||||
metadata: ModelMetadata,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Arquivos:**
|
|
||||||
|
|
||||||
- Criar `src-tauri/src/llama_cpp_state.rs`
|
|
||||||
- Registrar state em `main()` via `.manage()`
|
|
||||||
|
|
||||||
### 2.3 Comando de Chat Streaming (`chat_stream_native`)
|
|
||||||
|
|
||||||
**Contrato:**
|
|
||||||
|
|
||||||
```rust
|
|
||||||
#[command]
|
|
||||||
async fn chat_stream_native(
|
|
||||||
window: Window,
|
|
||||||
app_handle: AppHandle,
|
|
||||||
session_id: Option<String>,
|
|
||||||
messages: Vec<Message>,
|
|
||||||
model_path: String,
|
|
||||||
system_prompt: Option<String>,
|
|
||||||
params: Option<LlamaParams>,
|
|
||||||
) -> Result<String, String>
|
|
||||||
```
|
|
||||||
|
|
||||||
**Implementação:**
|
|
||||||
|
|
||||||
- Carregar modelo lazy (verificar se já está em `AppState`)
|
|
||||||
- Usar `llama-cpp-rs` para streaming de tokens
|
|
||||||
- Emitir eventos `chat-token` (mesmo formato que `chat_stream` atual)
|
|
||||||
- Reutilizar lógica de salvamento em DB existente
|
|
||||||
- Parâmetros: `n_gpu_layers`, `n_ctx`, `threads` (configuráveis via settings)
|
|
||||||
|
|
||||||
**Arquivos:**
|
|
||||||
|
|
||||||
- Criar `src-tauri/src/llama_cpp_chat.rs`
|
|
||||||
- Comando em `lib.rs`
|
|
||||||
- Integrar com `ProcessingState` existente
|
|
||||||
|
|
||||||
### 2.4 Configuração de Parâmetros
|
|
||||||
|
|
||||||
**Settings store (frontend):**
|
|
||||||
|
|
||||||
- Adicionar `llamaCppParams` em `settings-store.ts`:
|
|
||||||
```typescript
|
|
||||||
llamaCppParams: {
|
|
||||||
nGpuLayers: number;
|
|
||||||
nCtx: number;
|
|
||||||
threads: number;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
**Backend:**
|
|
||||||
|
|
||||||
- Struct `LlamaParams` serializável
|
|
||||||
- Valores padrão: `n_gpu_layers: 0` (CPU), `n_ctx: 4096`, `threads: auto`
|
|
||||||
|
|
||||||
## Fase 3: Backend - Listagem Local
|
|
||||||
|
|
||||||
### 3.1 Scan de Arquivos GGUF (`list_local_gguf_models`)
|
|
||||||
|
|
||||||
**Contrato:**
|
|
||||||
|
|
||||||
```rust
|
|
||||||
#[command]
|
|
||||||
fn list_local_gguf_models(app_handle: AppHandle) -> Result<Vec<LocalGgufModel>, String>
|
|
||||||
```
|
|
||||||
|
|
||||||
**Implementação:**
|
|
||||||
|
|
||||||
- Scan recursivo em `{app_data_dir}/models/gguf/` (estrutura hierárquica)
|
|
||||||
- Usar `walkdir` (já presente)
|
|
||||||
- **Parsing de metadados GGUF usando crate `gguf`:**
|
|
||||||
```rust
|
|
||||||
use gguf::GGUFFile;
|
|
||||||
|
|
||||||
pub fn extract_gguf_metadata(path: &Path) -> Result<GgufMetadata, String> {
|
|
||||||
let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
|
|
||||||
let gguf = GGUFFile::parse(file).map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
Ok(GgufMetadata {
|
|
||||||
architecture: gguf.header.metadata.get("general.architecture"),
|
|
||||||
quantization: gguf.header.metadata.get("general.quantization_version"),
|
|
||||||
parameter_count: gguf.header.metadata.get("general.parameter_count"),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- Extrair metadados:
|
|
||||||
- Tamanho do arquivo
|
|
||||||
- Quantização do filename (regex corrigido)
|
|
||||||
- **Arquitetura via parsing de header GGUF** (não inferir do filename)
|
|
||||||
- Cache de metadados para evitar re-scan frequente
|
|
||||||
|
|
||||||
**Estrutura de retorno:**
|
|
||||||
|
|
||||||
```rust
|
|
||||||
pub struct LocalGgufModel {
|
|
||||||
pub path: String,
|
|
||||||
pub name: String,
|
|
||||||
pub size: u64,
|
|
||||||
pub quantization: Option<String>,
|
|
||||||
pub architecture: Option<String>,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Arquivos:**
|
|
||||||
|
|
||||||
- Função em `lib.rs` ou módulo separado `src-tauri/src/local_models.rs`
|
|
||||||
|
|
||||||
### 3.2 Detecção Automática
|
|
||||||
|
|
||||||
- Ao baixar modelo do Hugging Face, adicionar à lista local automaticamente
|
|
||||||
- Verificar integridade (tamanho, extensão) antes de listar
|
|
||||||
|
|
||||||
## Fase 4: Frontend - UI Experimental
|
|
||||||
|
|
||||||
### 4.1 Settings Store - Runtime Selection
|
|
||||||
|
|
||||||
**Modificações em `store/settings-store.ts`:**
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
runtime: 'ollama' | 'llama-cpp';
|
|
||||||
llamaCppParams: { nGpuLayers: number; nCtx: number; threads: number };
|
|
||||||
setRuntime: (runtime: 'ollama' | 'llama-cpp') => void;
|
|
||||||
setLlamaCppParams: (params: Partial<LlamaCppParams>) => void;
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4.2 Toggle de Runtime (`components/settings/`)
|
|
||||||
|
|
||||||
**Componente:**
|
|
||||||
|
|
||||||
- Toggle switch "Usar llama.cpp nativo"
|
|
||||||
- **Indicador visual melhorado** com ícone + tooltip:
|
|
||||||
```tsx
|
|
||||||
<Badge variant={runtime === 'ollama' ? 'default' : 'secondary'}>
|
|
||||||
{runtime === 'ollama' ? (
|
|
||||||
<>🦙 Ollama</>
|
|
||||||
) : (
|
|
||||||
<>⚡ llama.cpp (nativo)</>
|
|
||||||
)}
|
|
||||||
</Badge>
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipContent>
|
|
||||||
{runtime === 'ollama'
|
|
||||||
? 'Usando Ollama como runtime (requer servidor externo)'
|
|
||||||
: 'Usando llama.cpp nativo (mais rápido, sem servidor externo)'}
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
```
|
|
||||||
|
|
||||||
- Desabilitar se nenhum modelo GGUF local disponível
|
|
||||||
|
|
||||||
**Arquivos:**
|
|
||||||
|
|
||||||
- Criar ou modificar `components/settings/runtime-settings-panel.tsx`
|
|
||||||
|
|
||||||
### 4.3 Seletor de Modelos Hugging Face
|
|
||||||
|
|
||||||
**Componente:**
|
|
||||||
|
|
||||||
- Input de busca
|
|
||||||
- Lista de modelos com filtros de quantização (Q4, Q5, Q8)
|
|
||||||
- Botão de download com progresso
|
|
||||||
- Integrar com `DownloadContext` existente
|
|
||||||
|
|
||||||
**Arquivos:**
|
|
||||||
|
|
||||||
- Criar `components/chat/huggingface-model-selector.tsx`
|
|
||||||
- Integrar em `components/chat/model-selector.tsx`
|
|
||||||
|
|
||||||
### 4.4 Página de Comparação
|
|
||||||
|
|
||||||
**Componente experimental:**
|
|
||||||
|
|
||||||
- Side-by-side: Ollama vs llama.cpp
|
|
||||||
- Mesmo prompt, comparar latência e qualidade
|
|
||||||
- Métricas: tokens/s, tempo total, uso de VRAM
|
|
||||||
|
|
||||||
**Arquivos:**
|
|
||||||
|
|
||||||
- Criar `app/benchmark/page.tsx` (opcional, pode ser feature flag)
|
|
||||||
|
|
||||||
### 4.5 Integração no Chat
|
|
||||||
|
|
||||||
**Modificações em `hooks/use-chat.ts`:**
|
|
||||||
|
|
||||||
- Verificar `runtime` do settings store
|
|
||||||
- Chamar `chat_stream` ou `chat_stream_native` conforme runtime
|
|
||||||
- Manter compatibilidade com código existente
|
|
||||||
|
|
||||||
**Arquivos:**
|
|
||||||
|
|
||||||
- Modificar `hooks/use-chat.ts`
|
|
||||||
- Atualizar `app/chat/page.tsx` se necessário
|
|
||||||
|
|
||||||
## Decisões Técnicas
|
|
||||||
|
|
||||||
### Abordagem Ingênua vs Sênior
|
|
||||||
|
|
||||||
| Aspecto | Ingênua | Sênior (Escolhida) |
|
|
||||||
|
|
||||||
|---------|---------|-------------------|
|
|
||||||
|
|
||||||
| Download | Polling de status | Streaming com eventos Tauri |
|
|
||||||
|
|
||||||
| Estado de Modelos | Sem cache | **LRU cache com limite de 3 modelos** |
|
|
||||||
|
|
||||||
| Integração Chat | Duplicar código | Abstração via enum Runtime |
|
|
||||||
|
|
||||||
| Validação | Apenas tamanho | **SHA256 obrigatório quando disponível** + tamanho + **parsing header GGUF** |
|
|
||||||
|
|
||||||
| Build llama.cpp | Sempre compilar | **Feature flags condicionais por OS + dev-no-llama** |
|
|
||||||
|
|
||||||
| Rate Limiting | Sem tratamento | **Backoff + Retry-After header** |
|
|
||||||
|
|
||||||
| Parsing Metadata | Inferir do filename | **Crate `gguf` para parsing correto** |
|
|
||||||
|
|
||||||
### Trade-offs
|
|
||||||
|
|
||||||
- **Performance:** llama.cpp nativo pode ser 10-30% mais rápido que Ollama (sem overhead HTTP)
|
|
||||||
- **Manutenção:** Duplicar lógica de chat aumenta complexidade; abstração Runtime reduz duplicação
|
|
||||||
- **VRAM:** llama.cpp permite controle fino de `n_gpu_layers`; Ollama gerencia automaticamente
|
|
||||||
|
|
||||||
### Modos de Falha
|
|
||||||
|
|
||||||
1. **Gargalo VRAM:** Modelos grandes podem não carregar; implementar fallback para CPU
|
|
||||||
|
|
||||||
- **Solução:** Usar `sysinfo` crate para detectar VRAM disponível antes de carregar
|
|
||||||
|
|
||||||
2. **Download interrompido:** Retry logic com resume (verificar se arquivo parcial existe)
|
|
||||||
3. **Build llama.cpp falha:** Feature flag `dev-no-llama` para desabilitar em desenvolvimento
|
|
||||||
4. **Latência de rede:** Cache agressivo de metadados do Hugging Face
|
|
||||||
5. **Rate limiting Hugging Face:** Tratar 429 com `Retry-After` header
|
|
||||||
6. **Concurrent downloads:** Limitar a 2 downloads paralelos com semáforo
|
|
||||||
7. **Memory leaks:** LRU cache com limite de 3 modelos previne crescimento indefinido
|
|
||||||
|
|
||||||
### Antipadrões a Evitar
|
|
||||||
|
|
||||||
- Não fazer polling de status de download (usar eventos)
|
|
||||||
- Não carregar todos os modelos na inicialização (lazy loading)
|
|
||||||
- Não duplicar lógica de streaming (abstrair Runtime)
|
|
||||||
- Não hardcodar paths (usar `app_data_dir`)
|
|
||||||
|
|
||||||
## Ordem de Implementação (Reordenada)
|
|
||||||
|
|
||||||
1. **Estrutura de diretórios e AppState** (fundação)
|
|
||||||
|
|
||||||
- Criar `get_models_dir()` com paths cross-platform
|
|
||||||
- Implementar `LlamaCppState` com LRU cache
|
|
||||||
|
|
||||||
2. **Listagem local de GGUF** (valida estrutura)
|
|
||||||
|
|
||||||
- `list_local_gguf_models()` com parsing via crate `gguf`
|
|
||||||
- Cache de metadados
|
|
||||||
|
|
||||||
3. **Download Hugging Face** (adiciona modelos)
|
|
||||||
|
|
||||||
- `download_gguf_model()` com SHA256 obrigatório
|
|
||||||
- Rate limiting e retry logic
|
|
||||||
|
|
||||||
4. **Parsing de metadados GGUF** (enriquece listagem)
|
|
||||||
|
|
||||||
- Integrar crate `gguf` para extrair arquitetura
|
|
||||||
|
|
||||||
5. **Integração llama.cpp** (runtime)
|
|
||||||
|
|
||||||
- `chat_stream_native()` com lazy loading
|
|
||||||
- Detecção de VRAM via `sysinfo`
|
|
||||||
|
|
||||||
6. **UI experimental** (camada final)
|
|
||||||
|
|
||||||
- Toggle de runtime com indicador melhorado
|
|
||||||
- Integração no `use-chat.ts`
|
|
||||||
|
|
||||||
## Validação
|
|
||||||
|
|
||||||
**Comandos de teste (Windows PowerShell):**
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
# Verificar modelos baixados
|
|
||||||
Get-ChildItem "$env:APPDATA\OllaHub\models\gguf" -Recurse -Filter "*.gguf"
|
|
||||||
|
|
||||||
# Testar download (via Tauri command)
|
|
||||||
# Usar DevTools do app para invocar: download_gguf_model
|
|
||||||
```
|
|
||||||
|
|
||||||
**Comandos de teste (Linux Bash):**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Verificar modelos baixados
|
|
||||||
find ~/.local/share/com.ollahub.app/models/gguf -name "*.gguf"
|
|
||||||
|
|
||||||
# Testar build llama.cpp (com feature flag)
|
|
||||||
cargo build --features llama-cpp # Build completo
|
|
||||||
cargo build --no-default-features --features dev-no-llama # Build rápido (dev)
|
|
||||||
|
|
||||||
# Verificar VRAM disponível (se NVIDIA)
|
|
||||||
nvidia-smi --query-gpu=memory.free --format=csv
|
|
||||||
```
|
|
||||||
|
|
||||||
## Correções Críticas Aplicadas
|
|
||||||
|
|
||||||
### 1. Crate llama.cpp
|
|
||||||
|
|
||||||
- ✅ Alterado de `llama-cpp-rs = "0.2"` para `llama_cpp = "0.4"` (edgenai, mais estável)
|
|
||||||
|
|
||||||
### 2. Feature Flags
|
|
||||||
|
|
||||||
- ✅ Features condicionais por OS (Metal/CUDA mutuamente exclusivos)
|
|
||||||
- ✅ Feature flag `dev-no-llama` para builds rápidos em desenvolvimento
|
|
||||||
|
|
||||||
### 3. Parsing de Metadados
|
|
||||||
|
|
||||||
- ✅ Adicionada dependência `gguf = "0.1"` para parsing correto de headers GGUF
|
|
||||||
- ✅ Removida inferência de arquitetura do filename
|
|
||||||
|
|
||||||
### 4. Memory Management
|
|
||||||
|
|
||||||
- ✅ Substituído `HashMap` por `LruCache` com limite de 3 modelos
|
|
||||||
|
|
||||||
### 5. Validação SHA256
|
|
||||||
|
|
||||||
- ✅ Tornada obrigatória quando disponível no Hugging Face
|
|
||||||
|
|
||||||
### 6. Rate Limiting
|
|
||||||
|
|
||||||
- ✅ Implementado tratamento de 429 com `Retry-After` header
|
|
||||||
|
|
||||||
### 7. Estrutura de Diretórios
|
|
||||||
|
|
||||||
- ✅ Hierárquica: `{repo_owner}/{repo_name}/{quantization}/model.gguf`
|
|
||||||
|
|
||||||
### 8. Regex de Quantização
|
|
||||||
|
|
||||||
- ✅ Corrigido: `[._-](Q\d+_?[KM]?_?[MS]?|[FI]P?\d+)[._-]`
|
|
||||||
|
|
||||||
### 9. Cross-Platform Paths
|
|
||||||
|
|
||||||
- ✅ Validação de `app_data_dir` para Windows/Linux/macOS
|
|
||||||
|
|
||||||
### 10. Indicador de Runtime
|
|
||||||
|
|
||||||
- ✅ Melhorado com ícone + tooltip explicativo
|
|
||||||
|
|
||||||
### 11. Ordem de Implementação
|
|
||||||
|
|
||||||
- ✅ Reordenada considerando dependências técnicas
|
|
||||||
|
|
||||||
### 12. Riscos Adicionais
|
|
||||||
|
|
||||||
- ✅ VRAM detection via `sysinfo`
|
|
||||||
- ✅ Limite de downloads paralelos (semáforo)
|
|
||||||
- ✅ Documentação de requisitos (CMake/Ninja)
|
|
||||||
@@ -43,7 +43,7 @@ jobs:
|
|||||||
- name: Install pnpm
|
- name: Install pnpm
|
||||||
uses: pnpm/action-setup@v4
|
uses: pnpm/action-setup@v4
|
||||||
with:
|
with:
|
||||||
version: 9
|
version: 8
|
||||||
|
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
@@ -57,14 +57,6 @@ jobs:
|
|||||||
toolchain: stable
|
toolchain: stable
|
||||||
targets: ${{ matrix.target }}
|
targets: ${{ matrix.target }}
|
||||||
|
|
||||||
- name: Rust cache
|
|
||||||
uses: swatinem/rust-cache@v2
|
|
||||||
with:
|
|
||||||
workspaces: './src-tauri -> target'
|
|
||||||
|
|
||||||
- name: Install Tauri CLI
|
|
||||||
run: cargo install tauri-cli --version "^2.9" --locked
|
|
||||||
|
|
||||||
- name: Install dependencies (Ubuntu only)
|
- name: Install dependencies (Ubuntu only)
|
||||||
if: matrix.platform == 'ubuntu-latest'
|
if: matrix.platform == 'ubuntu-latest'
|
||||||
run: |
|
run: |
|
||||||
@@ -72,96 +64,19 @@ jobs:
|
|||||||
sudo apt-get install -y libwebkit2gtk-4.1-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev patchelf
|
sudo apt-get install -y libwebkit2gtk-4.1-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev patchelf
|
||||||
|
|
||||||
- name: Install frontend dependencies
|
- name: Install frontend dependencies
|
||||||
shell: bash
|
run: pnpm install --frozen-lockfile
|
||||||
run: |
|
|
||||||
if [ -f pnpm-lock.yaml ]; then
|
|
||||||
pnpm install --frozen-lockfile
|
|
||||||
else
|
|
||||||
pnpm install
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Generate changelog
|
- name: Generate changelog
|
||||||
run: pnpm generate-changelog
|
run: pnpm generate-changelog
|
||||||
|
|
||||||
- name: Build frontend (Next.js)
|
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
NODE_OPTIONS: ${{ matrix.platform == 'macos-latest' && matrix.target == 'aarch64-apple-darwin' && '--max-old-space-size=4096' || '--max-old-space-size=2048' }}
|
|
||||||
run: |
|
|
||||||
echo "Building Next.js frontend with NODE_OPTIONS=${NODE_OPTIONS}"
|
|
||||||
pnpm build
|
|
||||||
if [ ! -d "out" ]; then
|
|
||||||
echo "Error: Frontend build failed - 'out' directory not found"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "Frontend build successful - 'out' directory exists"
|
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
- name: Prepare bundle resources (Windows only)
|
|
||||||
if: matrix.platform == 'windows-latest'
|
|
||||||
shell: powershell
|
|
||||||
run: |
|
|
||||||
# Criar diretórios
|
|
||||||
New-Item -ItemType Directory -Force -Path "src-tauri/bundle/ollama" | Out-Null
|
|
||||||
New-Item -ItemType Directory -Force -Path "src-tauri/bundle/models/embeddings" | Out-Null
|
|
||||||
|
|
||||||
# Baixar instalador do Ollama (se não existir)
|
|
||||||
$ollamaPath = "src-tauri/bundle/ollama/OllamaSetup.exe"
|
|
||||||
if (!(Test-Path $ollamaPath)) {
|
|
||||||
Write-Host "Downloading Ollama installer..."
|
|
||||||
Invoke-WebRequest -Uri "https://ollama.com/download/OllamaSetup.exe" -OutFile $ollamaPath -UseBasicParsing
|
|
||||||
}
|
|
||||||
|
|
||||||
# Baixar modelos de embeddings (se não existirem)
|
|
||||||
$modelPath = "src-tauri/bundle/models/embeddings/all-MiniLM-L6-v2.onnx"
|
|
||||||
if (!(Test-Path $modelPath)) {
|
|
||||||
Write-Host "Downloading ONNX embedding model (~90MB, this may take a while)..."
|
|
||||||
Invoke-WebRequest -Uri "https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2/resolve/main/onnx/model.onnx" -OutFile $modelPath -UseBasicParsing
|
|
||||||
}
|
|
||||||
|
|
||||||
$tokenizerPath = "src-tauri/bundle/models/embeddings/tokenizer.json"
|
|
||||||
if (!(Test-Path $tokenizerPath)) {
|
|
||||||
Write-Host "Downloading tokenizer..."
|
|
||||||
Invoke-WebRequest -Uri "https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2/resolve/main/tokenizer.json" -OutFile $tokenizerPath -UseBasicParsing
|
|
||||||
}
|
|
||||||
|
|
||||||
# Baixar e extrair ONNX Runtime DLL
|
|
||||||
$ortDllPath = "src-tauri/bundle/models/embeddings/onnxruntime.dll"
|
|
||||||
if (!(Test-Path $ortDllPath)) {
|
|
||||||
$ortZipPath = "src-tauri/bundle/models/embeddings/onnxruntime.zip"
|
|
||||||
if (!(Test-Path $ortZipPath)) {
|
|
||||||
Write-Host "Downloading ONNX Runtime library (~50MB)..."
|
|
||||||
Invoke-WebRequest -Uri "https://github.com/microsoft/onnxruntime/releases/download/v1.20.1/onnxruntime-win-x64-1.20.1.zip" -OutFile $ortZipPath -UseBasicParsing
|
|
||||||
}
|
|
||||||
|
|
||||||
Write-Host "Extracting ONNX Runtime DLL..."
|
|
||||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
|
||||||
$zip = [System.IO.Compression.ZipFile]::OpenRead($ortZipPath)
|
|
||||||
foreach ($entry in $zip.Entries) {
|
|
||||||
if ($entry.Name -eq "onnxruntime.dll") {
|
|
||||||
[System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $ortDllPath, $true)
|
|
||||||
Write-Host "Extracted onnxruntime.dll"
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$zip.Dispose()
|
|
||||||
Remove-Item $ortZipPath -ErrorAction SilentlyContinue
|
|
||||||
}
|
|
||||||
|
|
||||||
Write-Host "Bundle resources prepared successfully"
|
|
||||||
|
|
||||||
=======
|
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
- name: Build Tauri app
|
- name: Build Tauri app
|
||||||
run: |
|
run: |
|
||||||
cd src-tauri
|
cd src-tauri
|
||||||
cargo build --release --target ${{ matrix.target }}
|
cargo build --release --target ${{ matrix.target }}
|
||||||
|
|
||||||
- name: Build Tauri bundle
|
- name: Build Tauri bundle
|
||||||
shell: bash
|
|
||||||
env:
|
env:
|
||||||
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_UPDATER_PRIVATE_KEY }}
|
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_UPDATER_PRIVATE_KEY }}
|
||||||
NODE_OPTIONS: ${{ matrix.platform == 'macos-latest' && matrix.target == 'aarch64-apple-darwin' && '--max-old-space-size=4096' || '--max-old-space-size=2048' }}
|
|
||||||
run: |
|
run: |
|
||||||
cd src-tauri
|
cd src-tauri
|
||||||
if [ -n "$TAURI_PRIVATE_KEY" ]; then
|
if [ -n "$TAURI_PRIVATE_KEY" ]; then
|
||||||
@@ -199,7 +114,7 @@ jobs:
|
|||||||
- name: Install pnpm
|
- name: Install pnpm
|
||||||
uses: pnpm/action-setup@v4
|
uses: pnpm/action-setup@v4
|
||||||
with:
|
with:
|
||||||
version: 9
|
version: 8
|
||||||
|
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
@@ -207,15 +122,6 @@ jobs:
|
|||||||
node-version: '20'
|
node-version: '20'
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
- name: Install frontend dependencies
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
if [ -f pnpm-lock.yaml ]; then
|
|
||||||
pnpm install --frozen-lockfile
|
|
||||||
else
|
|
||||||
pnpm install
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Get version
|
- name: Get version
|
||||||
id: get_version
|
id: get_version
|
||||||
run: |
|
run: |
|
||||||
@@ -233,7 +139,6 @@ jobs:
|
|||||||
|
|
||||||
- name: Extract release notes
|
- name: Extract release notes
|
||||||
id: extract_notes
|
id: extract_notes
|
||||||
shell: bash
|
|
||||||
run: |
|
run: |
|
||||||
if [ -f "data/changelog.json" ]; then
|
if [ -f "data/changelog.json" ]; then
|
||||||
NOTES=$(node -e "
|
NOTES=$(node -e "
|
||||||
|
|||||||
-11
@@ -40,14 +40,3 @@ yarn-error.log*
|
|||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
next-env.d.ts
|
next-env.d.ts
|
||||||
~/.tauri/ollahub.key
|
~/.tauri/ollahub.key
|
||||||
|
|
||||||
# tauri build artifacts
|
|
||||||
src-tauri/target/
|
|
||||||
src-tauri/bundle/
|
|
||||||
*.exe
|
|
||||||
*.msi
|
|
||||||
*.AppImage
|
|
||||||
*.deb
|
|
||||||
*.dmg
|
|
||||||
OllamaSetup.exe
|
|
||||||
src-tauri/bundle/ollama/
|
|
||||||
@@ -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`.
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
OllaHub Community License (v1.0)
|
|
||||||
Copyright (c) 2024 Evandro Fonseca Junior (evandrodevbr) Website: https://evandro.dev.br
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
||||||
|
|
||||||
1. GRANT OF LICENSE Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to use, copy, modify, merge, publish, distribute, and sublicense copies of the Software, subject strictly to the conditions and limitations set forth below.
|
|
||||||
|
|
||||||
2. ATTRIBUTION REQUIREMENT (CREDITWARE) This license explicitly requires correct attribution as a condition of use. a) Source Code & Distribution: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. b) Public Display: Any redistribution, fork, derivative work, video content, article, social media post, or public demonstration involving this Software MUST include visible and clear credits to the original author (Evandro Fonseca Junior) and a direct link to https://evandro.dev.br. c) UI Integrity: Removal, obscuring, or modification of copyright notices, author links, metadata, or "About" screens within the Software's user interface is strictly prohibited.
|
|
||||||
|
|
||||||
3. NON-COMMERCIAL & ANTI-MONETIZATION RESTRICTIONS This license distinguishes between "Internal Use" and "Commercial Distribution." a) Prohibition of Sale: You may NOT sell, rent, lease, or sub-license the Software for a fee. You may not bundle this Software within a paid product or service without express written permission from the Copyright Holder. b) No Monetization Barriers: You may NOT use the Software as a mechanism for monetization, including but not limited to "freemium" models, paywalls, or "pay-for-speed" download gates. c) Permitted Internal Use: The use of this Software internally within a commercial organization for productivity, research, or development purposes (e.g., employees using the tool to perform their daily tasks) is EXPLICITLY PERMITTED and encouraged, provided the Software itself is not the product being sold.
|
|
||||||
|
|
||||||
4. DONATION POLICY The Software is developed and maintained through voluntary contributions. a) Official Channels Only: No third-party entity is authorized to solicit or collect donations on behalf of OllaHub or its author. b) Direct Support: All financial contributions must be directed exclusively to the official channels listed at https://evandro.dev.br. Soliciting donations for a fork or redistribution of this Software without significant and distinct added value is prohibited.
|
|
||||||
|
|
||||||
5. DISCLAIMER OF WARRANTY & LIABILITY THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
|
|
||||||
6. SPECIFIC DISCLAIMER: AI & WEB SCRAPING The Software interacts with Large Language Models (LLMs) and performs web scraping operations. By using this Software, you acknowledge and agree that: a) The authors are not responsible for the accuracy, hallucinations, or bias of content generated by LLMs. b) You are solely responsible for ensuring that your use of the web scraping features complies with the Terms of Service (ToS) of third-party websites and applicable local laws. c) You are responsible for maintaining data privacy and security when processing sensitive information.
|
|
||||||
|
|
||||||
7. COMMERCIAL LICENSING For usage scenarios that fall outside these terms (e.g., white-labeling, redistribution in paid suites, or custom enterprise agreements), please contact the author for a commercial license:
|
|
||||||
|
|
||||||
Website: https://evandro.dev.br
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,206 +1,81 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
<h1>🧠 OllaHub</h1>
|
|
||||||
<p><strong>Local-first LLM workspace with deep research capabilities and native OS integration.</strong></p>
|
|
||||||
|
|
||||||
<p align="center">
|
<img src="assets/readme/hero.svg" width="100%" alt="OllaHub: desktop chat for your local Ollama models, with web search and MCP tools">
|
||||||
<a href="https://www.rust-lang.org/"><img src="https://img.shields.io/badge/Rust-1.77.2-orange.svg?style=flat-square&logo=rust" alt="Rust"></a>
|
|
||||||
<a href="https://tauri.app/"><img src="https://img.shields.io/badge/Tauri-2.9.2-24C8DB.svg?style=flat-square&logo=tauri" alt="Tauri"></a>
|
|
||||||
<a href="https://nextjs.org/"><img src="https://img.shields.io/badge/Next.js-16.0.3-black.svg?style=flat-square&logo=next.js" alt="Next.js"></a>
|
|
||||||
<a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/TypeScript-5.0-blue.svg?style=flat-square&logo=typescript" alt="TypeScript"></a>
|
|
||||||
<a href="LICENSE"><img src="https://img.shields.io/badge/License-Custom-blue.svg?style=flat-square" alt="License"></a>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<br>
|

|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
</div>
|
[Quick start](#quick-start) · [Docs](docs/) · [Issues](https://git.evandro.dev.br/evandro/OllaHub/issues)
|
||||||
|
|
||||||
---
|
</div>
|
||||||
|
|
||||||
## 🌟 Why OllaHub?
|
## What it is
|
||||||
|
|
||||||
OllaHub is a powerful desktop application that orchestrates local Large Language Models (LLMs) through **Ollama**, providing a private, offline-capable workspace for research, analysis, and conversation.
|
OllaHub is a desktop chat app for the models you run with [Ollama](https://ollama.com). On first run it scans your hardware, recommends a model and downloads it. After that it chats with streaming, keeps history in a local SQLite database, and can add context from web search, MCP tools and scheduled tasks. The UI is Next.js inside a Tauri 2 window, and a Rust backend does the work.
|
||||||
|
|
||||||
Unlike standard chat interfaces, OllaHub executes **complex research workflows** by decomposing queries, performing parallel web scraping, and synthesizing context from multiple sources before generating responses—all while keeping your data 100% local and private.
|
OllaHub is a client, not a model runtime. It talks to the Ollama API (default `http://localhost:11434`, configurable in Settings), tries to start Ollama when it is installed but stopped, and can download the Ollama installer when it is missing.
|
||||||
|
|
||||||
---
|
## Why use it
|
||||||
|
|
||||||
## ✨ Key Features
|
- **Local by default.** Prompts go to your own Ollama, and chats live in `ollahub.db` in the app data directory, with FTS5 full-text search. Besides downloads (models, the embedding model, updates), web search is what reaches the internet.
|
||||||
|
- **Web answers ranked on your machine.** Headless Chrome scrapes Google, Bing, Yahoo, DuckDuckGo and Startpage (order configurable), then local embeddings (`all-MiniLM-L6-v2` on ONNX Runtime) rank and prune the pages, with a BM25-like fallback when the embedding model is unavailable. A deep-research mode runs planning → searching → aggregating → validating → formulating.
|
||||||
|
- **More than a chat box.** MCP servers run as child processes configured in `mcp_config.json`, their tools can be called from the chat, and cron tasks (search and summarize, notification, custom prompt) keep running in the background.
|
||||||
|
|
||||||
### 🔍 Deep Research Pipeline
|
**When not to use it:** if you want a finished, tested product (version `0.1.0`, no test suite), a model runtime of its own, or a server you can run without a desktop.
|
||||||
OllaHub doesn't just answer; it researches. Our multi-stage pipeline includes:
|
|
||||||
1. **Query Decomposition:** Uses the LLM to break complex queries into 3-5 atomic, search-optimized sub-queries.
|
|
||||||
2. **Parallel Scraping:** Executes concurrent searches using headless Chrome and the DuckDuckGo metadata API.
|
|
||||||
3. **Knowledge Aggregation:** Collects, deduplicates, and cleans content from multiple sources.
|
|
||||||
4. **Context Condensation:** Applies relevance scoring (ONNX embeddings) and summarization to fit context within token limits.
|
|
||||||
5. **Validation:** Verifies knowledge base sufficiency before response generation, with safety fallbacks.
|
|
||||||
|
|
||||||
### 🛡️ Local-First & Privacy-Focused
|
## How it works
|
||||||
* **Ollama Integration:** Direct subprocess management for seamless local model execution.
|
|
||||||
* **Local Semantic Search:** Powered by ONNX Runtime (`all-MiniLM-L6-v2` 384-dimensional embeddings) with no external API calls.
|
|
||||||
* **Hybrid Storage:** Blazing fast SQLite (FTS5 for full-text search) with JSON fallbacks for backward compatibility and data safety.
|
|
||||||
|
|
||||||
### 🔌 MCP (Model Context Protocol) Integration
|
- **Frontend** (`app/`, `components/`, `hooks/`, `lib/`, `store/`): Next.js 16 with `output: 'export'`, React 19, Tailwind 4, Radix UI and Zustand. It calls the backend through Tauri `invoke` and events.
|
||||||
Extensible by design. Connect external tools via MCP servers:
|
- **Backend** (`src-tauri/src/`): `lib.rs` holds the commands for chat (`chat_stream`), models, the Ollama lifecycle, sessions, MCP, search, tasks, export and the installer. `db.rs` handles SQLite, `web_scraper.rs` the search engines, `embeddings.rs` the ranking, and `scheduler.rs` the cron tasks stored in `tasks.json`.
|
||||||
* **Tool Discovery:** Automatic enumeration of available tools from running servers.
|
- **Models:** list, delete and pull with progress, install a local `.gguf` file, and get a recommendation for your hardware.
|
||||||
* **Process Management:** Full lifecycle control (start, stop, restart) with health monitoring.
|
- **System monitor:** CPU and RAM stats plus GPU VRAM, usage and temperature. GPU detection uses `wmic` and `nvidia-smi` on Windows and `lspci` on Linux.
|
||||||
* **Tool Execution:** Runtime invocation of tools with direct result injection into the LLM context.
|
- **Updates:** the Tauri updater checks automatically. Its endpoint in `src-tauri/tauri.conf.json` points to a GitHub Releases `latest.json`.
|
||||||
|
|
||||||
### ⚡ Reactive & Customizable UI
|
More notes: [`docs/updater-setup.md`](docs/updater-setup.md) (signing keys and updater) and [`docs/style-guide.md`](docs/style-guide.md) (UI spacing, radii, accessibility).
|
||||||
Built with **React 19, Next.js 16, and Tailwind CSS**. Features smooth animations (Framer Motion), accessible primitives (Radix UI/Shadcn), resizable panels, and lightweight state management (Zustand).
|
|
||||||
|
|
||||||
---
|
## Quick start
|
||||||
|
|
||||||
## 🏗️ System Architecture
|
No release is published on this repository yet, so build it locally. You need Node.js 20, pnpm 8, a stable Rust toolchain and the [Tauri 2 prerequisites](https://tauri.app/start/prerequisites/) (the versions come from the CI workflow). On Ubuntu the workflow also installs `libwebkit2gtk-4.1-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev patchelf`. Ollama is needed at runtime.
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary><b>Click to view Architecture Diagram</b></summary>
|
|
||||||
|
|
||||||
```mermaid
|
|
||||||
graph TB
|
|
||||||
subgraph Frontend["Frontend (Next.js)"]
|
|
||||||
UI[React Components]
|
|
||||||
Hooks[Custom Hooks]
|
|
||||||
Store[Zustand Store]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph Bridge["Tauri Bridge"]
|
|
||||||
Commands[Tauri Commands]
|
|
||||||
Events[Event System]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph Backend["Rust Core"]
|
|
||||||
Orchestrator[Orchestrator]
|
|
||||||
Scraper[Web Scraper]
|
|
||||||
DB[(SQLite + FTS5)]
|
|
||||||
Embeddings[ONNX Embeddings]
|
|
||||||
Scheduler[Task Scheduler]
|
|
||||||
MCP[MCP Manager]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph External["External Services"]
|
|
||||||
Ollama[Ollama Subprocess]
|
|
||||||
Chrome[Headless Chrome]
|
|
||||||
MCP_Servers[MCP Servers]
|
|
||||||
end
|
|
||||||
|
|
||||||
UI --> Hooks
|
|
||||||
Hooks --> Store
|
|
||||||
Store --> Commands
|
|
||||||
Commands --> Orchestrator
|
|
||||||
Orchestrator --> Scraper
|
|
||||||
Orchestrator --> DB
|
|
||||||
Orchestrator --> Embeddings
|
|
||||||
Orchestrator --> Scheduler
|
|
||||||
Orchestrator --> MCP
|
|
||||||
Scraper --> Chrome
|
|
||||||
Orchestrator --> Ollama
|
|
||||||
MCP --> MCP_Servers
|
|
||||||
Events --> UI
|
|
||||||
|
|
||||||
style Frontend fill:#2563eb,color:#fff
|
|
||||||
style Bridge fill:#7c3aed,color:#fff
|
|
||||||
style Backend fill:#dc2626,color:#fff
|
|
||||||
style External fill:#059669,color:#fff
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🚀 Getting Started
|
|
||||||
|
|
||||||
### Prerequisites
|
|
||||||
|
|
||||||
Before you begin, ensure you have the following installed:
|
|
||||||
|
|
||||||
* **Node.js**: `v20.x` or later
|
|
||||||
* **Rust**: `v1.77.2` or later
|
|
||||||
* **pnpm**: Latest version (`npm install -g pnpm`)
|
|
||||||
* **[Ollama](https://ollama.ai)**: Must be running locally on `http://localhost:11434`
|
|
||||||
|
|
||||||
### Installation & Development
|
|
||||||
|
|
||||||
1. **Clone the repository:**
|
|
||||||
```bash
|
```bash
|
||||||
git clone [https://github.com/evandrodevbr/OllaHub.git](https://github.com/evandrodevbr/OllaHub.git)
|
git clone https://git.evandro.dev.br/evandro/OllaHub.git
|
||||||
cd OllaHub
|
cd OllaHub
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
2. **Install dependencies:**
|
|
||||||
```bash
|
|
||||||
pnpm install
|
pnpm install
|
||||||
|
|
||||||
|
pnpm tauri dev # starts `pnpm dev` (Next.js on http://localhost:3000) inside the Tauri window
|
||||||
|
pnpm tauri build # runs `pnpm generate-changelog && pnpm build`, then bundles the installer
|
||||||
|
pnpm lint # ESLint
|
||||||
|
pnpm bump-version # patch | minor | major, optional --commit
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The workflow [`.github/workflows/release.yml`](.github/workflows/release.yml) builds `msi` (Windows), `dmg` (macOS, Apple Silicon and Intel) and `AppImage` (Linux) on pushes to `main`, `master` and `develop`, and publishes release `v<version>` on pushes to `main` or `master`.
|
||||||
|
|
||||||
3. **Run in development mode:**
|
> [!WARNING]
|
||||||
```bash
|
> **Two things the app does on its own.**
|
||||||
pnpm tauri dev
|
> 1. Opening the chat page pulls the small helper model **`qwen2.5:0.5b`** if it is not installed yet, used for automatic chat titles. Expect an extra download on first use.
|
||||||
|
> 2. **Closing the window only hides it.** The close request is intercepted (`prevent_close`) so scheduled tasks keep running, but there is no tray icon to bring the window back yet; the tray step is still pending in [`IMPLEMENTATION_GUIDE.md`](IMPLEMENTATION_GUIDE.md).
|
||||||
|
|
||||||
```
|
## Project status
|
||||||
|
|
||||||
|
Early: version `0.1.0`, 47 commits between 2025-10-27 and 2025-11-27, no automated tests (`package.json` defines `dev`, `build`, `start`, `lint`, `generate-changelog` and `bump-version`). Known limitations:
|
||||||
|
|
||||||
*This starts the Next.js server (`localhost:3000`), builds the Rust backend, and launches the Tauri native window.*
|
- **No tray icon yet:** closing the window hides it (see the warning above).
|
||||||
|
- **"Start with the system" does nothing yet:** the setting only toggles a stored flag; the code has a `TODO` until `tauri-plugin-autostart` is configured.
|
||||||
|
- **RAG inside `chat_stream` is not wired:** the `enable_rag` branch is commented out as `TODO`; the frontend assembles web context before the request.
|
||||||
|
- **Embeddings outside Windows:** the ONNX Runtime library is downloaded automatically only on Windows. On macOS and Linux, provide it in the app data folder or on the system path, otherwise ranking falls back to BM25-like scoring.
|
||||||
|
- **Unused leftovers:** `src-tauri/scripts/scraper.py` is not called by the Rust backend, and the 188 model files in `data/models/` are not referenced by the app code.
|
||||||
|
|
||||||
### Building for Production
|
## License
|
||||||
|
|
||||||
```bash
|
No published license: all rights reserved.
|
||||||
pnpm tauri build
|
|
||||||
|
|
||||||
```
|
Built with [Tauri](https://tauri.app), [Next.js](https://nextjs.org), [Radix UI](https://www.radix-ui.com), [Tailwind CSS](https://tailwindcss.com), [Zustand](https://zustand-demo.pmnd.rs), [Lucide](https://lucide.dev), [headless_chrome](https://github.com/rust-headless-chrome/rust-headless-chrome), [ONNX Runtime](https://onnxruntime.ai) and the [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) model.
|
||||||
|
|
||||||
*Compiled binaries will be available in `src-tauri/target/release/bundle/` (.msi, .dmg, .app, .deb, etc.).*
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 💻 Tech Stack Deep Dive
|
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
<img src="https://www.google.com/search?q=https://skillicons.dev/icons%3Fi%3Drust,tauri,nextjs,react,ts,tailwind,sqlite" />
|
|
||||||
|
<sub>Made by <a href="https://evandro.dev.br">Evandro Fonseca Junior</a> · <a href="https://git.evandro.dev.br/evandro">git.evandro.dev.br</a></sub>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
| Layer | Technologies Used | Purpose |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| **Core** | Tauri 2.9, Rust 1.77 | Native desktop environment, high-performance system I/O, concurrency (Tokio). |
|
|
||||||
| **Frontend** | Next.js 16, React 19, TS | SSR-capable UI, Zustand (State), Framer Motion (Animations), Tailwind/Radix. |
|
|
||||||
| **Database** | SQLite (rusqlite 0.31) | FTS5 virtual tables for lightning-fast full-text search and session storage. |
|
|
||||||
| **AI / ML** | Ollama, ONNX Runtime | Local LLM execution and 384-dim semantic embeddings (`all-MiniLM-L6-v2`). |
|
|
||||||
| **Scraping** | headless_chrome, scraper | Parallel web automation, DOM parsing, and readability extraction. |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🗺️ Roadmap
|
|
||||||
|
|
||||||
* [ ] **Vector Store Integration**: Transition from SQLite BLOB embeddings to a dedicated vector DB (LanceDB or Qdrant).
|
|
||||||
* [ ] **Advanced RAG**: Multi-modal retrieval supporting images, PDFs, and local documents.
|
|
||||||
* [ ] **Cloud Sync**: Optional E2E encrypted synchronization of chat sessions across devices.
|
|
||||||
* [ ] **Custom Plugin System**: Extensible architecture for user-defined research workflows.
|
|
||||||
* [ ] **Model Fine-Tuning UI**: Native interface for training custom models on personal knowledge bases.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## ⚖️ License & Terms
|
|
||||||
|
|
||||||
OllaHub is released under a custom license combining freeware and creditware models. See the [LICENSE](https://www.google.com/search?q=LICENSE) file for full legal terms.
|
|
||||||
|
|
||||||
**TL;DR:**
|
|
||||||
|
|
||||||
* ✅ **You may:** Use freely for personal/educational/internal use, modify, and fork the project.
|
|
||||||
* ✅ **You must:** Give visible credit to **Evandro Fonseca Junior** and link to [evandro.dev.br](https://evandro.dev.br). Keep copyright notices intact.
|
|
||||||
* ❌ **You may not:** Sell the software, bundle it in paid products, or monetize it without explicit written permission.
|
|
||||||
|
|
||||||
For commercial licensing inquiries, please contact me via [evandro.dev.br](https://evandro.dev.br).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
<div align="center">
|
|
||||||
<p>Built by <a href="https://github.com/evandrodevbr">Evandro Fonseca Junior</a></p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
```
|
|
||||||
+269
-377
@@ -3,9 +3,8 @@
|
|||||||
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";
|
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { MessageSquare, Settings, Server, Moon, Sun, PanelLeftClose, PanelLeftOpen, Loader2, ChevronDown, Plus, RefreshCw, Cpu } from "lucide-react";
|
import { MessageSquare, Settings, Server, Moon, Sun, PanelLeftClose, PanelLeftOpen, Loader2, ChevronDown, Plus, ScrollText, Copy, Check, Globe, RefreshCw, Cpu } from "lucide-react";
|
||||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||||
import { ModelSelector } from "@/components/chat/model-selector";
|
|
||||||
import { ChatInput } from "@/components/chat/chat-input";
|
import { ChatInput } from "@/components/chat/chat-input";
|
||||||
import { ChatMessage } from "@/components/chat/chat-message";
|
import { ChatMessage } from "@/components/chat/chat-message";
|
||||||
import { ReasoningChain } from "@/components/chat/reasoning-chain";
|
import { ReasoningChain } from "@/components/chat/reasoning-chain";
|
||||||
@@ -14,7 +13,6 @@ import { TitleBar } from "@/components/titlebar";
|
|||||||
import { SidebarList } from "@/components/chat/sidebar-list";
|
import { SidebarList } from "@/components/chat/sidebar-list";
|
||||||
import { useChat } from "@/hooks/use-chat";
|
import { useChat } from "@/hooks/use-chat";
|
||||||
import { useLocalModels } from "@/hooks/use-local-models";
|
import { useLocalModels } from "@/hooks/use-local-models";
|
||||||
import { useModelSelection } from "@/hooks/use-model-selection";
|
|
||||||
import { useChatStorage } from "@/hooks/use-chat-storage";
|
import { useChatStorage } from "@/hooks/use-chat-storage";
|
||||||
import { useAutoLabelingModel } from "@/hooks/use-auto-labeling-model";
|
import { useAutoLabelingModel } from "@/hooks/use-auto-labeling-model";
|
||||||
import { useWebSearch } from "@/hooks/use-web-search";
|
import { useWebSearch } from "@/hooks/use-web-search";
|
||||||
@@ -26,17 +24,15 @@ import { useDeepResearch } from "@/hooks/use-deep-research";
|
|||||||
import { DEEP_RESEARCH_PROMPTS } from "@/data/prompts/deep-research";
|
import { DEEP_RESEARCH_PROMPTS } from "@/data/prompts/deep-research";
|
||||||
import { useSettingsStore } from "@/store/settings-store";
|
import { useSettingsStore } from "@/store/settings-store";
|
||||||
import type { ScrapedContent } from "@/services/webSearch";
|
import type { ScrapedContent } from "@/services/webSearch";
|
||||||
import { useState, useEffect, useRef, useCallback, startTransition } from "react";
|
import { useState, useEffect, useRef, useCallback } from "react";
|
||||||
import { useTheme } from "next-themes";
|
import { useTheme } from "next-themes";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { invoke } from "@tauri-apps/api/core";
|
|
||||||
import { ImperativePanelHandle } from "react-resizable-panels";
|
import { ImperativePanelHandle } from "react-resizable-panels";
|
||||||
import { ModelDownloadDialog } from "@/components/chat/model-download-dialog";
|
import { ModelDownloadDialog } from "@/components/chat/model-download-dialog";
|
||||||
import { chatLog } from "@/lib/terminal-logger";
|
import { chatLog } from "@/lib/terminal-logger";
|
||||||
import { useQueryPreprocessor, type PreprocessedQuery } from "@/hooks/use-query-preprocessor";
|
import { useQueryPreprocessor, type PreprocessedQuery } from "@/hooks/use-query-preprocessor";
|
||||||
import type { Message, ThinkingMessageMetadata, ThinkingStepType, ThinkingStepStatus } from "@/hooks/use-chat";
|
import type { Message, ThinkingMessageMetadata, ThinkingStepType, ThinkingStepStatus } from "@/hooks/use-chat";
|
||||||
import { executeProgressiveSearch } from "@/lib/web-search-fallback";
|
import { executeProgressiveSearch } from "@/lib/web-search-fallback";
|
||||||
import type { DebugData } from "@/components/chat/debug-console";
|
|
||||||
// @ts-expect-error - MD file import
|
// @ts-expect-error - MD file import
|
||||||
import defaultFormatPrompt from "@/data/prompts/default-format.md";
|
import defaultFormatPrompt from "@/data/prompts/default-format.md";
|
||||||
|
|
||||||
@@ -46,7 +42,6 @@ export default function ChatPage() {
|
|||||||
const { messages, setMessages, sendMessage, isLoading, stop, clearChat } = useChat();
|
const { messages, setMessages, sendMessage, isLoading, stop, clearChat } = useChat();
|
||||||
const { models, refresh } = useLocalModels();
|
const { models, refresh } = useLocalModels();
|
||||||
const { theme, setTheme } = useTheme();
|
const { theme, setTheme } = useTheme();
|
||||||
const { isSetupCompleted } = useSettingsStore();
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
sessions,
|
sessions,
|
||||||
@@ -116,68 +111,9 @@ export default function ChatPage() {
|
|||||||
}));
|
}));
|
||||||
}, [setMessages]);
|
}, [setMessages]);
|
||||||
|
|
||||||
const { selectedModel, setSelectedModel } = useModelSelection();
|
const [selectedModel, setSelectedModel] = useState("");
|
||||||
|
|
||||||
// Sincronizar eventos de busca com thinking messages
|
|
||||||
useEffect(() => {
|
|
||||||
if (webSearch.activeQueries.length > 0 || webSearch.activeUrls.length > 0) {
|
|
||||||
updateThinkingMessage('web-research', {
|
|
||||||
activeQueries: webSearch.activeQueries,
|
|
||||||
activeUrls: webSearch.activeUrls,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, [webSearch.activeQueries, webSearch.activeUrls, updateThinkingMessage]);
|
|
||||||
const [mounted, setMounted] = useState(false);
|
const [mounted, setMounted] = useState(false);
|
||||||
const initializedRef = useRef(false);
|
const initializedRef = useRef(false);
|
||||||
|
|
||||||
// Refs para evitar loops e execuções múltiplas
|
|
||||||
const hasCheckedIntegrityRef = useRef(false);
|
|
||||||
const isRedirectingRef = useRef(false);
|
|
||||||
|
|
||||||
// Guarda de roteamento: verificar se setup foi completado
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isSetupCompleted && !isRedirectingRef.current) {
|
|
||||||
isRedirectingRef.current = true;
|
|
||||||
startTransition(() => {
|
|
||||||
router.replace("/setup"); // Mudar de push para replace para consistência
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, [isSetupCompleted, router]);
|
|
||||||
|
|
||||||
// Guarda de integridade: verificar se Ollama está funcional
|
|
||||||
// Executa SEMPRE que o componente montar, independente do status do setup
|
|
||||||
useEffect(() => {
|
|
||||||
if (hasCheckedIntegrityRef.current) return; // Proteção contra múltiplas execuções
|
|
||||||
if (isRedirectingRef.current) return; // Evitar redirecionamentos múltiplos
|
|
||||||
|
|
||||||
const checkIntegrity = async () => {
|
|
||||||
try {
|
|
||||||
const isOllamaIntact = await invoke<boolean>('verify_ollama_integrity_command');
|
|
||||||
|
|
||||||
if (!isOllamaIntact && !isRedirectingRef.current) {
|
|
||||||
isRedirectingRef.current = true;
|
|
||||||
// Ollama não está funcional - redirecionar para setup
|
|
||||||
console.warn("Integridade do Ollama falhou no chat. Redirecionando para Setup.");
|
|
||||||
startTransition(() => {
|
|
||||||
router.replace('/setup');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
// Em caso de erro na verificação, redirecionar para setup (fallback seguro)
|
|
||||||
if (!isRedirectingRef.current) {
|
|
||||||
isRedirectingRef.current = true;
|
|
||||||
console.error("Falha ao verificar integridade do Ollama no chat:", e);
|
|
||||||
startTransition(() => {
|
|
||||||
router.replace('/setup');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
hasCheckedIntegrityRef.current = true; // Marcar como executado
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
checkIntegrity();
|
|
||||||
}, [router]); // Remover isSetupCompleted das dependências - executar sempre
|
|
||||||
// Initialize with default format prompt
|
// Initialize with default format prompt
|
||||||
const [systemPrompt] = useState(defaultFormatPrompt || "Você é um assistente útil e prestativo.");
|
const [systemPrompt] = useState(defaultFormatPrompt || "Você é um assistente útil e prestativo.");
|
||||||
const [isChatsSidebarCollapsed, setIsChatsSidebarCollapsed] = useState(true); // Iniciar colapsada
|
const [isChatsSidebarCollapsed, setIsChatsSidebarCollapsed] = useState(true); // Iniciar colapsada
|
||||||
@@ -189,9 +125,14 @@ export default function ChatPage() {
|
|||||||
const lastSavedMessagesRef = useRef<number>(0);
|
const lastSavedMessagesRef = useRef<number>(0);
|
||||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||||
const scrollContainerRef = useRef<HTMLDivElement>(null);
|
const scrollContainerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [showContextDebug, setShowContextDebug] = useState(false);
|
||||||
|
const [showProcessDebug, setShowProcessDebug] = useState(false);
|
||||||
|
const [lastWebContext, setLastWebContext] = useState('');
|
||||||
|
const [lastContextSources, setLastContextSources] = useState<ScrapedContent[]>([]);
|
||||||
const [showDownloadDialog, setShowDownloadDialog] = useState(false);
|
const [showDownloadDialog, setShowDownloadDialog] = useState(false);
|
||||||
|
const [logsCopied, setLogsCopied] = useState(false);
|
||||||
|
const [lastUserQuery, setLastUserQuery] = useState('');
|
||||||
const [searchMatchIndex, setSearchMatchIndex] = useState(0);
|
const [searchMatchIndex, setSearchMatchIndex] = useState(0);
|
||||||
const [debugDataMap, setDebugDataMap] = useState<Map<number, DebugData>>(new Map());
|
|
||||||
|
|
||||||
// Resetar índice quando busca é limpa ou sessão muda
|
// Resetar índice quando busca é limpa ou sessão muda
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -200,10 +141,25 @@ export default function ChatPage() {
|
|||||||
}
|
}
|
||||||
}, [searchQuery, currentSessionId]);
|
}, [searchQuery, currentSessionId]);
|
||||||
|
|
||||||
|
// Auto-select first model
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setMounted(true);
|
setMounted(true);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (initializedRef.current) return;
|
||||||
|
const stored = settings.selectedModel;
|
||||||
|
const first = models.length > 0 ? models[0].name : "";
|
||||||
|
const next = stored || first || "";
|
||||||
|
if (next) {
|
||||||
|
setSelectedModel(next);
|
||||||
|
if (!stored) {
|
||||||
|
settings.setSelectedModel(next);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
initializedRef.current = true;
|
||||||
|
}, [settings, models]);
|
||||||
|
|
||||||
// Auto-scroll para o final durante streaming
|
// Auto-scroll para o final durante streaming
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (messagesEndRef.current && (isLoading || messages.length > 0)) {
|
if (messagesEndRef.current && (isLoading || messages.length > 0)) {
|
||||||
@@ -413,6 +369,13 @@ export default function ChatPage() {
|
|||||||
chatLog.info(`Should Search: ${preprocessed.shouldSearch}`);
|
chatLog.info(`Should Search: ${preprocessed.shouldSearch}`);
|
||||||
chatLog.info(`Timestamp: ${new Date().toISOString()}`);
|
chatLog.info(`Timestamp: ${new Date().toISOString()}`);
|
||||||
|
|
||||||
|
setShowContextDebug(false);
|
||||||
|
setShowProcessDebug(false);
|
||||||
|
setLastWebContext('');
|
||||||
|
setLastContextSources([]);
|
||||||
|
setLastUserQuery(content); // Store for copy logs
|
||||||
|
setLogsCopied(false);
|
||||||
|
|
||||||
// Generate ID if new session (but don't create card yet - wait for title)
|
// Generate ID if new session (but don't create card yet - wait for title)
|
||||||
if (!currentSessionId) {
|
if (!currentSessionId) {
|
||||||
const newId = crypto.randomUUID();
|
const newId = crypto.randomUUID();
|
||||||
@@ -473,10 +436,7 @@ export default function ChatPage() {
|
|||||||
|
|
||||||
// Executar busca progressiva para cada query do plano
|
// Executar busca progressiva para cada query do plano
|
||||||
const searchPromises = searchPlan.map(async (query, idx) => {
|
const searchPromises = searchPlan.map(async (query, idx) => {
|
||||||
const queryStartTime = Date.now();
|
chatLog.info(` → Starting progressive search ${idx + 1}/${searchPlan.length}: "${query}"`);
|
||||||
chatLog.info(`\n[WebResearch] ========== QUERY ${idx + 1}/${searchPlan.length} ==========`);
|
|
||||||
chatLog.info(`[WebResearch] Query: "${query}"`);
|
|
||||||
chatLog.info(`[WebResearch] Timestamp: ${new Date().toISOString()}`);
|
|
||||||
|
|
||||||
// Atualizar progresso
|
// Atualizar progresso
|
||||||
updateThinkingMessage('web-research', {
|
updateThinkingMessage('web-research', {
|
||||||
@@ -489,22 +449,6 @@ export default function ChatPage() {
|
|||||||
const context = deepResearch.state.context;
|
const context = deepResearch.state.context;
|
||||||
const enrichedQueries = deepResearch.state.enrichedQueries;
|
const enrichedQueries = deepResearch.state.enrichedQueries;
|
||||||
|
|
||||||
if (context) {
|
|
||||||
chatLog.info(`[WebResearch] Using contextual analysis:`, {
|
|
||||||
intent: context.intent,
|
|
||||||
entities: context.entities.length,
|
|
||||||
topics: context.topics.length,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (enrichedQueries) {
|
|
||||||
chatLog.info(`[WebResearch] Using enriched queries:`, {
|
|
||||||
literal: enrichedQueries.literal.length,
|
|
||||||
semantic: enrichedQueries.semantic.length,
|
|
||||||
related: enrichedQueries.related.length,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Executar busca progressiva com semantic search se disponível
|
// Executar busca progressiva com semantic search se disponível
|
||||||
const fallbackResult = await executeProgressiveSearch(
|
const fallbackResult = await executeProgressiveSearch(
|
||||||
query,
|
query,
|
||||||
@@ -528,47 +472,22 @@ export default function ChatPage() {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
const queryDuration = Date.now() - queryStartTime;
|
// Log do resultado
|
||||||
|
chatLog.info(` ✓ Progressive search ${idx + 1} complete:`);
|
||||||
|
chatLog.info(` - Success: ${fallbackResult.success}`);
|
||||||
|
chatLog.info(` - Total results: ${fallbackResult.scrapedSources.length}`);
|
||||||
|
chatLog.info(` - Total analyzed: ${fallbackResult.totalResultsAnalyzed}`);
|
||||||
|
chatLog.info(` - Attempts: ${fallbackResult.attempts.length}`);
|
||||||
|
chatLog.info(` - Used fallback: ${fallbackResult.usedFallback}`);
|
||||||
|
|
||||||
// Log detalhado do resultado
|
// Log detalhado de cada resultado
|
||||||
chatLog.info(`\n[WebResearch] ========== QUERY ${idx + 1} RESULTS ==========`);
|
fallbackResult.scrapedSources.forEach((result, resultIdx) => {
|
||||||
chatLog.info(`[WebResearch] Duration: ${queryDuration}ms`);
|
chatLog.info(` → Result ${resultIdx + 1}: ${result.title}`);
|
||||||
chatLog.info(`[WebResearch] Success: ${fallbackResult.success}`);
|
chatLog.info(` URL: ${result.url}`);
|
||||||
chatLog.info(`[WebResearch] Total results: ${fallbackResult.scrapedSources.length}`);
|
const contentLength = result.markdown?.length || 0;
|
||||||
chatLog.info(`[WebResearch] Total analyzed: ${fallbackResult.totalResultsAnalyzed}`);
|
chatLog.info(` Content length: ${contentLength} chars`);
|
||||||
chatLog.info(`[WebResearch] Attempts: ${fallbackResult.attempts.length}`);
|
|
||||||
chatLog.info(`[WebResearch] Used fallback: ${fallbackResult.usedFallback}`);
|
|
||||||
|
|
||||||
// Log detalhado de cada tentativa
|
|
||||||
fallbackResult.attempts.forEach((attempt, attemptIdx) => {
|
|
||||||
chatLog.info(`\n Attempt ${attemptIdx + 1}:`);
|
|
||||||
chatLog.info(` Round: ${attempt.round}`);
|
|
||||||
chatLog.info(` Strategy: ${attempt.strategy || 'N/A'}`);
|
|
||||||
chatLog.info(` Query: "${attempt.query}"`);
|
|
||||||
chatLog.info(` Results: ${attempt.results.length}`);
|
|
||||||
chatLog.info(` Relevance score: ${attempt.relevanceScore.toFixed(3)}`);
|
|
||||||
chatLog.info(` Duration: ${attempt.duration}ms`);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Log detalhado de cada resultado extraído
|
|
||||||
if (fallbackResult.scrapedSources.length > 0) {
|
|
||||||
chatLog.info(`\n[WebResearch] Extracted Sources:`);
|
|
||||||
fallbackResult.scrapedSources.forEach((result, resultIdx) => {
|
|
||||||
chatLog.info(`\n [${resultIdx + 1}] ${result.title}`);
|
|
||||||
chatLog.info(` URL: ${result.url}`);
|
|
||||||
const contentLength = result.markdown?.length || result.content?.length || 0;
|
|
||||||
const snippetLength = result.snippet?.length || 0;
|
|
||||||
chatLog.info(` Markdown length: ${contentLength} chars`);
|
|
||||||
chatLog.info(` Snippet length: ${snippetLength} chars`);
|
|
||||||
chatLog.info(` Cached: ${result.cached ? 'Yes' : 'No'}`);
|
|
||||||
if (result.markdown) {
|
|
||||||
const preview = result.markdown.substring(0, 200);
|
|
||||||
chatLog.info(` Preview: ${preview}${contentLength > 200 ? '...' : ''}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
chatLog.info(`[WebResearch] ============================================\n`);
|
|
||||||
|
|
||||||
// Adicionar resultados à Knowledge Base
|
// Adicionar resultados à Knowledge Base
|
||||||
if (fallbackResult.scrapedSources.length > 0) {
|
if (fallbackResult.scrapedSources.length > 0) {
|
||||||
deepResearch.addToKnowledgeBase(query, fallbackResult.scrapedSources);
|
deepResearch.addToKnowledgeBase(query, fallbackResult.scrapedSources);
|
||||||
@@ -608,14 +527,13 @@ export default function ChatPage() {
|
|||||||
chatLog.info(`All searches complete. Knowledge Base size: ${deepResearch.state.knowledgeBase.length}`);
|
chatLog.info(`All searches complete. Knowledge Base size: ${deepResearch.state.knowledgeBase.length}`);
|
||||||
|
|
||||||
// Coletar todas as fontes para exibição
|
// Coletar todas as fontes para exibição
|
||||||
scrapedSources = deepResearch.state.knowledgeBase.map(entry => ({
|
scrapedSources = deepResearch.state.knowledgeBase.map(entry => ({
|
||||||
url: entry.sourceUrl,
|
url: entry.sourceUrl,
|
||||||
title: entry.title,
|
title: entry.title,
|
||||||
content: entry.content,
|
content: entry.content,
|
||||||
markdown: entry.content,
|
markdown: entry.content,
|
||||||
snippet: entry.content.substring(0, 200),
|
snippet: entry.content.substring(0, 200)
|
||||||
cached: false
|
}));
|
||||||
}));
|
|
||||||
|
|
||||||
// Adicionar mensagem: Fontes encontradas
|
// Adicionar mensagem: Fontes encontradas
|
||||||
if (scrapedSources.length > 0) {
|
if (scrapedSources.length > 0) {
|
||||||
@@ -628,86 +546,60 @@ export default function ChatPage() {
|
|||||||
|
|
||||||
if (deepResearch.state.knowledgeBase.length > 0) {
|
if (deepResearch.state.knowledgeBase.length > 0) {
|
||||||
// Passo 3: Validação e Contexto
|
// Passo 3: Validação e Contexto
|
||||||
chatLog.info('\n[DeepResearch] ========== STEP 3: VALIDATION ==========');
|
chatLog.info('\nStep 3: Validation');
|
||||||
deepResearch.setStep('aggregating');
|
deepResearch.setStep('aggregating');
|
||||||
|
|
||||||
// Adicionar mensagem: Processamento
|
// Adicionar mensagem: Processamento
|
||||||
addThinkingMessage('processing', 'Processando contexto...', 'running');
|
addThinkingMessage('processing', 'Processando contexto...', 'running');
|
||||||
const validationStart = Date.now();
|
|
||||||
validationReport = await deepResearch.validate(selectedModel, content);
|
validationReport = await deepResearch.validate(selectedModel, content);
|
||||||
const validationDuration = Date.now() - validationStart;
|
chatLog.info(`Validation Report Length: ${validationReport.length} chars`);
|
||||||
|
|
||||||
chatLog.info(`[DeepResearch] Validation duration: ${validationDuration}ms`);
|
|
||||||
chatLog.info(`[DeepResearch] Validation report length: ${validationReport.length} chars`);
|
|
||||||
if (validationReport) {
|
|
||||||
const preview = validationReport.substring(0, 500);
|
|
||||||
chatLog.info(`[DeepResearch] Validation preview: ${preview}${validationReport.length > 500 ? '...' : ''}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Passo 4: Obter contexto curado (usando versão otimizada)
|
// Passo 4: Obter contexto curado (usando versão otimizada)
|
||||||
chatLog.info('\n[DeepResearch] ========== STEP 4: CONTEXT CONDENSATION ==========');
|
chatLog.info('\nStep 4: Getting Curated Context (Optimized)');
|
||||||
|
|
||||||
// Calcular tokens disponíveis dinamicamente
|
// Calcular tokens disponíveis dinamicamente
|
||||||
const { getModelContextInfo } = await import('@/lib/model-context');
|
const { getModelContextInfo } = await import('@/lib/model-context');
|
||||||
const contextInfo = await getModelContextInfo(selectedModel, systemPrompt, messages);
|
const contextInfo = await getModelContextInfo(selectedModel, systemPrompt, messages);
|
||||||
const availableTokens = contextInfo.recommendedContextWindow;
|
const availableTokens = contextInfo.recommendedContextWindow;
|
||||||
|
|
||||||
chatLog.info(`[DeepResearch] Model: ${selectedModel}`);
|
chatLog.info(`Model Context Window: ${contextInfo.maxContextWindow} tokens`);
|
||||||
chatLog.info(`[DeepResearch] Max context window: ${contextInfo.maxContextWindow} tokens`);
|
chatLog.info(`Available Tokens for KB: ${availableTokens} tokens`);
|
||||||
chatLog.info(`[DeepResearch] Available tokens for KB: ${availableTokens} tokens`);
|
|
||||||
|
|
||||||
const condensationStart = Date.now();
|
|
||||||
const optimizedResult = deepResearch.getCuratedContextOptimized(content, availableTokens);
|
const optimizedResult = deepResearch.getCuratedContextOptimized(content, availableTokens);
|
||||||
const condensationDuration = Date.now() - condensationStart;
|
|
||||||
knowledgeBaseContext = optimizedResult.context;
|
knowledgeBaseContext = optimizedResult.context;
|
||||||
|
|
||||||
chatLog.info(`\n[DeepResearch] ========== CONDENSATION SUMMARY ==========`);
|
chatLog.info(`Knowledge Base Context Length: ${knowledgeBaseContext.length} chars`);
|
||||||
chatLog.info(`[DeepResearch] Duration: ${condensationDuration}ms`);
|
chatLog.info(`Condensation Method: ${optimizedResult.result.method}`);
|
||||||
chatLog.info(`[DeepResearch] Final context length: ${knowledgeBaseContext.length} chars`);
|
chatLog.info(`Chunks Used: ${optimizedResult.result.chunksUsed} / ${optimizedResult.result.chunksTotal}`);
|
||||||
chatLog.info(`[DeepResearch] Method: ${optimizedResult.result.method}`);
|
chatLog.info(`Compression Ratio: ${(optimizedResult.result.compressionRatio * 100).toFixed(1)}%`);
|
||||||
chatLog.info(`[DeepResearch] Chunks used: ${optimizedResult.result.chunksUsed} / ${optimizedResult.result.chunksTotal}`);
|
|
||||||
chatLog.info(`[DeepResearch] Compression ratio: ${(optimizedResult.result.compressionRatio * 100).toFixed(1)}%`);
|
|
||||||
chatLog.info(`[DeepResearch] Original tokens: ${optimizedResult.result.originalTokens}`);
|
|
||||||
chatLog.info(`[DeepResearch] Final tokens: ${optimizedResult.result.totalTokens}`);
|
|
||||||
|
|
||||||
// Log detalhado por fonte
|
|
||||||
if (optimizedResult.result.sources.length > 0) {
|
|
||||||
chatLog.info(`[DeepResearch] Chunks per source:`);
|
|
||||||
optimizedResult.result.sources.forEach((source, idx) => {
|
|
||||||
chatLog.info(` [${idx + 1}] ${source.title}: ${source.chunksUsed} chunks`);
|
|
||||||
chatLog.info(` URL: ${source.url}`);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Log preview do contexto se não for muito longo
|
// Log preview do contexto se não for muito longo
|
||||||
if (knowledgeBaseContext.length > 0) {
|
if (knowledgeBaseContext.length > 0) {
|
||||||
chatLog.info(`\n[DeepResearch] Context preview:`);
|
|
||||||
if (knowledgeBaseContext.length > 2000) {
|
if (knowledgeBaseContext.length > 2000) {
|
||||||
chatLog.info(`${knowledgeBaseContext.substring(0, 2000)}...`);
|
chatLog.info(`Context Preview (first 2000 chars):\n${knowledgeBaseContext.substring(0, 2000)}...`);
|
||||||
chatLog.info(`[DeepResearch] (truncated, ${knowledgeBaseContext.length} chars total)`);
|
|
||||||
} else {
|
} else {
|
||||||
chatLog.info(knowledgeBaseContext);
|
chatLog.info(`Full Context:\n${knowledgeBaseContext}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validar contexto
|
// Validar contexto
|
||||||
const { validateCondensedContext } = await import('@/lib/knowledge-base-processor');
|
const { validateCondensedContext } = await import('@/lib/knowledge-base-processor');
|
||||||
const validation = validateCondensedContext(optimizedResult.result, content);
|
const validation = validateCondensedContext(optimizedResult.result, content);
|
||||||
|
|
||||||
chatLog.info(`\n[DeepResearch] ========== CONTEXT VALIDATION ==========`);
|
|
||||||
if (!validation.isValid) {
|
if (!validation.isValid) {
|
||||||
chatLog.error(`[DeepResearch] Validation failed: ${validation.warnings.join(', ')}`);
|
chatLog.error(`Context validation failed: ${validation.warnings.join(', ')}`);
|
||||||
} else if (validation.warnings.length > 0) {
|
} else if (validation.warnings.length > 0) {
|
||||||
validation.warnings.forEach(warning => {
|
validation.warnings.forEach(warning => {
|
||||||
chatLog.warn(`[DeepResearch] ⚠️ ${warning}`);
|
chatLog.warn(`⚠️ ${warning}`);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
chatLog.info(`[DeepResearch] ✓ Context validation passed`);
|
chatLog.info('✓ Context validation passed');
|
||||||
}
|
}
|
||||||
chatLog.info(`[DeepResearch] ============================================\n`);
|
|
||||||
} else {
|
} else {
|
||||||
chatLog.warn('[DeepResearch] ⚠️ Knowledge Base Context is empty!');
|
chatLog.warn('⚠️ Knowledge Base Context is empty!');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setLastWebContext(knowledgeBaseContext);
|
||||||
|
setLastContextSources(scrapedSources);
|
||||||
|
|
||||||
// Atualizar mensagem: Processamento concluído
|
// Atualizar mensagem: Processamento concluído
|
||||||
updateThinkingMessage('processing', {
|
updateThinkingMessage('processing', {
|
||||||
@@ -735,6 +627,8 @@ export default function ChatPage() {
|
|||||||
deepResearch.addToKnowledgeBase(simpleQuery, results);
|
deepResearch.addToKnowledgeBase(simpleQuery, results);
|
||||||
knowledgeBaseContext = deepResearch.getCuratedContext();
|
knowledgeBaseContext = deepResearch.getCuratedContext();
|
||||||
scrapedSources = results;
|
scrapedSources = results;
|
||||||
|
setLastWebContext(knowledgeBaseContext);
|
||||||
|
setLastContextSources(scrapedSources);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
chatLog.info('Simple query returned NO_SEARCH, skipping web search');
|
chatLog.info('Simple query returned NO_SEARCH, skipping web search');
|
||||||
@@ -744,21 +638,17 @@ export default function ChatPage() {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Tratar erro graciosamente sem quebrar o fluxo
|
// Tratar erro graciosamente sem quebrar o fluxo
|
||||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||||
chatLog.warn(`⚠️ Error in Deep Research pipeline (using local model fallback): ${errorMsg}`);
|
chatLog.warn(`⚠️ Error in Deep Research pipeline (continuing with partial results): ${errorMsg}`);
|
||||||
|
|
||||||
// Atualizar mensagem de processo com aviso (não erro fatal)
|
// Atualizar mensagem de processo com aviso (não erro fatal)
|
||||||
updateThinkingMessage('web-research', {
|
updateThinkingMessage('web-research', {
|
||||||
status: 'completed', // Marcar como completed mesmo com erro
|
status: 'completed', // Marcar como completed mesmo com erro parcial
|
||||||
details: `Erro na pesquisa web (${errorMsg}). Usando modelo local como fallback.`,
|
details: `Alguns erros ocorreram durante a pesquisa: ${errorMsg}. Continuando com resultados parciais...`,
|
||||||
duration: Date.now() - webResearchStart,
|
duration: Date.now() - webResearchStart,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Garantir que o estado de erro seja registrado para ativar fallback
|
|
||||||
// O erro já será detectado pelo hasWebSearchError através do estado do hook
|
|
||||||
chatLog.info('Web search error registered - will use local model fallback');
|
|
||||||
|
|
||||||
// Não definir erro global - permitir que o fluxo continue
|
// Não definir erro global - permitir que o fluxo continue
|
||||||
// O sistema continuará com conhecimento interno (fallback automático)
|
// O sistema continuará com conhecimento interno se necessário
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (!webSearch.isEnabled) {
|
if (!webSearch.isEnabled) {
|
||||||
@@ -819,9 +709,8 @@ export default function ChatPage() {
|
|||||||
let enhancedSystemPrompt = systemPrompt;
|
let enhancedSystemPrompt = systemPrompt;
|
||||||
|
|
||||||
// Se tivermos uma Knowledge Base, usar o prompt STRICT_GENERATION
|
// Se tivermos uma Knowledge Base, usar o prompt STRICT_GENERATION
|
||||||
// Verificar se houve fallback (nenhum resultado relevante encontrado ou erro na pesquisa)
|
// Verificar se houve fallback (nenhum resultado relevante encontrado)
|
||||||
const usedFallback = knowledgeBaseContext.length === 0 || knowledgeBaseContext.length < 100;
|
const usedFallback = knowledgeBaseContext.length === 0 || knowledgeBaseContext.length < 100;
|
||||||
const hasWebSearchError = webSearch.status === 'error' || webSearch.error !== null;
|
|
||||||
|
|
||||||
if (knowledgeBaseContext && knowledgeBaseContext.length > 100) {
|
if (knowledgeBaseContext && knowledgeBaseContext.length > 100) {
|
||||||
const strictPrompt = DEEP_RESEARCH_PROMPTS.STRICT_GENERATION
|
const strictPrompt = DEEP_RESEARCH_PROMPTS.STRICT_GENERATION
|
||||||
@@ -830,36 +719,25 @@ export default function ChatPage() {
|
|||||||
.replace('{{userQuery}}', content);
|
.replace('{{userQuery}}', content);
|
||||||
|
|
||||||
enhancedSystemPrompt = strictPrompt;
|
enhancedSystemPrompt = strictPrompt;
|
||||||
} else if (usedFallback || hasWebSearchError) {
|
} else if (usedFallback) {
|
||||||
// Fallback: usar prompt sem contexto web, mas informando que não encontrou fontes
|
// Fallback: usar prompt sem contexto web, mas informando que não encontrou fontes
|
||||||
// Isso garante que o modelo local sempre gere uma resposta mesmo sem dados web
|
|
||||||
const errorContext = hasWebSearchError && webSearch.error
|
|
||||||
? `\n**Motivo:** ${webSearch.error}`
|
|
||||||
: '';
|
|
||||||
|
|
||||||
enhancedSystemPrompt = `${systemPrompt}
|
enhancedSystemPrompt = `${systemPrompt}
|
||||||
|
|
||||||
## ⚠️ FALLBACK PARA CONHECIMENTO INTERNO
|
## ⚠️ AVISO IMPORTANTE
|
||||||
|
|
||||||
Não foi possível acessar fontes web para esta consulta após múltiplas tentativas de busca.${errorContext}
|
Não foi possível encontrar informações relevantes nas fontes web consultadas após múltiplas tentativas de busca.
|
||||||
|
|
||||||
**INSTRUÇÕES CRÍTICAS:**
|
**INSTRUÇÕES:**
|
||||||
- Você DEVE responder usando APENAS seu conhecimento interno (treinamento do modelo)
|
- Responda usando APENAS seu conhecimento interno (treinamento)
|
||||||
- Seja transparente: informe que não foi possível acessar fontes web, mas que você responderá com base no seu conhecimento
|
- Seja honesto e diga: "Não encontrei essa informação nas fontes consultadas."
|
||||||
- Se tiver conhecimento sobre o tópico, compartilhe-o de forma útil e detalhada
|
- Se tiver conhecimento sobre o tópico, compartilhe, mas deixe claro que não há fontes externas verificadas
|
||||||
- Seja honesto sobre limitações: se não souber algo, diga claramente
|
- Não invente informações ou cite fontes que não foram consultadas
|
||||||
- NÃO invente informações ou cite fontes que não foram consultadas
|
|
||||||
- NÃO mencione "fontes consultadas" ou "pesquisa realizada" - apenas responda com seu conhecimento
|
|
||||||
|
|
||||||
**IMPORTANTE:** Este é um fallback legítimo. O usuário espera uma resposta útil mesmo sem dados web. Use seu conhecimento para ajudar da melhor forma possível.
|
|
||||||
|
|
||||||
## DATA E HORA ATUAL DO SISTEMA
|
## DATA E HORA ATUAL DO SISTEMA
|
||||||
|
|
||||||
**DATA/HORA FORMATADA:** ${currentDateTime}
|
**DATA/HORA FORMATADA:** ${currentDateTime}
|
||||||
**DATA/HORA NUMÉRICA:** ${currentDateExplicit}
|
|
||||||
**ISO 8601:** ${currentDateISO}
|
|
||||||
|
|
||||||
Use esta data exata para referências temporais quando relevante.`;
|
Use esta data exata para referências temporais.`;
|
||||||
}
|
}
|
||||||
// Fallback para lógica antiga se não tiver Knowledge Base
|
// Fallback para lógica antiga se não tiver Knowledge Base
|
||||||
else if (knowledgeBaseContext) {
|
else if (knowledgeBaseContext) {
|
||||||
@@ -929,9 +807,6 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
let finalUserContent = content;
|
let finalUserContent = content;
|
||||||
if (knowledgeBaseContext && knowledgeBaseContext.length > 100) {
|
if (knowledgeBaseContext && knowledgeBaseContext.length > 100) {
|
||||||
finalUserContent = `[KNOWLEDGE BASE - ÚNICA FONTE DE VERDADE]\n${knowledgeBaseContext}\n[/KNOWLEDGE BASE]\n\nResponda a pergunta usando APENAS os dados acima. Se a informação não estiver na Knowledge Base, diga "Não encontrei essa informação nas fontes consultadas."\n\nPergunta: ${content}`;
|
finalUserContent = `[KNOWLEDGE BASE - ÚNICA FONTE DE VERDADE]\n${knowledgeBaseContext}\n[/KNOWLEDGE BASE]\n\nResponda a pergunta usando APENAS os dados acima. Se a informação não estiver na Knowledge Base, diga "Não encontrei essa informação nas fontes consultadas."\n\nPergunta: ${content}`;
|
||||||
} else if (usedFallback || hasWebSearchError) {
|
|
||||||
// Quando usar fallback, garantir que o modelo saiba que deve usar conhecimento interno
|
|
||||||
finalUserContent = `Pergunta do usuário: ${content}\n\nNota: Não foi possível acessar fontes web para esta consulta. Responda usando seu conhecimento interno de forma útil e detalhada.`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
chatLog.info(`Final User Content Length: ${finalUserContent.length} chars`);
|
chatLog.info(`Final User Content Length: ${finalUserContent.length} chars`);
|
||||||
@@ -962,149 +837,6 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
chatLog.info('✅ Response generation complete');
|
chatLog.info('✅ Response generation complete');
|
||||||
chatLog.info('========== QUERY COMPLETE ==========\n');
|
chatLog.info('========== QUERY COMPLETE ==========\n');
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
// Capturar dados antes do setMessages para garantir que estão no escopo correto
|
|
||||||
const currentScrapedSources = scrapedSources.length > 0
|
|
||||||
? scrapedSources
|
|
||||||
: deepResearch.state.knowledgeBase.map(entry => ({
|
|
||||||
url: entry.sourceUrl,
|
|
||||||
title: entry.title,
|
|
||||||
content: entry.content,
|
|
||||||
markdown: entry.content,
|
|
||||||
cached: false,
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Coletar thinking steps das mensagens (apenas os relacionados a esta query)
|
|
||||||
const allThinkingSteps: ThinkingMessageMetadata[] = [];
|
|
||||||
const currentMessages = messages; // Capturar referência atual
|
|
||||||
currentMessages.forEach((msg, idx) => {
|
|
||||||
// Coletar thinking steps das últimas mensagens (relacionadas a esta query)
|
|
||||||
if (idx >= currentMessages.length - 10) { // Últimas 10 mensagens
|
|
||||||
if (msg.metadata && typeof msg.metadata === 'object' && 'type' in msg.metadata && msg.metadata.type === 'thinking') {
|
|
||||||
allThinkingSteps.push(msg.metadata as ThinkingMessageMetadata);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Coletar sites pesquisados com detalhes completos
|
|
||||||
const sitesResearched = currentScrapedSources.map((source, idx) => {
|
|
||||||
// Tentar encontrar informações de duração e status dos logs
|
|
||||||
const sourceLog = deepResearch.state.logs.find(log => {
|
|
||||||
if (!log.parsedOutput || typeof log.parsedOutput !== 'object') return false;
|
|
||||||
const parsed = log.parsedOutput as Record<string, unknown>;
|
|
||||||
return 'url' in parsed && parsed.url === source.url;
|
|
||||||
});
|
|
||||||
|
|
||||||
let duration: number | undefined = undefined;
|
|
||||||
if (sourceLog?.parsedOutput && typeof sourceLog.parsedOutput === 'object') {
|
|
||||||
const parsed = sourceLog.parsedOutput as Record<string, unknown>;
|
|
||||||
if ('duration' in parsed && typeof parsed.duration === 'number') {
|
|
||||||
duration = parsed.duration;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
url: source.url,
|
|
||||||
title: source.title || 'Sem título',
|
|
||||||
status: source.cached ? 'cached' : 'scraped',
|
|
||||||
source: source.cached ? 'cache' : 'nodriver',
|
|
||||||
contentLength: source.content?.length || source.markdown?.length || 0,
|
|
||||||
scrapedAt: sourceLog?.timestamp || Date.now(),
|
|
||||||
duration: duration,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
// Coletar dados de raciocínio dos logs do deep research
|
|
||||||
const reasoningSteps = deepResearch.state.logs
|
|
||||||
.filter(log => log.stage === 'generation' || log.stage === 'validation')
|
|
||||||
.map(log => ({
|
|
||||||
stage: log.stage,
|
|
||||||
input: log.input,
|
|
||||||
output: log.rawOutput || JSON.stringify(log.parsedOutput),
|
|
||||||
timestamp: log.timestamp,
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Estimar token usage (aproximado)
|
|
||||||
const estimatedInputTokens = Math.ceil((enhancedSystemPrompt.length + finalUserContent.length) / 4);
|
|
||||||
const lastAssistantMsg = currentMessages.find(m => m.role === 'assistant');
|
|
||||||
const estimatedOutputTokens = Math.ceil((lastAssistantMsg?.content?.length || 0) / 4);
|
|
||||||
|
|
||||||
=======
|
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
// Construir dados de debug para a última mensagem do assistente
|
|
||||||
setMessages(prev => {
|
|
||||||
const newMessages = [...prev];
|
|
||||||
const lastMsgIndex = newMessages.length - 1;
|
|
||||||
if (lastMsgIndex >= 0 && newMessages[lastMsgIndex].role === 'assistant') {
|
|
||||||
const lastMsg = newMessages[lastMsgIndex];
|
|
||||||
const debugData: DebugData = {
|
|
||||||
model: selectedModel,
|
|
||||||
timestamp: Date.now(),
|
|
||||||
latency: Date.now() - responseStart,
|
|
||||||
systemPrompt: enhancedSystemPrompt,
|
|
||||||
userQuery: content,
|
|
||||||
<<<<<<< HEAD
|
|
||||||
contextUsed: prev.filter(m => m.role !== 'system' && m.role !== 'assistant'),
|
|
||||||
webResearch: {
|
|
||||||
queries: deepResearch.state.plan || [],
|
|
||||||
enrichedQueries: deepResearch.state.enrichedQueries || undefined,
|
|
||||||
sources: currentScrapedSources,
|
|
||||||
sitesResearched: sitesResearched,
|
|
||||||
logs: deepResearch.state.logs || [],
|
|
||||||
plan: deepResearch.state.plan || [],
|
|
||||||
=======
|
|
||||||
contextUsed: messages.filter(m => m.role !== 'system'),
|
|
||||||
webResearch: {
|
|
||||||
queries: deepResearch.state.plan || [],
|
|
||||||
enrichedQueries: deepResearch.state.enrichedQueries || undefined,
|
|
||||||
sources: scrapedSources,
|
|
||||||
logs: deepResearch.state.logs,
|
|
||||||
plan: deepResearch.state.plan,
|
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
knowledgeBase: deepResearch.state.knowledgeBase.map(entry => ({
|
|
||||||
sourceUrl: entry.sourceUrl,
|
|
||||||
title: entry.title,
|
|
||||||
content: entry.content,
|
|
||||||
})),
|
|
||||||
<<<<<<< HEAD
|
|
||||||
activeQueries: webSearch.activeQueries.length > 0 ? webSearch.activeQueries : undefined,
|
|
||||||
activeUrls: webSearch.activeUrls.length > 0 ? webSearch.activeUrls : undefined,
|
|
||||||
},
|
|
||||||
deepResearchState: deepResearch.state,
|
|
||||||
thinkingSteps: allThinkingSteps.length > 0 ? allThinkingSteps : undefined,
|
|
||||||
reasoning: reasoningSteps.length > 0 ? {
|
|
||||||
steps: reasoningSteps.map(r => `${r.stage}: ${r.input.substring(0, 100)}...`),
|
|
||||||
intermediateResults: reasoningSteps.map(r => ({
|
|
||||||
stage: r.stage,
|
|
||||||
output: r.output,
|
|
||||||
timestamp: r.timestamp,
|
|
||||||
})),
|
|
||||||
} : undefined,
|
|
||||||
finalResponse: lastMsg.content || '',
|
|
||||||
rawResponse: lastMsg.content || '',
|
|
||||||
tokenUsage: {
|
|
||||||
input: estimatedInputTokens,
|
|
||||||
output: estimatedOutputTokens,
|
|
||||||
total: estimatedInputTokens + estimatedOutputTokens,
|
|
||||||
},
|
|
||||||
=======
|
|
||||||
},
|
|
||||||
deepResearchState: deepResearch.state,
|
|
||||||
finalResponse: lastMsg.content,
|
|
||||||
rawResponse: lastMsg.content,
|
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
};
|
|
||||||
|
|
||||||
// Armazenar debug data usando o índice da mensagem
|
|
||||||
setDebugDataMap(prevMap => {
|
|
||||||
const newMap = new Map(prevMap);
|
|
||||||
newMap.set(lastMsgIndex, debugData);
|
|
||||||
return newMap;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return newMessages;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Persistir fontes na mensagem do assistente (metadata)
|
// Persistir fontes na mensagem do assistente (metadata)
|
||||||
if (scrapedSources.length > 0) {
|
if (scrapedSources.length > 0) {
|
||||||
// Aguardar um pouco para garantir que o sendMessage iniciou e criou a mensagem do assistente
|
// Aguardar um pouco para garantir que o sendMessage iniciou e criou a mensagem do assistente
|
||||||
@@ -1266,6 +998,45 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Copy Logs to Clipboard
|
||||||
|
const handleCopyLogs = async () => {
|
||||||
|
const logs = deepResearch.state.logs;
|
||||||
|
const lastAssistantMessage = messages.filter(m => m.role === 'assistant').pop();
|
||||||
|
|
||||||
|
let logText = `# Deep Research Debug Log\n\n`;
|
||||||
|
logText += `## User Query\n${lastUserQuery}\n\n`;
|
||||||
|
logText += `## Model\n${selectedModel}\n\n`;
|
||||||
|
logText += `## Process Logs\n\n`;
|
||||||
|
|
||||||
|
logs.forEach((log, idx) => {
|
||||||
|
logText += `### ${idx + 1}. Stage: ${log.stage.toUpperCase()}\n`;
|
||||||
|
logText += `- **Time**: ${new Date(log.timestamp).toLocaleTimeString()}\n`;
|
||||||
|
logText += `- **Input**: ${log.input.substring(0, 500)}${log.input.length > 500 ? '...' : ''}\n`;
|
||||||
|
if (log.rawOutput) {
|
||||||
|
logText += `- **Raw Output**: ${log.rawOutput.substring(0, 500)}${log.rawOutput.length > 500 ? '...' : ''}\n`;
|
||||||
|
}
|
||||||
|
if (log.parsedOutput) {
|
||||||
|
logText += `- **Parsed Output**: \`\`\`json\n${JSON.stringify(log.parsedOutput, null, 2)}\n\`\`\`\n`;
|
||||||
|
}
|
||||||
|
if (log.error) {
|
||||||
|
logText += `- **Error**: ${log.error}\n`;
|
||||||
|
}
|
||||||
|
logText += '\n';
|
||||||
|
});
|
||||||
|
|
||||||
|
logText += `## AI Response\n`;
|
||||||
|
logText += lastAssistantMessage?.content || '[No response yet]';
|
||||||
|
logText += '\n\n---\n';
|
||||||
|
logText += `Generated at: ${new Date().toISOString()}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(logText);
|
||||||
|
setLogsCopied(true);
|
||||||
|
setTimeout(() => setLogsCopied(false), 2000);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to copy logs:', err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="h-screen w-full bg-background overflow-hidden flex flex-col overflow-x-hidden">
|
<div className="h-screen w-full bg-background overflow-hidden flex flex-col overflow-x-hidden">
|
||||||
@@ -1273,19 +1044,19 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
<TitleBar />
|
<TitleBar />
|
||||||
|
|
||||||
{/* Main Content Area */}
|
{/* Main Content Area */}
|
||||||
<div className="flex-1 flex overflow-hidden pt-8">
|
<div className="flex-1 flex overflow-hidden">
|
||||||
<ResizablePanelGroup direction="horizontal" className="flex-1">
|
<ResizablePanelGroup direction="horizontal" className="flex-1">
|
||||||
|
|
||||||
<ResizablePanel
|
<ResizablePanel
|
||||||
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" />
|
||||||
@@ -1293,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" />
|
||||||
@@ -1348,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"
|
||||||
@@ -1366,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>
|
||||||
@@ -1380,7 +1153,61 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
|
|
||||||
<div className="flex-1 max-w-full sm:max-w-[420px] flex items-center gap-2 min-w-0">
|
<div className="flex-1 max-w-full sm:max-w-[420px] flex items-center gap-2 min-w-0">
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<ModelSelector />
|
<TooltipProvider>
|
||||||
|
<Select
|
||||||
|
value={selectedModel || undefined}
|
||||||
|
onValueChange={(v) => {
|
||||||
|
if (v === "__add_model__") {
|
||||||
|
setShowDownloadDialog(true);
|
||||||
|
// Não alterar selectedModel quando abrir dialog
|
||||||
|
} else {
|
||||||
|
setSelectedModel(v);
|
||||||
|
settings.setSelectedModel(v);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<SelectTrigger className="h-9 min-w-0 max-w-full">
|
||||||
|
<SelectValue placeholder="Selecione um modelo..." className="truncate" />
|
||||||
|
</SelectTrigger>
|
||||||
|
</TooltipTrigger>
|
||||||
|
{selectedModel && (
|
||||||
|
<TooltipContent side="top" className="max-w-[70vw] break-words">
|
||||||
|
<p className="text-sm">{selectedModel}</p>
|
||||||
|
</TooltipContent>
|
||||||
|
)}
|
||||||
|
</Tooltip>
|
||||||
|
<SelectContent className="max-w-[90vw] sm:max-w-[420px]">
|
||||||
|
{models.map(m => (
|
||||||
|
<Tooltip key={m.name}>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<SelectItem value={m.name} className="min-w-0">
|
||||||
|
<span className="flex items-center justify-between w-full min-w-0 gap-2">
|
||||||
|
<span className="flex items-center gap-2 truncate flex-1 min-w-0" style={{ maxWidth: '70vw' }}>
|
||||||
|
<Cpu className="w-4 h-4 text-muted-foreground shrink-0" />
|
||||||
|
<span className="truncate">{m.name}</span>
|
||||||
|
</span>
|
||||||
|
<span className="ml-2 text-xs text-muted-foreground shrink-0">{m.size}</span>
|
||||||
|
</span>
|
||||||
|
</SelectItem>
|
||||||
|
</TooltipTrigger>
|
||||||
|
{m.name.length > 40 && (
|
||||||
|
<TooltipContent side="right" className="max-w-[70vw] break-words">
|
||||||
|
<p className="text-sm">{m.name}</p>
|
||||||
|
</TooltipContent>
|
||||||
|
)}
|
||||||
|
</Tooltip>
|
||||||
|
))}
|
||||||
|
<SelectItem value="__add_model__" className="font-medium">
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
Adicionar modelo...
|
||||||
|
</span>
|
||||||
|
</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</TooltipProvider>
|
||||||
</div>
|
</div>
|
||||||
<Button variant="outline" size="icon" className="h-9 w-9" onClick={refresh} title="Atualizar modelos">
|
<Button variant="outline" size="icon" className="h-9 w-9" onClick={refresh} title="Atualizar modelos">
|
||||||
<RefreshCw className="w-4 h-4" />
|
<RefreshCw className="w-4 h-4" />
|
||||||
@@ -1396,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">
|
||||||
@@ -1408,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>
|
||||||
@@ -1555,7 +1382,6 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
highlightTerm={searchQuery && searchQuery.trim().length >= 2 ? searchQuery.trim() : undefined}
|
highlightTerm={searchQuery && searchQuery.trim().length >= 2 ? searchQuery.trim() : undefined}
|
||||||
highlightIndex={messageMatchIndex}
|
highlightIndex={messageMatchIndex}
|
||||||
messageIndex={group.index}
|
messageIndex={group.index}
|
||||||
debugData={group.index !== undefined ? debugDataMap.get(group.index) : undefined}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -1566,6 +1392,71 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Debug Info (Moved inside scroll) */}
|
||||||
|
{(deepResearch.state.logs.length > 0 || lastWebContext) && (
|
||||||
|
<div className="mt-12 pt-6 border-t border-dashed border-border">
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Process Log Toggle */}
|
||||||
|
{deepResearch.state.logs.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowProcessDebug((prev) => !prev)}
|
||||||
|
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" />
|
||||||
|
Debug: Processo de Pensamento
|
||||||
|
<ChevronDown className={`w-3 h-3 transition-transform ${showProcessDebug ? 'rotate-180' : ''}`} />
|
||||||
|
</button>
|
||||||
|
{showProcessDebug && (
|
||||||
|
<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">
|
||||||
|
<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
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{deepResearch.state.logs.map((log, idx) => (
|
||||||
|
<div key={idx} className="grid grid-cols-[60px_1fr] gap-2 border-b border-border/60 pb-2 last:border-0">
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Context Debug Toggle */}
|
||||||
|
{lastWebContext && (
|
||||||
|
<div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowContextDebug((prev) => !prev)}
|
||||||
|
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" />
|
||||||
|
Debug: Contexto Web ({lastContextSources.length} fontes)
|
||||||
|
<ChevronDown className={`w-3 h-3 transition-transform ${showContextDebug ? 'rotate-180' : ''}`} />
|
||||||
|
</button>
|
||||||
|
{showContextDebug && (
|
||||||
|
<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">
|
||||||
|
{lastContextSources.map((s, i) => (
|
||||||
|
<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 className="border-t border-border pt-2">
|
||||||
|
<p className="mb-1 font-semibold">Preview Contexto:</p>
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Spacer for Bottom Input */}
|
{/* Spacer for Bottom Input */}
|
||||||
<div className="h-32 md:h-40 w-full shrink-0" ref={messagesEndRef} />
|
<div className="h-32 md:h-40 w-full shrink-0" ref={messagesEndRef} />
|
||||||
</div>
|
</div>
|
||||||
@@ -1577,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}
|
||||||
@@ -1592,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>
|
||||||
@@ -1606,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}
|
||||||
@@ -1652,3 +1543,4 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
+171
-205
@@ -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,86 +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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Utility class para ocultar scrollbar */
|
|
||||||
.scrollbar-hide {
|
|
||||||
-ms-overflow-style: none; /* IE and Edge */
|
|
||||||
scrollbar-width: none; /* Firefox */
|
|
||||||
}
|
|
||||||
|
|
||||||
.scrollbar-hide::-webkit-scrollbar {
|
|
||||||
display: none; /* Chrome, Safari and Opera */
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -412,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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 136 KiB |
+4
-38
@@ -1,34 +1,13 @@
|
|||||||
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";
|
||||||
import { KeyboardShortcuts } from "@/components/keyboard-shortcuts";
|
|
||||||
<<<<<<< HEAD
|
|
||||||
import { DownloadProvider } from "@/contexts/download-context";
|
|
||||||
import { GlobalDownloadStatusBar } from "@/components/global-download-status-bar";
|
|
||||||
import { OllamaHealthProvider } from "@/contexts/ollama-health-context";
|
|
||||||
import { ServiceInterruptionOverlay } from "@/components/ui/service-interruption-overlay";
|
|
||||||
=======
|
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
|
|
||||||
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",
|
||||||
icons: {
|
|
||||||
icon: "/icon.png",
|
|
||||||
apple: "/icon.png",
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
@@ -39,29 +18,16 @@ 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
|
||||||
>
|
>
|
||||||
<<<<<<< HEAD
|
|
||||||
<OllamaHealthProvider>
|
|
||||||
<DownloadProvider>
|
|
||||||
<KeyboardShortcuts />
|
|
||||||
{children}
|
|
||||||
<AppUpdaterProvider />
|
|
||||||
<GlobalDownloadStatusBar />
|
|
||||||
<ServiceInterruptionOverlay />
|
|
||||||
</DownloadProvider>
|
|
||||||
</OllamaHealthProvider>
|
|
||||||
=======
|
|
||||||
<KeyboardShortcuts />
|
|
||||||
{children}
|
{children}
|
||||||
<AppUpdaterProvider />
|
<AppUpdaterProvider />
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+32
-183
@@ -1,230 +1,80 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
<<<<<<< HEAD
|
import { useOllamaCheck } from "@/hooks/use-ollama-check";
|
||||||
import { TitleBar } from "@/components/titlebar";
|
|
||||||
import { Loader2 } from "lucide-react";
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { useEffect, useState, startTransition, useRef } from "react";
|
|
||||||
import { useSettingsStore } from "@/store/settings-store";
|
|
||||||
import { invoke } from "@tauri-apps/api/core";
|
|
||||||
|
|
||||||
export default function Home() {
|
|
||||||
=======
|
|
||||||
import { useSetupCheck } from "@/hooks/use-setup-check";
|
|
||||||
import { Hero } from "@/components/landing/hero";
|
import { Hero } from "@/components/landing/hero";
|
||||||
import { InstallModal } from "@/components/modals/install-modal";
|
import { InstallModal } from "@/components/modals/install-modal";
|
||||||
import { StoppedCard } from "@/components/landing/stopped-card";
|
import { StoppedCard } from "@/components/landing/stopped-card";
|
||||||
import { WelcomeNotification } from "@/components/notifications/welcome-notification";
|
import { WelcomeNotification } from "@/components/notifications/welcome-notification";
|
||||||
import { Loader2 } from "lucide-react";
|
import { Loader2 } from "lucide-react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useEffect, startTransition } from "react";
|
import { useEffect } from "react";
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
const { status, ollamaStatus, checkingStep, recheck } = useSetupCheck();
|
const { status, check } = useOllamaCheck();
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { setSetupCompleted } = useSettingsStore();
|
|
||||||
const [isHydrated, setIsHydrated] = useState(false);
|
|
||||||
const [isChecking, setIsChecking] = useState(true);
|
|
||||||
|
|
||||||
// Refs para evitar loops e execuções múltiplas
|
|
||||||
const hasCheckedRef = useRef(false);
|
|
||||||
const isRedirectingRef = useRef(false);
|
|
||||||
|
|
||||||
<<<<<<< HEAD
|
// Tentar iniciar Ollama automaticamente quando o componente montar
|
||||||
// Hydration check: aguardar Zustand carregar do localStorage
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setIsHydrated(true);
|
const tryAutoStart = async () => {
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Guarda de roteamento: verificação de integridade do Ollama + flag persistente
|
|
||||||
// Prioridade: Integridade do Sistema > Flag de Setup
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isHydrated) return;
|
|
||||||
if (hasCheckedRef.current) return; // Proteção contra múltiplas execuções
|
|
||||||
|
|
||||||
const performCheck = async () => {
|
|
||||||
if (isRedirectingRef.current) return; // Evitar múltiplos redirecionamentos
|
|
||||||
|
|
||||||
setIsChecking(true);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 1. Verificação Real do Sistema (Fonte da Verdade)
|
const { invoke } = await import("@tauri-apps/api/core");
|
||||||
const isOllamaIntact = await invoke<boolean>('verify_ollama_integrity_command');
|
await invoke('auto_start_ollama');
|
||||||
|
// Aguardar um pouco e verificar novamente
|
||||||
// Ler isSetupCompleted diretamente do store (não usar como dependência)
|
setTimeout(() => {
|
||||||
const currentSetupStatus = useSettingsStore.getState().isSetupCompleted;
|
check();
|
||||||
|
}, 2000);
|
||||||
if (!isOllamaIntact) {
|
} catch (error) {
|
||||||
// Se o motor não existe, força o setup, não importa o que o storage diga
|
console.error('Erro ao tentar iniciar Ollama automaticamente:', error);
|
||||||
console.warn("Integridade do Ollama falhou. Redirecionando para Setup.");
|
|
||||||
|
|
||||||
if (!isRedirectingRef.current) {
|
|
||||||
isRedirectingRef.current = true;
|
|
||||||
// Resetar flag de setup se Ollama não está íntegro (ANTES de redirecionar)
|
|
||||||
setSetupCompleted(false);
|
|
||||||
|
|
||||||
// Pequeno delay para garantir que o estado seja persistido no localStorage
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 100));
|
|
||||||
|
|
||||||
startTransition(() => {
|
|
||||||
router.replace('/setup');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Verificação de Fluxo de UI (apenas se Ollama está OK)
|
|
||||||
if (!isRedirectingRef.current) {
|
|
||||||
isRedirectingRef.current = true;
|
|
||||||
|
|
||||||
if (currentSetupStatus) {
|
|
||||||
startTransition(() => {
|
|
||||||
router.replace('/chat');
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
startTransition(() => {
|
|
||||||
router.replace('/setup');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error("Falha crítica no check de inicialização", e);
|
|
||||||
// Fallback seguro: sempre ir para setup em caso de erro
|
|
||||||
if (!isRedirectingRef.current) {
|
|
||||||
isRedirectingRef.current = true;
|
|
||||||
setSetupCompleted(false);
|
|
||||||
|
|
||||||
// Pequeno delay para garantir que o estado seja persistido no localStorage
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 100));
|
|
||||||
|
|
||||||
startTransition(() => {
|
|
||||||
router.replace('/setup');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
setIsChecking(false);
|
|
||||||
hasCheckedRef.current = true; // Marcar como executado
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
performCheck();
|
// Só tentar se estiver instalado mas não rodando
|
||||||
}, [isHydrated, router, setSetupCompleted]);
|
if (status === 'installed_stopped') {
|
||||||
|
tryAutoStart();
|
||||||
// Enquanto não hidratou ou está verificando, retornar skeleton simples
|
|
||||||
if (!isHydrated || isChecking) {
|
|
||||||
return (
|
|
||||||
<div className="h-screen w-full bg-background overflow-hidden flex flex-col">
|
|
||||||
<TitleBar />
|
|
||||||
<div className="flex-1 flex items-center justify-center pt-8">
|
|
||||||
<div className="flex flex-col items-center gap-4">
|
|
||||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
|
||||||
<div className="flex flex-col items-center gap-1">
|
|
||||||
<span className="text-sm font-medium text-foreground">
|
|
||||||
{!isHydrated ? 'Carregando...' : 'Verificando sistema...'}
|
|
||||||
</span>
|
|
||||||
<span className="text-xs text-muted-foreground">Aguarde um momento...</span>
|
|
||||||
</div>
|
|
||||||
=======
|
|
||||||
// Redirecionar automaticamente se tudo estiver pronto
|
|
||||||
useEffect(() => {
|
|
||||||
if (status === 'ready') {
|
|
||||||
const setupComplete = localStorage.getItem("ollahub_setup_complete");
|
|
||||||
|
|
||||||
// Se setup não foi marcado como completo, marcar agora
|
|
||||||
if (!setupComplete) {
|
|
||||||
localStorage.setItem("ollahub_setup_complete", "true");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Redirecionar para chat imediatamente (startTransition já garante não-bloqueio)
|
|
||||||
startTransition(() => {
|
|
||||||
router.push("/chat");
|
|
||||||
});
|
|
||||||
|
|
||||||
return () => clearTimeout(timer);
|
|
||||||
}
|
}
|
||||||
}, [status, router]);
|
}, [status, check]);
|
||||||
|
|
||||||
const handleStart = () => {
|
const handleStart = () => {
|
||||||
const setupComplete = localStorage.getItem("ollahub_setup_complete");
|
const setupComplete = localStorage.getItem("ollahub_setup_complete");
|
||||||
if (setupComplete) {
|
if (setupComplete) {
|
||||||
startTransition(() => {
|
router.push("/chat");
|
||||||
router.push("/chat");
|
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
startTransition(() => {
|
router.push("/setup");
|
||||||
router.push("/setup");
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Mostrar loading durante verificação
|
|
||||||
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">
|
||||||
<div className="flex flex-col items-center gap-4">
|
<Loader2 className="h-5 w-5 animate-spin text-primary" />
|
||||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
<span className="text-muted-foreground">Verificando sistema...</span>
|
||||||
<div className="flex flex-col items-center gap-1">
|
|
||||||
<span className="text-sm font-medium text-foreground">{checkingStep}</span>
|
|
||||||
<span className="text-xs text-muted-foreground">Aguarde um momento...</span>
|
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Após verificação, mostrar loading de redirecionamento (não deve aparecer por muito tempo)
|
|
||||||
return (
|
return (
|
||||||
<<<<<<< HEAD
|
<main className="flex min-h-screen flex-col items-center justify-center p-4 bg-background text-foreground">
|
||||||
<div className="h-screen w-full bg-background overflow-hidden flex flex-col">
|
|
||||||
<TitleBar />
|
|
||||||
<div className="flex-1 flex items-center justify-center pt-8">
|
|
||||||
<div className="flex flex-col items-center gap-4">
|
|
||||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
|
||||||
<div className="flex flex-col items-center gap-1">
|
|
||||||
<span className="text-sm font-medium text-foreground">Redirecionando...</span>
|
|
||||||
<span className="text-xs text-muted-foreground">Aguarde um momento...</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
=======
|
|
||||||
<main className="flex min-h-screen flex-col items-center justify-center p-4 bg-background text-foreground transition-colors duration-300">
|
|
||||||
{/* Notificação de boas-vindas */}
|
{/* Notificação de boas-vindas */}
|
||||||
<WelcomeNotification />
|
<WelcomeNotification />
|
||||||
|
|
||||||
{/* Layout for Ready State - Redirecionamento automático */}
|
{/* Layout for Running State */}
|
||||||
{status === 'ready' && (
|
{status === 'running' && (
|
||||||
<div className="flex h-screen w-full items-center justify-center bg-background">
|
|
||||||
<div className="flex flex-col items-center gap-4 animate-in fade-in duration-300">
|
|
||||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
|
||||||
<div className="flex flex-col items-center gap-1">
|
|
||||||
<span className="text-sm font-medium text-foreground">Tudo pronto!</span>
|
|
||||||
<span className="text-xs text-muted-foreground">Redirecionando para o chat...</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Layout for Needs Setup State */}
|
|
||||||
{status === 'needs_setup' && ollamaStatus === 'running' && (
|
|
||||||
<Hero onStart={handleStart} />
|
<Hero onStart={handleStart} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Layout for Stopped State */}
|
{/* Layout for Stopped State */}
|
||||||
{status === 'needs_setup' && ollamaStatus === '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={recheck} />
|
<StoppedCard onCheckAgain={check} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Layout for Not Installed State (Background + Modal) */}
|
{/* Layout for Not Installed State (Background + Modal) */}
|
||||||
{status === 'needs_ollama' && (
|
{status === 'not_installed' && (
|
||||||
<>
|
<>
|
||||||
<div className="opacity-20 pointer-events-none blur-sm">
|
<div className="opacity-20 pointer-events-none blur-sm">
|
||||||
<Hero onStart={() => {}} />
|
<Hero onStart={() => {}} />
|
||||||
@@ -232,11 +82,10 @@ export default function Home() {
|
|||||||
{/* Hero is shown in background, modal is open */}
|
{/* Hero is shown in background, modal is open */}
|
||||||
<InstallModal
|
<InstallModal
|
||||||
open={true}
|
open={true}
|
||||||
onCheckAgain={recheck}
|
onCheckAgain={check}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</main>
|
</main>
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
+990
-1547
File diff suppressed because it is too large.
Load diff
+26
-19
@@ -1,41 +1,48 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
import { SetupWizard } from '@/components/setup/setup-wizard';
|
|
||||||
import { TitleBar } from '@/components/titlebar';
|
|
||||||
|
|
||||||
export default function SetupPage() {
|
|
||||||
=======
|
|
||||||
import { useHardware } from "@/hooks/use-hardware";
|
import { useHardware } from "@/hooks/use-hardware";
|
||||||
import { HardwareScan } from "@/components/setup/hardware-scan";
|
import { HardwareScan } from "@/components/setup/hardware-scan";
|
||||||
import { GpuSelector } from "@/components/setup/gpu-selector";
|
import { GpuSelector } from "@/components/setup/gpu-selector";
|
||||||
import { ModelSelector } from "@/components/setup/model-selector";
|
import { ModelSelector } from "@/components/setup/model-selector";
|
||||||
import { getRecommendation } from "@/lib/recommendation";
|
import { getRecommendation } from "@/lib/recommendation";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { startTransition, useState } from "react";
|
|
||||||
|
|
||||||
export default function SetupPage() {
|
export default function SetupPage() {
|
||||||
const { specs, loading, gpus } = useHardware();
|
const { specs, loading, gpus } = useHardware();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [isNavigating, setIsNavigating] = useState(false);
|
|
||||||
|
|
||||||
const handleComplete = () => {
|
const handleComplete = () => {
|
||||||
setIsNavigating(true);
|
|
||||||
// Save setup state if needed
|
// Save setup state if needed
|
||||||
localStorage.setItem("ollahub_setup_complete", "true");
|
localStorage.setItem("ollahub_setup_complete", "true");
|
||||||
|
router.push("/chat");
|
||||||
// Usar startTransition para navegação não-bloqueante
|
|
||||||
startTransition(() => {
|
|
||||||
router.push("/chat");
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
return (
|
return (
|
||||||
<div className="h-screen w-full bg-background overflow-hidden flex flex-col">
|
<main className="flex min-h-screen flex-col items-center justify-center p-4 bg-background text-foreground">
|
||||||
<TitleBar />
|
<div className="w-full max-w-2xl space-y-8 animate-in fade-in duration-200 ease-out">
|
||||||
<SetupWizard />
|
<div className="text-center space-y-2">
|
||||||
</div>
|
<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>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<HardwareScan specs={specs} loading={loading} />
|
||||||
|
|
||||||
|
{!loading && specs && gpus.length > 0 && (
|
||||||
|
<div className="animate-in fade-in duration-200 ease-out">
|
||||||
|
<GpuSelector gpus={gpus} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!loading && specs && (
|
||||||
|
<div className="animate-in fade-in duration-200 ease-out">
|
||||||
|
<ModelSelector
|
||||||
|
recommendation={getRecommendation(specs)}
|
||||||
|
onComplete={handleComplete}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
+12
-10
@@ -105,13 +105,13 @@ export default function TasksPage() {
|
|||||||
return (
|
return (
|
||||||
<div className="h-screen w-full bg-background overflow-hidden flex flex-col">
|
<div className="h-screen w-full bg-background overflow-hidden flex flex-col">
|
||||||
<TitleBar />
|
<TitleBar />
|
||||||
<div className="flex-1 overflow-y-auto pt-8">
|
<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>
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="420" viewBox="0 0 1200 420" role="img" aria-labelledby="title desc">
|
||||||
|
<title id="title">OllaHub</title>
|
||||||
|
<desc id="desc">OllaHub: a desktop window with a chat sidebar, a local Ollama model download in progress, an answer backed by numbered web sources, and Web and MCP toggles in the message box.</desc>
|
||||||
|
|
||||||
|
<rect width="1200" height="420" rx="24" fill="#09090B"/>
|
||||||
|
|
||||||
|
<g id="title-block" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif">
|
||||||
|
<text x="64" y="170" font-size="64" font-weight="700" fill="#FAFAFA">OllaHub</text>
|
||||||
|
<text x="64" y="226" font-size="28" fill="#FAFAFA">Desktop chat for your local Ollama</text>
|
||||||
|
<text x="64" y="264" font-size="28" fill="#FAFAFA">models, with web search and MCP.</text>
|
||||||
|
<text x="64" y="322" font-size="20" fill="#9F9FA9" font-family="ui-monospace, 'SF Mono', Consolas, monospace">Tauri 2 · Rust · Next.js 16 · React 19</text>
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<g id="window" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif">
|
||||||
|
<rect x="608" y="52" width="528" height="316" rx="14" fill="#09090B" stroke="#27272A" stroke-width="2"/>
|
||||||
|
<path d="M622 52 h500 a14 14 0 0 1 14 14 v26 h-528 v-26 a14 14 0 0 1 14 -14 z" fill="#18181B"/>
|
||||||
|
<text x="628" y="79" font-size="18" fill="#9F9FA9">OllaHub</text>
|
||||||
|
<g fill="none" stroke="#9F9FA9" stroke-width="2" stroke-linecap="round">
|
||||||
|
<path d="M1052 72 h14"/>
|
||||||
|
<rect x="1078" y="65" width="14" height="14" rx="2"/>
|
||||||
|
<path d="M1106 65 l14 14 M1120 65 l-14 14"/>
|
||||||
|
</g>
|
||||||
|
<path d="M608 92 h528" stroke="#27272A" stroke-width="2"/>
|
||||||
|
|
||||||
|
<path d="M608 92 h144 v276 h-130 a14 14 0 0 1 -14 -14 z" fill="#18181B"/>
|
||||||
|
<rect x="622" y="108" width="116" height="34" rx="8" fill="#1447E6"/>
|
||||||
|
<text x="680" y="131" font-size="18" fill="#FAFAFA" text-anchor="middle">New chat</text>
|
||||||
|
<rect x="622" y="166" width="100" height="10" rx="5" fill="#27272A"/>
|
||||||
|
<rect x="622" y="192" width="84" height="10" rx="5" fill="#27272A"/>
|
||||||
|
<rect x="622" y="218" width="94" height="10" rx="5" fill="#27272A"/>
|
||||||
|
<rect x="622" y="244" width="72" height="10" rx="5" fill="#27272A"/>
|
||||||
|
|
||||||
|
<text x="772" y="128" font-size="18" fill="#FAFAFA" font-family="ui-monospace, 'SF Mono', Consolas, monospace">qwen2.5:0.5b</text>
|
||||||
|
<rect x="772" y="140" width="344" height="10" rx="5" fill="#27272A"/>
|
||||||
|
<rect x="772" y="140" width="220" height="10" rx="5" fill="#1447E6"/>
|
||||||
|
|
||||||
|
<rect x="772" y="170" width="344" height="116" rx="12" fill="#201E25"/>
|
||||||
|
<rect x="790" y="190" width="290" height="10" rx="5" fill="#9F9FA9"/>
|
||||||
|
<rect x="790" y="212" width="300" height="10" rx="5" fill="#9F9FA9"/>
|
||||||
|
<rect x="790" y="234" width="180" height="10" rx="5" fill="#9F9FA9"/>
|
||||||
|
<text x="790" y="272" font-size="18" fill="#9F9FA9">Sources</text>
|
||||||
|
<g font-size="18" fill="#FAFAFA" text-anchor="middle">
|
||||||
|
<rect x="866" y="254" width="26" height="26" rx="13" fill="#27272A"/>
|
||||||
|
<text x="879" y="273">1</text>
|
||||||
|
<rect x="898" y="254" width="26" height="26" rx="13" fill="#27272A"/>
|
||||||
|
<text x="911" y="273">2</text>
|
||||||
|
<rect x="930" y="254" width="26" height="26" rx="13" fill="#27272A"/>
|
||||||
|
<text x="943" y="273">3</text>
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<rect x="772" y="302" width="344" height="40" rx="20" fill="#18181B" stroke="#27272A" stroke-width="2"/>
|
||||||
|
<rect x="782" y="309" width="60" height="26" rx="13" fill="#27272A"/>
|
||||||
|
<text x="812" y="328" font-size="18" fill="#FAFAFA" text-anchor="middle">Web</text>
|
||||||
|
<rect x="850" y="309" width="62" height="26" rx="13" fill="#27272A"/>
|
||||||
|
<text x="881" y="328" font-size="18" fill="#FAFAFA" text-anchor="middle">MCP</text>
|
||||||
|
<circle cx="1096" cy="322" r="13" fill="#1447E6"/>
|
||||||
|
<path d="M1096 328 v-12 M1090 321 l6 -6 l6 6" fill="none" stroke="#FAFAFA" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 3.8 KiB |
@@ -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>
|
||||||
|
|||||||
@@ -8,9 +8,7 @@ import { markdownRenderers } from "./markdown-renderers";
|
|||||||
import { MessageActions } from "./message-actions";
|
import { MessageActions } from "./message-actions";
|
||||||
import { MessageBackground } from "./message-background";
|
import { MessageBackground } from "./message-background";
|
||||||
import { MessageStepThinking } from "./message-step-thinking";
|
import { MessageStepThinking } from "./message-step-thinking";
|
||||||
import { DebugConsole, type DebugData } from "./debug-console";
|
|
||||||
import type { ThinkingMessageMetadata } from "@/hooks/use-chat";
|
import type { ThinkingMessageMetadata } from "@/hooks/use-chat";
|
||||||
import { useSettingsStore } from "@/store/settings-store";
|
|
||||||
|
|
||||||
interface ChatMessageProps {
|
interface ChatMessageProps {
|
||||||
message: Message;
|
message: Message;
|
||||||
@@ -18,17 +16,16 @@ interface ChatMessageProps {
|
|||||||
highlightTerm?: string;
|
highlightTerm?: string;
|
||||||
highlightIndex?: number;
|
highlightIndex?: number;
|
||||||
messageIndex?: number;
|
messageIndex?: number;
|
||||||
debugData?: DebugData;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Componente de mensagem do chat otimizado com React.memo
|
* Componente de mensagem do chat otimizado com React.memo
|
||||||
*
|
*
|
||||||
* Renderiza markdown em tempo real durante streaming para melhor UX.
|
* Durante streaming, usa renderização simplificada (texto puro) para evitar
|
||||||
* Usa useMemo para otimizar re-renders e manter performance.
|
* recálculo custoso da árvore DOM e syntax highlight a cada token.
|
||||||
|
* Markdown completo é aplicado apenas quando a mensagem está finalizada.
|
||||||
*/
|
*/
|
||||||
function ChatMessageComponent({ message, isStreaming = false, highlightTerm, highlightIndex = 0, messageIndex, debugData }: ChatMessageProps) {
|
function ChatMessageComponent({ message, isStreaming = false, highlightTerm, highlightIndex = 0, messageIndex }: ChatMessageProps) {
|
||||||
const debugMode = useSettingsStore(state => state.debugMode);
|
|
||||||
// Verificar se é mensagem de processo de pensamento
|
// Verificar se é mensagem de processo de pensamento
|
||||||
const isThinkingMessage = message.metadata &&
|
const isThinkingMessage = message.metadata &&
|
||||||
typeof message.metadata === 'object' &&
|
typeof message.metadata === 'object' &&
|
||||||
@@ -64,9 +61,6 @@ function ChatMessageComponent({ message, isStreaming = false, highlightTerm, hig
|
|||||||
|
|
||||||
return content || message.content;
|
return content || message.content;
|
||||||
}, [message.content]);
|
}, [message.content]);
|
||||||
|
|
||||||
// Memoizar conteúdo markdown para otimizar re-renders durante streaming
|
|
||||||
const markdownContent = useMemo(() => processedContent, [processedContent]);
|
|
||||||
|
|
||||||
// Processar highlight separadamente (após limpeza de conteúdo)
|
// Processar highlight separadamente (após limpeza de conteúdo)
|
||||||
// Desabilitar durante streaming para performance
|
// Desabilitar durante streaming para performance
|
||||||
@@ -104,11 +98,11 @@ function ChatMessageComponent({ message, isStreaming = false, highlightTerm, hig
|
|||||||
// Adicionar texto antes do match
|
// Adicionar texto antes do match
|
||||||
highlighted += 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}">${match.text}</mark>`;
|
highlighted += `<mark class="${className}">${match.text}</mark>`;
|
||||||
lastIndex = match.end;
|
lastIndex = match.end;
|
||||||
@@ -120,101 +114,76 @@ function ChatMessageComponent({ message, isStreaming = false, highlightTerm, hig
|
|||||||
}, [processedContent, highlightTerm, highlightIndex, message.role, isStreaming]);
|
}, [processedContent, highlightTerm, highlightIndex, message.role, isStreaming]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<MessageBackground
|
||||||
<MessageBackground
|
role={isUser ? 'user' : 'assistant'}
|
||||||
role={isUser ? 'user' : 'assistant'}
|
state={selected ? 'selected' : 'normal'}
|
||||||
state={selected ? 'selected' : 'normal'}
|
className={cn(
|
||||||
className={cn(
|
"cursor-default transition-colors duration-150 rounded-lg",
|
||||||
"cursor-default transition-colors rounded-xl",
|
selected && "bg-surface",
|
||||||
selected && "bg-muted/40",
|
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">
|
||||||
<div className="flex-shrink-0 mt-0.5">
|
<div className="w-8 h-8 rounded-full flex items-center justify-center border bg-surface text-muted-foreground">
|
||||||
<div className={cn(
|
{isUser ? <User className="w-4 h-4" /> : <Bot className="w-4 h-4 text-foreground" />}
|
||||||
"w-8 h-8 rounded-full flex items-center justify-center shadow-sm ring-1 ring-border/50 backdrop-blur-sm",
|
|
||||||
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}>
|
|
||||||
{isUser ? (
|
<div className="flex-1 overflow-hidden min-w-0 max-w-[72ch] pt-1" data-message-index={messageIndex}>
|
||||||
// Estilo específico para mensagem do usuário (mais destaque, fonte maior)
|
{isUser ? (
|
||||||
<div
|
// Estilo específico para mensagem do usuário (mais destaque, fonte maior)
|
||||||
className="text-lg sm:text-xl font-medium tracking-tight text-foreground/90 leading-relaxed break-words whitespace-pre-wrap"
|
<div
|
||||||
dangerouslySetInnerHTML={highlightedContent ? { __html: highlightedContent } : undefined}
|
className="text-lg font-medium text-foreground break-words whitespace-pre-wrap"
|
||||||
>
|
dangerouslySetInnerHTML={highlightedContent ? { __html: highlightedContent } : undefined}
|
||||||
{!highlightedContent && processedContent}
|
>
|
||||||
</div>
|
{!highlightedContent && processedContent}
|
||||||
) : (
|
</div>
|
||||||
// Estilo Assistant
|
) : (
|
||||||
isEmpty && isStreaming ? (
|
// Estilo Assistant
|
||||||
<div className="flex items-center gap-2 text-muted-foreground py-1">
|
isEmpty && isStreaming ? (
|
||||||
<div className="w-2 h-2 bg-primary rounded-full animate-pulse" />
|
<div className="flex items-center gap-2 text-muted-foreground py-1">
|
||||||
<span className="text-sm font-medium">Gerando resposta...</span>
|
<div className="w-2 h-2 bg-primary rounded-full animate-pulse" />
|
||||||
|
<span className="text-sm">Gerando resposta...</span>
|
||||||
|
</div>
|
||||||
|
) : isStreaming ? (
|
||||||
|
// Renderização LEVE durante streaming: texto simples com formatação básica
|
||||||
|
// Evita recálculo de ReactMarkdown e syntax highlight a cada token
|
||||||
|
<div className="max-w-none break-words text-sm text-foreground relative">
|
||||||
|
<div className="whitespace-pre-wrap font-sans">
|
||||||
|
{processedContent}
|
||||||
</div>
|
</div>
|
||||||
) : isStreaming ? (
|
<span className="inline-block w-2 h-4 bg-primary ml-1 animate-pulse rounded-sm align-middle" />
|
||||||
// Renderização de markdown em tempo real durante streaming
|
</div>
|
||||||
<div className={cn(
|
) : (
|
||||||
"prose prose-neutral dark:prose-invert max-w-none break-words leading-7 text-base text-foreground/90",
|
// Renderização COMPLETA quando mensagem finalizada: ReactMarkdown com syntax highlight
|
||||||
"prose-headings:font-semibold prose-headings:tracking-tight prose-h1:text-2xl prose-h2:text-xl prose-h3:text-lg",
|
<div className="max-w-none break-words text-sm text-foreground">
|
||||||
"prose-p:leading-7 prose-li:leading-7",
|
{highlightedContent ? (
|
||||||
"prose-pre:bg-muted/50 prose-pre:border prose-pre:border-border/50 prose-pre:rounded-xl",
|
<div dangerouslySetInnerHTML={{ __html: highlightedContent }} />
|
||||||
"prose-mark:bg-yellow-200/50 prose-mark:dark:bg-yellow-800/50 prose-mark:px-0.5 prose-mark:rounded",
|
) : (
|
||||||
"relative"
|
|
||||||
)}>
|
|
||||||
<ReactMarkdown
|
<ReactMarkdown
|
||||||
remarkPlugins={[remarkGfm]}
|
remarkPlugins={[remarkGfm]}
|
||||||
components={markdownRenderers}
|
components={markdownRenderers}
|
||||||
>
|
>
|
||||||
{markdownContent}
|
{processedContent}
|
||||||
</ReactMarkdown>
|
</ReactMarkdown>
|
||||||
<span className="inline-block w-2 h-4 bg-primary ml-1 animate-pulse rounded-full align-middle" />
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
)
|
||||||
// Renderização COMPLETA quando mensagem finalizada: ReactMarkdown com syntax highlight
|
|
||||||
<div className={cn(
|
|
||||||
"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 ? (
|
|
||||||
<div dangerouslySetInnerHTML={{ __html: highlightedContent }} />
|
|
||||||
) : (
|
|
||||||
<ReactMarkdown
|
|
||||||
remarkPlugins={[remarkGfm]}
|
|
||||||
components={markdownRenderers}
|
|
||||||
>
|
|
||||||
{processedContent}
|
|
||||||
</ReactMarkdown>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{!isUser && !isStreaming && (
|
|
||||||
<div className={cn(
|
|
||||||
"absolute -bottom-8 left-12 flex items-center gap-2 opacity-0 transition-opacity duration-200",
|
|
||||||
"group-hover:opacity-100",
|
|
||||||
selected && "opacity-100"
|
|
||||||
)}>
|
|
||||||
<MessageActions content={message.content} role={message.role} />
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</MessageBackground>
|
</div>
|
||||||
{!isUser && !isStreaming && debugMode && debugData && (
|
|
||||||
<DebugConsole data={debugData} />
|
{!isUser && !isStreaming && (
|
||||||
|
<div className={cn(
|
||||||
|
"absolute -bottom-8 left-12 flex items-center gap-2 opacity-0 transition-opacity duration-150",
|
||||||
|
"group-hover:opacity-100 group-focus-within:opacity-100",
|
||||||
|
selected && "opacity-100"
|
||||||
|
)}>
|
||||||
|
<MessageActions content={message.content} role={message.role} />
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</>
|
</MessageBackground>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,8 +212,7 @@ export const ChatMessage = React.memo(ChatMessageComponent, (prevProps, nextProp
|
|||||||
prevProps.message.role === nextProps.message.role &&
|
prevProps.message.role === nextProps.message.role &&
|
||||||
prevProps.highlightTerm === nextProps.highlightTerm &&
|
prevProps.highlightTerm === nextProps.highlightTerm &&
|
||||||
prevProps.highlightIndex === nextProps.highlightIndex &&
|
prevProps.highlightIndex === nextProps.highlightIndex &&
|
||||||
prevProps.messageIndex === nextProps.messageIndex &&
|
prevProps.messageIndex === nextProps.messageIndex
|
||||||
prevProps.debugData === nextProps.debugData
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -1,521 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState, useMemo } from 'react';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import {
|
|
||||||
ChevronDown,
|
|
||||||
ChevronUp,
|
|
||||||
Copy,
|
|
||||||
Check,
|
|
||||||
Brain,
|
|
||||||
Search,
|
|
||||||
Settings,
|
|
||||||
FileText,
|
|
||||||
Globe,
|
|
||||||
Clock,
|
|
||||||
Database,
|
|
||||||
Code2
|
|
||||||
} from 'lucide-react';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
<<<<<<< HEAD
|
|
||||||
import { Message, ThinkingMessageMetadata } from '@/hooks/use-chat';
|
|
||||||
=======
|
|
||||||
import { Message } from '@/hooks/use-chat';
|
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
import type { DeepResearchState } from '@/hooks/use-deep-research';
|
|
||||||
import type { ScrapedContent } from '@/services/webSearch';
|
|
||||||
|
|
||||||
export interface DebugData {
|
|
||||||
model: string;
|
|
||||||
timestamp: number;
|
|
||||||
latency?: number;
|
|
||||||
systemPrompt: string;
|
|
||||||
userQuery: string;
|
|
||||||
contextUsed: Message[];
|
|
||||||
webResearch?: {
|
|
||||||
queries: string[];
|
|
||||||
enrichedQueries?: {
|
|
||||||
literal: string[];
|
|
||||||
semantic: string[];
|
|
||||||
related: string[];
|
|
||||||
expanded: string[];
|
|
||||||
contextual: string[];
|
|
||||||
};
|
|
||||||
sources: ScrapedContent[];
|
|
||||||
<<<<<<< HEAD
|
|
||||||
sitesResearched?: Array<{
|
|
||||||
url: string;
|
|
||||||
title: string;
|
|
||||||
status: string;
|
|
||||||
source: string;
|
|
||||||
duration?: number;
|
|
||||||
contentLength: number;
|
|
||||||
scrapedAt: number;
|
|
||||||
}>;
|
|
||||||
=======
|
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
logs: Array<{
|
|
||||||
stage: string;
|
|
||||||
timestamp: number;
|
|
||||||
input: string;
|
|
||||||
rawOutput?: string;
|
|
||||||
parsedOutput?: any;
|
|
||||||
error?: string;
|
|
||||||
}>;
|
|
||||||
plan?: string[];
|
|
||||||
knowledgeBase?: Array<{
|
|
||||||
sourceUrl: string;
|
|
||||||
title: string;
|
|
||||||
content: string;
|
|
||||||
}>;
|
|
||||||
<<<<<<< HEAD
|
|
||||||
activeQueries?: Array<{
|
|
||||||
query: string;
|
|
||||||
source: string;
|
|
||||||
round?: number;
|
|
||||||
startedAt: number;
|
|
||||||
}>;
|
|
||||||
activeUrls?: Array<{
|
|
||||||
url: string;
|
|
||||||
title?: string;
|
|
||||||
status: string;
|
|
||||||
source?: string;
|
|
||||||
startedAt: number;
|
|
||||||
duration?: number;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
deepResearchState?: DeepResearchState;
|
|
||||||
thinkingSteps?: ThinkingMessageMetadata[];
|
|
||||||
reasoning?: {
|
|
||||||
steps?: string[];
|
|
||||||
intermediateResults?: any[];
|
|
||||||
};
|
|
||||||
finalResponse: string;
|
|
||||||
rawResponse: string;
|
|
||||||
tokenUsage?: {
|
|
||||||
input: number;
|
|
||||||
output: number;
|
|
||||||
total: number;
|
|
||||||
=======
|
|
||||||
};
|
|
||||||
deepResearchState?: DeepResearchState;
|
|
||||||
finalResponse: string;
|
|
||||||
rawResponse?: string;
|
|
||||||
tokenUsage?: {
|
|
||||||
input: number;
|
|
||||||
output: number;
|
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
interface DebugConsoleProps {
|
|
||||||
data: DebugData;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function DebugConsole({ data }: DebugConsoleProps) {
|
|
||||||
const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set());
|
|
||||||
const [copied, setCopied] = useState(false);
|
|
||||||
|
|
||||||
const toggleSection = (section: string) => {
|
|
||||||
setExpandedSections(prev => {
|
|
||||||
const next = new Set(prev);
|
|
||||||
if (next.has(section)) {
|
|
||||||
next.delete(section);
|
|
||||||
} else {
|
|
||||||
next.add(section);
|
|
||||||
}
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const copyFullDump = async () => {
|
|
||||||
try {
|
|
||||||
await navigator.clipboard.writeText(JSON.stringify(data, null, 2));
|
|
||||||
setCopied(true);
|
|
||||||
setTimeout(() => setCopied(false), 2000);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to copy:', error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatTimestamp = (ts: number) => {
|
|
||||||
return new Date(ts).toLocaleString('pt-BR', {
|
|
||||||
day: '2-digit',
|
|
||||||
month: '2-digit',
|
|
||||||
year: 'numeric',
|
|
||||||
hour: '2-digit',
|
|
||||||
minute: '2-digit',
|
|
||||||
second: '2-digit',
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatDuration = (ms?: number) => {
|
|
||||||
if (!ms) return 'N/A';
|
|
||||||
if (ms < 1000) return `${ms}ms`;
|
|
||||||
return `${(ms / 1000).toFixed(2)}s`;
|
|
||||||
};
|
|
||||||
|
|
||||||
const isExpanded = (section: string) => expandedSections.has(section);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="mt-6 border-t border-border/50 pt-4">
|
|
||||||
<div className="bg-muted/30 rounded-lg border border-border/50 overflow-hidden font-mono">
|
|
||||||
{/* Header Bar */}
|
|
||||||
<div className="bg-muted/50 border-b border-border/50 px-4 py-3 flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-3 flex-wrap">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Code2 className="w-4 h-4 text-muted-foreground" />
|
|
||||||
<span className="text-sm font-semibold text-foreground">Debug Console</span>
|
|
||||||
</div>
|
|
||||||
<Badge variant="outline" className="text-xs font-mono">
|
|
||||||
{data.model || 'N/A'}
|
|
||||||
</Badge>
|
|
||||||
{data.latency !== undefined && (
|
|
||||||
<Badge variant="outline" className="text-xs font-mono">
|
|
||||||
<Clock className="w-3 h-3 mr-1" />
|
|
||||||
{formatDuration(data.latency)}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
{data.tokenUsage && (
|
|
||||||
<Badge variant="outline" className="text-xs font-mono">
|
|
||||||
Tokens: {data.tokenUsage.input}/{data.tokenUsage.output}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={copyFullDump}
|
|
||||||
className="h-7 px-2 text-xs"
|
|
||||||
>
|
|
||||||
{copied ? (
|
|
||||||
<>
|
|
||||||
<Check className="w-3 h-3 mr-1" />
|
|
||||||
Copiado
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Copy className="w-3 h-3 mr-1" />
|
|
||||||
Copiar Dump (JSON)
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Sections */}
|
|
||||||
<div className="divide-y divide-border/50">
|
|
||||||
{/* Section A: Contexto & Memória */}
|
|
||||||
<Section
|
|
||||||
id="context"
|
|
||||||
title="🧠 Contexto & Memória (Input)"
|
|
||||||
icon={<Brain className="w-4 h-4" />}
|
|
||||||
isExpanded={isExpanded('context')}
|
|
||||||
onToggle={() => toggleSection('context')}
|
|
||||||
>
|
|
||||||
<div className="space-y-4 p-4">
|
|
||||||
<div>
|
|
||||||
<h4 className="text-xs font-semibold mb-2 text-muted-foreground uppercase tracking-wide">
|
|
||||||
System Prompt
|
|
||||||
</h4>
|
|
||||||
<pre className="text-xs bg-background/50 p-3 rounded border border-border/30 overflow-x-auto whitespace-pre-wrap break-words">
|
|
||||||
{data.systemPrompt}
|
|
||||||
</pre>
|
|
||||||
<p className="text-[10px] text-muted-foreground mt-1">
|
|
||||||
Injetado em: {formatTimestamp(data.timestamp)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h4 className="text-xs font-semibold mb-2 text-muted-foreground uppercase tracking-wide">
|
|
||||||
Histórico da Sessão ({data.contextUsed.length} mensagens)
|
|
||||||
</h4>
|
|
||||||
<details className="text-xs">
|
|
||||||
<summary className="cursor-pointer text-muted-foreground hover:text-foreground mb-2">
|
|
||||||
Expandir JSON
|
|
||||||
</summary>
|
|
||||||
<pre className="bg-background/50 p-3 rounded border border-border/30 overflow-x-auto">
|
|
||||||
{JSON.stringify(data.contextUsed, null, 2)}
|
|
||||||
</pre>
|
|
||||||
</details>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Section>
|
|
||||||
|
|
||||||
{/* Section B: Deep Research */}
|
|
||||||
{data.webResearch && (
|
|
||||||
<Section
|
|
||||||
id="research"
|
|
||||||
title="🔎 Deep Research (Processamento)"
|
|
||||||
icon={<Search className="w-4 h-4" />}
|
|
||||||
isExpanded={isExpanded('research')}
|
|
||||||
onToggle={() => toggleSection('research')}
|
|
||||||
>
|
|
||||||
<div className="space-y-4 p-4">
|
|
||||||
{/* Pipeline Status */}
|
|
||||||
<div>
|
|
||||||
<h4 className="text-xs font-semibold mb-3 text-muted-foreground uppercase tracking-wide">
|
|
||||||
Status do Pipeline
|
|
||||||
</h4>
|
|
||||||
<div className="space-y-3">
|
|
||||||
{/* Decomposition */}
|
|
||||||
{data.webResearch.plan && data.webResearch.plan.length > 0 && (
|
|
||||||
<div className="border-l-2 border-primary/50 pl-3">
|
|
||||||
<div className="flex items-center gap-2 mb-1">
|
|
||||||
<div className="w-2 h-2 bg-green-500 rounded-full" />
|
|
||||||
<span className="text-xs font-medium">Decomposition</span>
|
|
||||||
</div>
|
|
||||||
<div className="text-xs text-muted-foreground ml-4 space-y-1">
|
|
||||||
{data.webResearch.plan.map((query, idx) => (
|
|
||||||
<div key={idx} className="flex items-start gap-2">
|
|
||||||
<span className="text-muted-foreground/50">{idx + 1}.</span>
|
|
||||||
<span>{query}</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Query Expansion */}
|
|
||||||
{data.webResearch.enrichedQueries && (
|
|
||||||
<div className="border-l-2 border-blue-500/50 pl-3">
|
|
||||||
<div className="flex items-center gap-2 mb-1">
|
|
||||||
<div className="w-2 h-2 bg-blue-500 rounded-full" />
|
|
||||||
<span className="text-xs font-medium">Query Expansion</span>
|
|
||||||
</div>
|
|
||||||
<div className="text-xs text-muted-foreground ml-4 space-y-2">
|
|
||||||
{data.webResearch.queries.map((original, idx) => {
|
|
||||||
const eq = data.webResearch?.enrichedQueries;
|
|
||||||
const allEnriched = eq ? [
|
|
||||||
...(eq.literal || []),
|
|
||||||
...(eq.semantic || []),
|
|
||||||
...(eq.related || []),
|
|
||||||
...(eq.expanded || []),
|
|
||||||
...(eq.contextual || []),
|
|
||||||
] : [];
|
|
||||||
return (
|
|
||||||
<div key={idx} className="space-y-1">
|
|
||||||
<div className="text-muted-foreground/70">
|
|
||||||
<span className="font-medium">Original:</span> {original}
|
|
||||||
</div>
|
|
||||||
{allEnriched.length > 0 && (
|
|
||||||
<div className="text-muted-foreground space-y-1">
|
|
||||||
<span className="font-medium">Enriquecidas ({allEnriched.length}):</span>
|
|
||||||
<div className="ml-2 space-y-0.5">
|
|
||||||
{allEnriched.slice(0, 5).map((q, qIdx) => (
|
|
||||||
<div key={qIdx} className="text-[10px]">• {q}</div>
|
|
||||||
))}
|
|
||||||
{allEnriched.length > 5 && (
|
|
||||||
<div className="text-[10px] text-muted-foreground/70">
|
|
||||||
... e mais {allEnriched.length - 5}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Web Crawling */}
|
|
||||||
{data.webResearch.sources && data.webResearch.sources.length > 0 && (
|
|
||||||
<div className="border-l-2 border-yellow-500/50 pl-3">
|
|
||||||
<div className="flex items-center gap-2 mb-1">
|
|
||||||
<div className="w-2 h-2 bg-yellow-500 rounded-full" />
|
|
||||||
<span className="text-xs font-medium">
|
|
||||||
Web Crawling ({data.webResearch.sources.length} fontes)
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="text-xs text-muted-foreground ml-4 space-y-2 max-h-60 overflow-y-auto">
|
|
||||||
{data.webResearch.sources.map((source, idx) => (
|
|
||||||
<div key={idx} className="flex items-start gap-2 p-2 bg-background/30 rounded border border-border/20">
|
|
||||||
<div className="flex-shrink-0 mt-0.5">
|
|
||||||
{source.content && source.content.length > 0 ? (
|
|
||||||
<span className="text-green-500">✓</span>
|
|
||||||
) : (
|
|
||||||
<span className="text-red-500">✗</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center gap-2 mb-1">
|
|
||||||
<span className="font-medium truncate">{source.title || source.url}</span>
|
|
||||||
{source.cached && (
|
|
||||||
<Badge variant="outline" className="text-[10px] px-1">
|
|
||||||
Cached
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<a
|
|
||||||
href={source.url}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="text-[10px] text-primary hover:underline truncate block"
|
|
||||||
>
|
|
||||||
{source.url}
|
|
||||||
</a>
|
|
||||||
{source.content && (
|
|
||||||
<p className="text-[10px] text-muted-foreground mt-1 line-clamp-2">
|
|
||||||
{source.content.substring(0, 150)}...
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Knowledge Base */}
|
|
||||||
{data.webResearch.knowledgeBase && data.webResearch.knowledgeBase.length > 0 && (
|
|
||||||
<div className="border-l-2 border-purple-500/50 pl-3">
|
|
||||||
<div className="flex items-center gap-2 mb-1">
|
|
||||||
<div className="w-2 h-2 bg-purple-500 rounded-full" />
|
|
||||||
<span className="text-xs font-medium">Knowledge Base</span>
|
|
||||||
</div>
|
|
||||||
<div className="text-xs text-muted-foreground ml-4">
|
|
||||||
<Badge variant="secondary" className="text-[10px]">
|
|
||||||
{data.webResearch.knowledgeBase.length} chunks extraídos
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Research Logs */}
|
|
||||||
{data.webResearch.logs && data.webResearch.logs.length > 0 && (
|
|
||||||
<div>
|
|
||||||
<h4 className="text-xs font-semibold mb-2 text-muted-foreground uppercase tracking-wide">
|
|
||||||
Logs Internos ({data.webResearch.logs.length} entradas)
|
|
||||||
</h4>
|
|
||||||
<div className="space-y-2 max-h-60 overflow-y-auto">
|
|
||||||
{data.webResearch.logs.map((log, idx) => (
|
|
||||||
<div key={idx} className="text-xs bg-background/30 p-2 rounded border border-border/20">
|
|
||||||
<div className="flex items-center gap-2 mb-1">
|
|
||||||
<Badge variant="outline" className="text-[10px] px-1">
|
|
||||||
{log.stage}
|
|
||||||
</Badge>
|
|
||||||
<span className="text-[10px] text-muted-foreground">
|
|
||||||
{formatTimestamp(log.timestamp)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="text-muted-foreground">
|
|
||||||
<div className="mb-1">
|
|
||||||
<span className="font-medium">Input:</span> {log.input}
|
|
||||||
</div>
|
|
||||||
{log.rawOutput && (
|
|
||||||
<div className="mb-1">
|
|
||||||
<span className="font-medium">Output:</span>{' '}
|
|
||||||
<span className="text-[10px]">{log.rawOutput.substring(0, 200)}...</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{log.error && (
|
|
||||||
<div className="text-red-500">
|
|
||||||
<span className="font-medium">Erro:</span> {log.error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Section>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Section C: Dados Processados */}
|
|
||||||
{data.deepResearchState && (
|
|
||||||
<Section
|
|
||||||
id="processed"
|
|
||||||
title="⚙️ Dados Processados (Raciocínio)"
|
|
||||||
icon={<Settings className="w-4 h-4" />}
|
|
||||||
isExpanded={isExpanded('processed')}
|
|
||||||
onToggle={() => toggleSection('processed')}
|
|
||||||
>
|
|
||||||
<div className="space-y-4 p-4">
|
|
||||||
<div>
|
|
||||||
<h4 className="text-xs font-semibold mb-2 text-muted-foreground uppercase tracking-wide">
|
|
||||||
Estado do Deep Research
|
|
||||||
</h4>
|
|
||||||
<div className="text-xs space-y-2">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-muted-foreground">Step:</span>
|
|
||||||
<Badge variant="outline">{data.deepResearchState.step}</Badge>
|
|
||||||
</div>
|
|
||||||
{data.deepResearchState.validationReport && (
|
|
||||||
<div>
|
|
||||||
<span className="text-muted-foreground font-medium">Validation Report:</span>
|
|
||||||
<pre className="mt-1 bg-background/50 p-2 rounded border border-border/30 overflow-x-auto whitespace-pre-wrap break-words text-[10px]">
|
|
||||||
{data.deepResearchState.validationReport}
|
|
||||||
</pre>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{data.deepResearchState.error && (
|
|
||||||
<div className="text-red-500">
|
|
||||||
<span className="font-medium">Erro:</span> {data.deepResearchState.error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Section>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Section D: Resposta Raw */}
|
|
||||||
<Section
|
|
||||||
id="response"
|
|
||||||
title="📤 Resposta Raw (Output)"
|
|
||||||
icon={<FileText className="w-4 h-4" />}
|
|
||||||
isExpanded={isExpanded('response')}
|
|
||||||
onToggle={() => toggleSection('response')}
|
|
||||||
>
|
|
||||||
<div className="p-4">
|
|
||||||
<pre className="text-xs bg-background/50 p-3 rounded border border-border/30 overflow-x-auto whitespace-pre-wrap break-words max-h-96 overflow-y-auto">
|
|
||||||
{data.rawResponse || data.finalResponse}
|
|
||||||
</pre>
|
|
||||||
</div>
|
|
||||||
</Section>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SectionProps {
|
|
||||||
id: string;
|
|
||||||
title: string;
|
|
||||||
icon: React.ReactNode;
|
|
||||||
isExpanded: boolean;
|
|
||||||
onToggle: () => void;
|
|
||||||
children: React.ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
function Section({ id, title, icon, isExpanded, onToggle, children }: SectionProps) {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<button
|
|
||||||
onClick={onToggle}
|
|
||||||
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/40 transition-colors text-left"
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
{icon}
|
|
||||||
<span className="text-sm font-medium">{title}</span>
|
|
||||||
</div>
|
|
||||||
{isExpanded ? (
|
|
||||||
<ChevronUp className="w-4 h-4 text-muted-foreground" />
|
|
||||||
) : (
|
|
||||||
<ChevronDown className="w-4 h-4 text-muted-foreground" />
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
{isExpanded && (
|
|
||||||
<div className="bg-background/20">
|
|
||||||
{children}
|
|
||||||
</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}
|
||||||
|
|||||||
@@ -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" : "";
|
||||||
|
|
||||||
|
|||||||
@@ -18,8 +18,6 @@ import {
|
|||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import type { ThinkingMessageMetadata } from '@/hooks/use-chat';
|
import type { ThinkingMessageMetadata } from '@/hooks/use-chat';
|
||||||
import { SearchQueriesMonitor } from './search-queries-monitor';
|
|
||||||
import { ScrapingUrlsMonitor } from './scraping-urls-monitor';
|
|
||||||
|
|
||||||
interface MessageStepThinkingProps {
|
interface MessageStepThinkingProps {
|
||||||
metadata: ThinkingMessageMetadata;
|
metadata: ThinkingMessageMetadata;
|
||||||
@@ -34,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" />;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -63,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>
|
||||||
)}
|
)}
|
||||||
@@ -97,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>
|
||||||
@@ -107,46 +106,27 @@ 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-4 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>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Monitoramento em Tempo Real - Queries */}
|
|
||||||
{metadata.activeQueries && metadata.activeQueries.length > 0 && (
|
|
||||||
<div className="pt-2 border-t border-muted/30">
|
|
||||||
<SearchQueriesMonitor queries={metadata.activeQueries} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Monitoramento em Tempo Real - URLs */}
|
|
||||||
{metadata.activeUrls && metadata.activeUrls.length > 0 && (
|
|
||||||
<div className="pt-2 border-t border-muted/30">
|
|
||||||
<ScrapingUrlsMonitor urls={metadata.activeUrls} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{metadata.sources && metadata.sources.length > 0 && (
|
{metadata.sources && metadata.sources.length > 0 && (
|
||||||
<div className="pt-2 border-t border-muted/30">
|
<div className="flex flex-wrap gap-2 pt-1">
|
||||||
<div className="text-xs font-medium text-muted-foreground mb-2">
|
|
||||||
Fontes Encontradas ({metadata.sources.length})
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
{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>
|
||||||
))}
|
))}
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{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>
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -1,317 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import * as React from 'react';
|
|
||||||
import { Check, ChevronsUpDown, Search, DownloadCloud, Cpu, Loader2 } from 'lucide-react';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import {
|
|
||||||
Popover,
|
|
||||||
PopoverContent,
|
|
||||||
PopoverTrigger,
|
|
||||||
} from '@/components/ui/popover';
|
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
|
||||||
import { useModelSelection } from '@/hooks/use-model-selection';
|
|
||||||
import { useDownloadContext } from '@/contexts/download-context';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import { useToast } from '@/hooks/use-toast';
|
|
||||||
|
|
||||||
export function ModelSelector() {
|
|
||||||
const [open, setOpen] = React.useState(false);
|
|
||||||
const [searchQuery, setSearchQuery] = React.useState('');
|
|
||||||
const { myModels, availableModels, selectedModel, setSelectedModel, installedVariantsByFamily, refreshModels } = useModelSelection();
|
|
||||||
const { startDownload, state: downloadState } = useDownloadContext();
|
|
||||||
const { toast } = useToast();
|
|
||||||
|
|
||||||
// Track selected variant for each model in the catalog
|
|
||||||
const [selectedVariants, setSelectedVariants] = React.useState<Record<string, string>>({});
|
|
||||||
|
|
||||||
const handleDownload = async (e: React.MouseEvent, modelName: string) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
try {
|
|
||||||
await startDownload(modelName);
|
|
||||||
toast({
|
|
||||||
title: "Download Iniciado",
|
|
||||||
description: `Baixando ${modelName}...`,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
toast({
|
|
||||||
title: "Erro",
|
|
||||||
description: "Falha ao iniciar download.",
|
|
||||||
variant: "destructive",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSmartDownload = async () => {
|
|
||||||
const term = searchQuery.trim();
|
|
||||||
if (!term) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
await startDownload(term);
|
|
||||||
setOpen(false);
|
|
||||||
setSearchQuery("");
|
|
||||||
toast({
|
|
||||||
title: "Download Iniciado",
|
|
||||||
description: `Baixando ${term} da biblioteca Ollama...`,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
toast({
|
|
||||||
title: "Erro",
|
|
||||||
description: "Falha ao iniciar download.",
|
|
||||||
variant: "destructive",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
React.useEffect(() => {
|
|
||||||
if (downloadState?.isSuccess) {
|
|
||||||
refreshModels();
|
|
||||||
}
|
|
||||||
}, [downloadState?.isSuccess, refreshModels]);
|
|
||||||
|
|
||||||
const filteredMyModels = React.useMemo(() => {
|
|
||||||
if (!searchQuery) return myModels;
|
|
||||||
return myModels.filter(m =>
|
|
||||||
m.model.toLowerCase().includes(searchQuery.toLowerCase())
|
|
||||||
);
|
|
||||||
}, [myModels, searchQuery]);
|
|
||||||
|
|
||||||
const filteredAvailableModels = React.useMemo(() => {
|
|
||||||
if (!searchQuery) return availableModels;
|
|
||||||
return availableModels.filter(m =>
|
|
||||||
m.model.toLowerCase().includes(searchQuery.toLowerCase())
|
|
||||||
);
|
|
||||||
}, [availableModels, searchQuery]);
|
|
||||||
|
|
||||||
// Helper to check if a model is currently selected (partial match for variants)
|
|
||||||
const isSelected = (modelName: string) => {
|
|
||||||
if (!selectedModel) return false;
|
|
||||||
return selectedModel.startsWith(modelName) || selectedModel === modelName;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Helper to extract tag/parameters from model name
|
|
||||||
const getVariantDisplay = (name: string) => {
|
|
||||||
if (name.includes(':')) {
|
|
||||||
return name.split(':')[1];
|
|
||||||
}
|
|
||||||
return 'latest';
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Popover open={open} onOpenChange={setOpen}>
|
|
||||||
<PopoverTrigger asChild>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
role="combobox"
|
|
||||||
aria-expanded={open}
|
|
||||||
className="w-[260px] justify-between"
|
|
||||||
>
|
|
||||||
{selectedModel ? (
|
|
||||||
<span className="flex items-center gap-2 truncate">
|
|
||||||
<Cpu className="w-4 h-4 text-muted-foreground shrink-0" />
|
|
||||||
<span className="truncate">{selectedModel}</span>
|
|
||||||
</span>
|
|
||||||
) : (
|
|
||||||
"Selecione um modelo..."
|
|
||||||
)}
|
|
||||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
|
||||||
</Button>
|
|
||||||
</PopoverTrigger>
|
|
||||||
<PopoverContent className="w-[400px] p-0" align="start">
|
|
||||||
<div className="flex flex-col">
|
|
||||||
{/* Search Input */}
|
|
||||||
<div className="flex items-center border-b border-border/50 px-3 bg-muted/30">
|
|
||||||
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
|
|
||||||
<input
|
|
||||||
className="flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50"
|
|
||||||
placeholder="Buscar modelos..."
|
|
||||||
value={searchQuery}
|
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === 'Enter' && searchQuery && filteredAvailableModels.length === 0) {
|
|
||||||
handleSmartDownload();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Tabs defaultValue="installed" className="w-full">
|
|
||||||
<TabsList className="w-full rounded-none border-b bg-transparent p-0">
|
|
||||||
<TabsTrigger
|
|
||||||
value="installed"
|
|
||||||
className="flex-1 rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent h-10"
|
|
||||||
>
|
|
||||||
Instalados
|
|
||||||
</TabsTrigger>
|
|
||||||
<TabsTrigger
|
|
||||||
value="available"
|
|
||||||
className="flex-1 rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent h-10"
|
|
||||||
>
|
|
||||||
Catálogo
|
|
||||||
</TabsTrigger>
|
|
||||||
</TabsList>
|
|
||||||
|
|
||||||
<TabsContent value="installed" className="m-0 max-h-[400px] overflow-y-auto p-2">
|
|
||||||
{filteredMyModels.length === 0 ? (
|
|
||||||
<div className="py-8 text-center text-sm text-muted-foreground">
|
|
||||||
{searchQuery ? (
|
|
||||||
<span>Nenhum modelo instalado encontrado.</span>
|
|
||||||
) : (
|
|
||||||
<span>Nenhum modelo instalado.</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="flex flex-col gap-2">
|
|
||||||
{filteredMyModels.map((modelDef) => {
|
|
||||||
const family = modelDef.model;
|
|
||||||
const installedTags = installedVariantsByFamily[family] || [];
|
|
||||||
const isFamilySelected = selectedModel ? (selectedModel === family || selectedModel.startsWith(family + ":")) : false;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={family}
|
|
||||||
className="relative flex flex-col rounded-md border border-transparent hover:border-border/50 bg-card/50 hover:bg-accent/30 p-3 text-sm transition-all"
|
|
||||||
>
|
|
||||||
<div className="flex items-start justify-between w-full mb-2">
|
|
||||||
<div className="flex flex-col gap-0.5 overflow-hidden pr-2">
|
|
||||||
<span className="font-bold text-base truncate flex items-center gap-2">
|
|
||||||
{modelDef.model}
|
|
||||||
{isFamilySelected && (
|
|
||||||
<Check className="h-3 w-3 text-primary animate-in fade-in zoom-in" />
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
<span className="text-xs text-muted-foreground line-clamp-2" title={modelDef.description}>
|
|
||||||
{modelDef.description}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-wrap gap-1.5 mt-1">
|
|
||||||
{installedTags.map((fullTag) => {
|
|
||||||
const tag = getVariantDisplay(fullTag);
|
|
||||||
const isExactSelected = selectedModel === fullTag;
|
|
||||||
// Find variant def for size info if available
|
|
||||||
const variantDef = modelDef.variants.find(v => v.name === fullTag);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Badge
|
|
||||||
key={fullTag}
|
|
||||||
variant="outline"
|
|
||||||
className={cn(
|
|
||||||
"cursor-pointer text-[10px] px-2 h-5 transition-all border-transparent",
|
|
||||||
isExactSelected
|
|
||||||
? "bg-foreground text-background hover:bg-foreground/90"
|
|
||||||
: "bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground"
|
|
||||||
)}
|
|
||||||
title={variantDef ? `Tamanho: ${variantDef.size}` : undefined}
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
setSelectedModel(fullTag);
|
|
||||||
setOpen(false);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{tag}
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</TabsContent>
|
|
||||||
|
|
||||||
<TabsContent value="available" className="m-0 max-h-[400px] overflow-y-auto p-2">
|
|
||||||
{filteredAvailableModels.length === 0 ? (
|
|
||||||
<div className="py-6 text-center text-sm">
|
|
||||||
{searchQuery ? (
|
|
||||||
<div className="flex flex-col items-center gap-2">
|
|
||||||
<p className="text-muted-foreground">Modelo não encontrado no catálogo.</p>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
className="h-auto py-2 px-4 border-dashed border-zinc-500/50 hover:border-primary hover:bg-primary/10"
|
|
||||||
onClick={handleSmartDownload}
|
|
||||||
>
|
|
||||||
<DownloadCloud className="mr-2 h-4 w-4" />
|
|
||||||
<span>Baixar <span className="font-bold ml-1">{searchQuery}</span></span>
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<span className="text-muted-foreground">Nenhum modelo encontrado.</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="flex flex-col gap-2">
|
|
||||||
{filteredAvailableModels.map((modelDef) => {
|
|
||||||
// Determine active variant for this item
|
|
||||||
const activeVariantName = selectedVariants[modelDef.model] || modelDef.variants[0]?.name;
|
|
||||||
const activeVariant = modelDef.variants.find(v => v.name === activeVariantName) || modelDef.variants[0];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={modelDef.model}
|
|
||||||
className="relative flex flex-col rounded-md border border-transparent hover:border-border/50 bg-card/50 hover:bg-accent/30 p-3 text-sm transition-all"
|
|
||||||
>
|
|
||||||
<div className="flex items-start justify-between w-full mb-2">
|
|
||||||
<div className="flex flex-col gap-0.5 overflow-hidden pr-2">
|
|
||||||
<span className="font-bold text-base truncate">{modelDef.model}</span>
|
|
||||||
<span className="text-xs text-muted-foreground line-clamp-2" title={modelDef.description}>
|
|
||||||
{modelDef.description}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground"
|
|
||||||
onClick={(e) => handleDownload(e, activeVariant.name)}
|
|
||||||
disabled={downloadState.isDownloading && downloadState.currentModel === activeVariant.name}
|
|
||||||
title={`Baixar ${activeVariant.name}`}
|
|
||||||
>
|
|
||||||
{downloadState.isDownloading && downloadState.currentModel === activeVariant.name ? (
|
|
||||||
<Loader2 className="h-4 w-4 animate-spin" />
|
|
||||||
) : (
|
|
||||||
<DownloadCloud className="h-4 w-4" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Variants Pills */}
|
|
||||||
<div className="flex flex-wrap gap-1.5 mt-1">
|
|
||||||
{modelDef.variants.map((variant) => {
|
|
||||||
const isVariantSelected = activeVariant.name === variant.name;
|
|
||||||
return (
|
|
||||||
<Badge
|
|
||||||
key={variant.name}
|
|
||||||
variant="outline"
|
|
||||||
className={cn(
|
|
||||||
"cursor-pointer text-[10px] px-2 h-5 transition-all border-transparent",
|
|
||||||
isVariantSelected
|
|
||||||
? "bg-foreground text-background hover:bg-foreground/90"
|
|
||||||
: "bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground"
|
|
||||||
)}
|
|
||||||
title={`Tamanho em disco: ${variant.size}`}
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
setSelectedVariants(prev => ({
|
|
||||||
...prev,
|
|
||||||
[modelDef.model]: variant.name
|
|
||||||
}));
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{getVariantDisplay(variant.name)}
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</TabsContent>
|
|
||||||
</Tabs>
|
|
||||||
</div>
|
|
||||||
</PopoverContent>
|
|
||||||
</Popover>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -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}
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -1,107 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { Loader2, CheckCircle2, XCircle, ExternalLink, Globe } from 'lucide-react';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import type { ActiveUrl } from '@/hooks/use-web-search-events';
|
|
||||||
|
|
||||||
interface ScrapingUrlsMonitorProps {
|
|
||||||
urls: ActiveUrl[];
|
|
||||||
className?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ScrapingUrlsMonitor({ urls, className }: ScrapingUrlsMonitorProps) {
|
|
||||||
if (urls.length === 0) return null;
|
|
||||||
|
|
||||||
const getFaviconUrl = (url: string): string => {
|
|
||||||
try {
|
|
||||||
const domain = new URL(url).hostname;
|
|
||||||
return `https://www.google.com/s2/favicons?domain=${domain}&sz=16`;
|
|
||||||
} catch {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getStatusIcon = (status: ActiveUrl['status']) => {
|
|
||||||
switch (status) {
|
|
||||||
case 'started':
|
|
||||||
return <Loader2 className="w-3 h-3 animate-spin text-primary" />;
|
|
||||||
case 'completed':
|
|
||||||
case 'cached':
|
|
||||||
return <CheckCircle2 className="w-3 h-3 text-green-500" />;
|
|
||||||
case 'failed':
|
|
||||||
return <XCircle className="w-3 h-3 text-red-500" />;
|
|
||||||
default:
|
|
||||||
return <Globe className="w-3 h-3 text-muted-foreground" />;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getSourceBadge = (source?: string) => {
|
|
||||||
if (!source) return null;
|
|
||||||
|
|
||||||
const colors: Record<string, string> = {
|
|
||||||
static: 'bg-blue-500/10 text-blue-600 border-blue-500/20',
|
|
||||||
nodriver: 'bg-purple-500/10 text-purple-600 border-purple-500/20',
|
|
||||||
playwright: 'bg-orange-500/10 text-orange-600 border-orange-500/20',
|
|
||||||
cached: 'bg-gray-500/10 text-gray-600 border-gray-500/20',
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Badge variant="outline" className={cn('text-xs', colors[source] || 'bg-muted')}>
|
|
||||||
{source}
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={cn('space-y-2', className)}>
|
|
||||||
<div className="text-xs font-medium text-muted-foreground mb-2">
|
|
||||||
Sites Sendo Acessados ({urls.length})
|
|
||||||
</div>
|
|
||||||
{urls.map((url, idx) => (
|
|
||||||
<div
|
|
||||||
key={`${url.url}-${idx}`}
|
|
||||||
className="flex items-start gap-2 p-2 rounded-md border bg-muted/30 hover:bg-muted/50 transition-colors"
|
|
||||||
>
|
|
||||||
<div className="flex-shrink-0 mt-0.5">
|
|
||||||
{getStatusIcon(url.status)}
|
|
||||||
</div>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-start gap-2">
|
|
||||||
<img
|
|
||||||
src={getFaviconUrl(url.url)}
|
|
||||||
alt=""
|
|
||||||
className="w-4 h-4 rounded mt-0.5 flex-shrink-0"
|
|
||||||
onError={(e) => {
|
|
||||||
(e.target as HTMLImageElement).style.display = 'none';
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
|
||||||
<a
|
|
||||||
href={url.url}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="text-xs font-medium text-primary hover:underline line-clamp-1 flex items-center gap-1"
|
|
||||||
>
|
|
||||||
{url.title || url.url}
|
|
||||||
<ExternalLink className="w-3 h-3 flex-shrink-0" />
|
|
||||||
</a>
|
|
||||||
{getSourceBadge(url.source)}
|
|
||||||
{url.duration && (
|
|
||||||
<span className="text-xs text-muted-foreground">
|
|
||||||
{url.duration}ms
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-muted-foreground truncate mt-0.5">
|
|
||||||
{url.url}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</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,70 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { Loader2, CheckCircle2, Globe, Search } from 'lucide-react';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import type { ActiveQuery } from '@/hooks/use-web-search-events';
|
|
||||||
|
|
||||||
interface SearchQueriesMonitorProps {
|
|
||||||
queries: ActiveQuery[];
|
|
||||||
className?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SearchQueriesMonitor({ queries, className }: SearchQueriesMonitorProps) {
|
|
||||||
if (queries.length === 0) return null;
|
|
||||||
|
|
||||||
const getSourceColor = (source: string) => {
|
|
||||||
switch (source) {
|
|
||||||
case 'brave':
|
|
||||||
return 'bg-blue-500/10 text-blue-600 border-blue-500/20';
|
|
||||||
case 'searxng':
|
|
||||||
return 'bg-green-500/10 text-green-600 border-green-500/20';
|
|
||||||
case 'duckduckgo':
|
|
||||||
return 'bg-yellow-500/10 text-yellow-600 border-yellow-500/20';
|
|
||||||
default:
|
|
||||||
return 'bg-muted text-muted-foreground border-muted';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getSourceLabel = (source: string) => {
|
|
||||||
switch (source) {
|
|
||||||
case 'brave':
|
|
||||||
return 'Brave';
|
|
||||||
case 'searxng':
|
|
||||||
return 'SearXNG';
|
|
||||||
case 'duckduckgo':
|
|
||||||
return 'DuckDuckGo';
|
|
||||||
default:
|
|
||||||
return source;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={cn('space-y-2', className)}>
|
|
||||||
<div className="text-xs font-medium text-muted-foreground mb-2">
|
|
||||||
Consultas Ativas ({queries.length})
|
|
||||||
</div>
|
|
||||||
{queries.map((query, idx) => (
|
|
||||||
<div
|
|
||||||
key={`${query.query}-${query.source}-${idx}`}
|
|
||||||
className="flex items-center gap-2 p-2 rounded-md border bg-muted/30 hover:bg-muted/50 transition-colors"
|
|
||||||
>
|
|
||||||
<Loader2 className="w-3 h-3 animate-spin text-primary flex-shrink-0" />
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
|
||||||
<span className="text-xs truncate">{query.query}</span>
|
|
||||||
<Badge variant="outline" className={cn('text-xs', getSourceColor(query.source))}>
|
|
||||||
{getSourceLabel(query.source)}
|
|
||||||
</Badge>
|
|
||||||
{query.round && (
|
|
||||||
<Badge variant="outline" className="text-xs">
|
|
||||||
Round {query.round}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -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" />
|
||||||
|
|||||||
@@ -1,80 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useDownloadContext } from '@/contexts/download-context';
|
|
||||||
import { Progress } from '@/components/ui/progress';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { X } from 'lucide-react';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
|
|
||||||
export function GlobalDownloadStatusBar() {
|
|
||||||
const { state, cancelDownload } = useDownloadContext();
|
|
||||||
|
|
||||||
if (!state.isDownloading) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { progress, currentModel, isCancelling } = state;
|
|
||||||
const modelDisplayName = currentModel || 'Modelo';
|
|
||||||
const percent = progress.percent ?? 0;
|
|
||||||
const hasSizeInfo = progress.totalBytes > 0 && progress.downloadedBytes > 0;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'fixed bottom-0 left-0 right-0 z-50',
|
|
||||||
'bg-background/95 backdrop-blur-sm border-t border-border',
|
|
||||||
'shadow-lg',
|
|
||||||
'animate-in slide-in-from-bottom duration-300',
|
|
||||||
'transition-all'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="container mx-auto px-4 py-3">
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center justify-between mb-1.5">
|
|
||||||
<span className="text-sm font-medium text-foreground truncate">
|
|
||||||
{isCancelling ? (
|
|
||||||
'Cancelando download...'
|
|
||||||
) : (
|
|
||||||
`Baixando Modelo: ${modelDisplayName} (${percent}%)`
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
{progress.speed && !isCancelling && (
|
|
||||||
<span className="text-xs text-muted-foreground font-mono ml-2 shrink-0">
|
|
||||||
{progress.speed}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Progress
|
|
||||||
value={percent}
|
|
||||||
className="h-1.5 mb-1.5"
|
|
||||||
/>
|
|
||||||
|
|
||||||
{hasSizeInfo && (
|
|
||||||
<div className="flex justify-between items-center text-[10px] text-muted-foreground/70 uppercase font-medium tracking-wider">
|
|
||||||
<span>
|
|
||||||
{progress.downloadedFormatted} / {progress.totalFormatted}
|
|
||||||
</span>
|
|
||||||
{progress.status && (
|
|
||||||
<span className="normal-case">{progress.status}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon-sm"
|
|
||||||
onClick={cancelDownload}
|
|
||||||
disabled={isCancelling}
|
|
||||||
className="shrink-0 h-8 w-8"
|
|
||||||
aria-label="Cancelar download"
|
|
||||||
>
|
|
||||||
<X className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useEffect } from 'react';
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
|
||||||
|
|
||||||
export function KeyboardShortcuts() {
|
|
||||||
useEffect(() => {
|
|
||||||
const handleKeyDown = (e: KeyboardEvent) => {
|
|
||||||
// CTRL+SHIFT+D para abrir devtools
|
|
||||||
if (e.ctrlKey && e.shiftKey && (e.key === 'd' || e.key === 'D')) {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
invoke('toggle_devtools').catch(console.error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bloquear F5 (refresh)
|
|
||||||
if (e.key === 'F5') {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bloquear CTRL+R (refresh)
|
|
||||||
if (e.ctrlKey && (e.key === 'r' || e.key === 'R') && !e.shiftKey && !e.altKey) {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bloquear CTRL+SHIFT+R (hard refresh)
|
|
||||||
if (e.ctrlKey && e.shiftKey && (e.key === 'r' || e.key === 'R')) {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bloquear CTRL+SHIFT+I (devtools)
|
|
||||||
if (e.ctrlKey && e.shiftKey && (e.key === 'i' || e.key === 'I')) {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bloquear CTRL+SHIFT+J (console)
|
|
||||||
if (e.ctrlKey && e.shiftKey && (e.key === 'j' || e.key === 'J')) {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bloquear CTRL+U (view source)
|
|
||||||
if (e.ctrlKey && (e.key === 'u' || e.key === 'U') && !e.shiftKey && !e.altKey) {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bloquear CTRL+SHIFT+DEL (clear storage)
|
|
||||||
if (e.ctrlKey && e.shiftKey && e.key === 'Delete') {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bloquear CTRL+W (fechar aba - mas permitir fechar janela com o comportamento customizado do Tauri)
|
|
||||||
// Não bloqueamos CTRL+W porque o Tauri já trata isso no on_window_event
|
|
||||||
|
|
||||||
// Bloquear CTRL+N (nova janela)
|
|
||||||
if (e.ctrlKey && (e.key === 'n' || e.key === 'N') && !e.shiftKey && !e.altKey) {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bloquear CTRL+SHIFT+N (nova janela anônima)
|
|
||||||
if (e.ctrlKey && e.shiftKey && (e.key === 'n' || e.key === 'N')) {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bloquear CTRL+T (nova aba)
|
|
||||||
if (e.ctrlKey && (e.key === 't' || e.key === 'T') && !e.shiftKey && !e.altKey) {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Adicionar listener com capture para interceptar antes de outros handlers
|
|
||||||
window.addEventListener('keydown', handleKeyDown, true);
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener('keydown', handleKeyDown, true);
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -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"
|
||||||
@@ -87,7 +87,10 @@ export function InstallModal({ open, onCheckAgain }: InstallModalProps) {
|
|||||||
const handleInstall = async () => {
|
const handleInstall = async () => {
|
||||||
try {
|
try {
|
||||||
await downloadState.handleInstall();
|
await downloadState.handleInstall();
|
||||||
// Toast será mostrado automaticamente via eventos de progresso
|
toast({
|
||||||
|
title: 'Instalador iniciado',
|
||||||
|
description: 'O instalador foi aberto. Siga as instruções na tela.',
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast({
|
toast({
|
||||||
title: 'Erro ao executar instalador',
|
title: 'Erro ao executar instalador',
|
||||||
@@ -141,10 +144,8 @@ export function InstallModal({ open, onCheckAgain }: InstallModalProps) {
|
|||||||
const isActive = activeTab === os;
|
const isActive = activeTab === os;
|
||||||
const isDownloading = downloadState.isDownloading && isActive;
|
const isDownloading = downloadState.isDownloading && isActive;
|
||||||
const hasDownloaded = downloadState.filePath !== null && isActive;
|
const hasDownloaded = downloadState.filePath !== null && isActive;
|
||||||
const isInstalling = downloadState.isInstalling && isActive;
|
|
||||||
const installStatus = downloadState.installStatus;
|
|
||||||
|
|
||||||
if (!isDownloading && !hasDownloaded && !isInstalling) {
|
if (!isDownloading && !hasDownloaded) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,39 +162,15 @@ export function InstallModal({ open, onCheckAgain }: InstallModalProps) {
|
|||||||
<Progress value={downloadState.downloadProgress} className="h-2" />
|
<Progress value={downloadState.downloadProgress} className="h-2" />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{isInstalling && (
|
{hasDownloaded && !isDownloading && (
|
||||||
<>
|
<div className="flex items-start gap-2 p-3 border border-success/30 bg-success/10 rounded-md">
|
||||||
<div className="flex items-center justify-between text-sm">
|
<CheckCircle2 className="h-4 w-4 mt-0.5 shrink-0 text-success" />
|
||||||
<span className="text-muted-foreground">
|
|
||||||
{installStatus || 'Instalando...'}
|
|
||||||
</span>
|
|
||||||
<Loader2 className="h-4 w-4 animate-spin text-primary" />
|
|
||||||
</div>
|
|
||||||
<Progress value={undefined} className="h-2" />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{hasDownloaded && !isDownloading && !isInstalling && (
|
|
||||||
<div className="flex items-start gap-2 p-3 bg-green-50 dark:bg-green-950/20 rounded-md">
|
|
||||||
<CheckCircle2 className="h-4 w-4 mt-0.5 text-green-600 dark:text-green-400" />
|
|
||||||
<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 automática.
|
Clique em "Instalar Ollama" para iniciar a instalação.
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{downloadState.isInstalled && !isInstalling && (
|
|
||||||
<div className="flex items-start gap-2 p-3 bg-green-50 dark:bg-green-950/20 rounded-md">
|
|
||||||
<CheckCircle2 className="h-4 w-4 mt-0.5 text-green-600 dark:text-green-400" />
|
|
||||||
<div className="text-sm flex-1">
|
|
||||||
<p className="font-medium text-green-900 dark:text-green-100">
|
|
||||||
Instalação concluída!
|
|
||||||
</p>
|
|
||||||
<p className="text-green-700 dark:text-green-300">
|
|
||||||
{installStatus || 'Ollama foi instalado com sucesso.'}
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -206,9 +183,7 @@ export function InstallModal({ open, onCheckAgain }: InstallModalProps) {
|
|||||||
<Dialog open={open}>
|
<Dialog open={open}>
|
||||||
<DialogContent className="sm:max-w-[600px]">
|
<DialogContent className="sm:max-w-[600px]">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle data-tauri-drag-region className="cursor-move select-none">
|
<DialogTitle>Ollama não encontrado</DialogTitle>
|
||||||
Ollama não encontrado
|
|
||||||
</DialogTitle>
|
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
Para usar o OllaHub, você precisa ter o Ollama instalado no seu sistema.
|
Para usar o OllaHub, você precisa ter o Ollama instalado no seu sistema.
|
||||||
Baixe e instale o Ollama usando os passos abaixo.
|
Baixe e instale o Ollama usando os passos abaixo.
|
||||||
@@ -228,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>
|
||||||
@@ -249,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">
|
||||||
@@ -259,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>
|
||||||
@@ -272,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>
|
||||||
@@ -287,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>
|
||||||
@@ -299,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>
|
||||||
@@ -308,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" />
|
||||||
@@ -67,11 +68,3 @@ export function WelcomeNotification() {
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -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>
|
||||||
)}
|
)}
|
||||||
@@ -269,11 +269,3 @@ export function GpuDashboard({ gpuId, pollInterval = 2000 }: GpuDashboardProps)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -43,33 +43,11 @@ export function HardwareDashboard() {
|
|||||||
|
|
||||||
if (isLoading || !stats) {
|
if (isLoading || !stats) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<Card>
|
||||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
<CardContent className="py-8 text-center text-muted-foreground">
|
||||||
{/* Skeleton Cards */}
|
Carregando estatísticas do sistema...
|
||||||
{[1, 2, 3, 4].map((i) => (
|
</CardContent>
|
||||||
<Card key={i}>
|
</Card>
|
||||||
<CardHeader className="pb-3">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="h-4 w-16 bg-muted animate-pulse rounded" />
|
|
||||||
<div className="h-5 w-12 bg-muted animate-pulse rounded" />
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-2">
|
|
||||||
<div className="h-2 w-full bg-muted animate-pulse rounded" />
|
|
||||||
<div className="h-3 w-24 bg-muted animate-pulse rounded" />
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<Card>
|
|
||||||
<CardContent className="py-8 text-center text-muted-foreground">
|
|
||||||
<div className="flex items-center justify-center gap-2">
|
|
||||||
<div className="h-4 w-4 border-2 border-primary border-t-transparent rounded-full animate-spin" />
|
|
||||||
<span>Carregando estatísticas do sistema...</span>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,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 (
|
||||||
@@ -196,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">
|
||||||
|
|||||||
@@ -1,169 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState } from 'react';
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from '@/components/ui/dialog';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import { ExternalLink, Copy, Check, Terminal } from 'lucide-react';
|
|
||||||
import { ProblemSolution } from '@/lib/docker-problems';
|
|
||||||
import { useToast } from '@/hooks/use-toast';
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
|
|
||||||
interface DockerCommandsModalProps {
|
|
||||||
open: boolean;
|
|
||||||
onOpenChange: (open: boolean) => void;
|
|
||||||
problem: ProblemSolution | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function DockerCommandsModal({ open, onOpenChange, problem }: DockerCommandsModalProps) {
|
|
||||||
const { toast } = useToast();
|
|
||||||
const [copiedIndex, setCopiedIndex] = useState<number | null>(null);
|
|
||||||
|
|
||||||
if (!problem) return null;
|
|
||||||
|
|
||||||
const handleCopyCommand = async (command: string, index: number) => {
|
|
||||||
try {
|
|
||||||
await navigator.clipboard.writeText(command);
|
|
||||||
setCopiedIndex(index);
|
|
||||||
toast({
|
|
||||||
title: 'Comando copiado',
|
|
||||||
description: 'Comando copiado para a área de transferência',
|
|
||||||
});
|
|
||||||
setTimeout(() => setCopiedIndex(null), 2000);
|
|
||||||
} catch (error) {
|
|
||||||
toast({
|
|
||||||
title: 'Erro ao copiar',
|
|
||||||
description: 'Não foi possível copiar o comando',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleOpenLink = async (url: string) => {
|
|
||||||
try {
|
|
||||||
await invoke('open_url', { url });
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error opening URL:', error);
|
|
||||||
// Fallback para window.open se Tauri falhar
|
|
||||||
window.open(url, '_blank', 'noopener,noreferrer');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
|
||||||
<DialogContent className="max-w-[95vw] sm:max-w-3xl max-h-[90vh] overflow-hidden flex flex-col p-4 sm:p-6">
|
|
||||||
<DialogHeader className="flex-shrink-0 pb-2 sm:pb-4">
|
|
||||||
<DialogTitle className="flex items-center gap-2 text-sm sm:text-base md:text-lg">
|
|
||||||
<Terminal className="w-4 h-4 sm:w-5 sm:h-5 shrink-0" />
|
|
||||||
<span className="break-words">{problem.problem}</span>
|
|
||||||
</DialogTitle>
|
|
||||||
{problem.description && (
|
|
||||||
<DialogDescription className="text-xs sm:text-sm mt-1 sm:mt-2">
|
|
||||||
{problem.description}
|
|
||||||
</DialogDescription>
|
|
||||||
)}
|
|
||||||
</DialogHeader>
|
|
||||||
|
|
||||||
<div className="space-y-3 sm:space-y-4 overflow-y-auto flex-1 min-h-0 pr-1 -mr-1">
|
|
||||||
{/* Links de Documentação */}
|
|
||||||
{problem.links.length > 0 && (
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="pb-2 sm:pb-3">
|
|
||||||
<CardTitle className="text-sm sm:text-base flex items-center gap-2">
|
|
||||||
<ExternalLink className="w-3 h-3 sm:w-4 sm:h-4" />
|
|
||||||
Documentação Oficial
|
|
||||||
</CardTitle>
|
|
||||||
<CardDescription className="text-xs sm:text-sm">
|
|
||||||
Links para documentação oficial sobre este problema
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-2">
|
|
||||||
{problem.links.map((link, idx) => (
|
|
||||||
<Button
|
|
||||||
key={idx}
|
|
||||||
variant="outline"
|
|
||||||
className="w-full justify-start text-xs sm:text-sm h-9 sm:h-10"
|
|
||||||
onClick={() => handleOpenLink(link.url)}
|
|
||||||
>
|
|
||||||
<ExternalLink className="w-3 h-3 sm:w-4 sm:h-4 mr-2 shrink-0" />
|
|
||||||
<span className="truncate">{link.title}</span>
|
|
||||||
</Button>
|
|
||||||
))}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Comandos */}
|
|
||||||
{problem.commands && problem.commands.length > 0 && (
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="pb-2 sm:pb-3">
|
|
||||||
<CardTitle className="text-sm sm:text-base flex items-center gap-2">
|
|
||||||
<Terminal className="w-3 h-3 sm:w-4 sm:h-4" />
|
|
||||||
Comandos
|
|
||||||
</CardTitle>
|
|
||||||
<CardDescription className="text-xs sm:text-sm">
|
|
||||||
Execute estes comandos no terminal para resolver o problema
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-3 sm:space-y-4">
|
|
||||||
{problem.commands.map((command, idx) => (
|
|
||||||
<div key={idx} className="space-y-2">
|
|
||||||
<div className="flex items-start justify-between gap-2">
|
|
||||||
<h4 className="text-xs sm:text-sm font-medium flex-1 break-words">{command.title}</h4>
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="ghost"
|
|
||||||
onClick={() => handleCopyCommand(command.code, idx)}
|
|
||||||
className="h-7 sm:h-8 shrink-0 text-xs"
|
|
||||||
>
|
|
||||||
{copiedIndex === idx ? (
|
|
||||||
<>
|
|
||||||
<Check className="w-3 h-3 mr-1 text-green-500" />
|
|
||||||
<span className="hidden sm:inline">Copiado</span>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Copy className="w-3 h-3 mr-1" />
|
|
||||||
<span className="hidden sm:inline">Copiar</span>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
{command.description && (
|
|
||||||
<p className="text-xs text-muted-foreground">{command.description}</p>
|
|
||||||
)}
|
|
||||||
<div className="relative">
|
|
||||||
<pre className="bg-muted p-2 sm:p-3 md:p-4 rounded-lg overflow-x-auto text-xs sm:text-sm">
|
|
||||||
<code className="font-mono whitespace-pre-wrap break-all">{command.code}</code>
|
|
||||||
</pre>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Mensagem quando não há comandos nem links */}
|
|
||||||
{problem.links.length === 0 && (!problem.commands || problem.commands.length === 0) && (
|
|
||||||
<Card>
|
|
||||||
<CardContent className="py-4 sm:py-6 text-center text-muted-foreground">
|
|
||||||
<p className="text-xs sm:text-sm">Nenhuma solução disponível para este problema.</p>
|
|
||||||
<p className="text-xs mt-2">
|
|
||||||
Consulte a documentação oficial do Docker para mais informações.
|
|
||||||
</p>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,899 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
|
||||||
import { Progress } from '@/components/ui/progress';
|
|
||||||
import {
|
|
||||||
CheckCircle2,
|
|
||||||
XCircle,
|
|
||||||
Loader2,
|
|
||||||
Download,
|
|
||||||
RefreshCw,
|
|
||||||
AlertCircle,
|
|
||||||
ExternalLink,
|
|
||||||
Settings,
|
|
||||||
Wrench,
|
|
||||||
Server,
|
|
||||||
Cpu,
|
|
||||||
HardDrive,
|
|
||||||
MemoryStick,
|
|
||||||
Shield,
|
|
||||||
Zap,
|
|
||||||
Terminal
|
|
||||||
} from 'lucide-react';
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
|
||||||
import { listen } from '@tauri-apps/api/event';
|
|
||||||
import { useToast } from '@/hooks/use-toast';
|
|
||||||
import { SearxngInstallWizard } from './searxng-install-wizard';
|
|
||||||
import { DockerCommandsModal } from './docker-commands-modal';
|
|
||||||
import { findProblemSolution, ProblemSolution } from '@/lib/docker-problems';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
|
|
||||||
interface SystemRequirements {
|
|
||||||
status: 'pass' | 'fail' | 'warn';
|
|
||||||
os: string;
|
|
||||||
arch: string;
|
|
||||||
ram_mb: number;
|
|
||||||
disk_gb: number;
|
|
||||||
cpu_cores: number;
|
|
||||||
kernel_version?: string;
|
|
||||||
issues: string[];
|
|
||||||
warnings: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface InstallProgressEvent {
|
|
||||||
event_type: 'step_start' | 'log' | 'step_complete' | 'error' | 'complete';
|
|
||||||
step?: number;
|
|
||||||
step_name?: string;
|
|
||||||
total_steps?: number;
|
|
||||||
progress: number;
|
|
||||||
message?: string;
|
|
||||||
log_line?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface FixProgressEvent {
|
|
||||||
event_type: 'start' | 'progress' | 'complete' | 'error';
|
|
||||||
message: string;
|
|
||||||
progress?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ValidationResult {
|
|
||||||
status: 'pass' | 'fail' | 'partial';
|
|
||||||
tests: Array<{
|
|
||||||
name: string;
|
|
||||||
status: 'pass' | 'fail' | 'warn';
|
|
||||||
message?: string;
|
|
||||||
}>;
|
|
||||||
docker_version?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function DockerSettingsPanel() {
|
|
||||||
const { toast } = useToast();
|
|
||||||
const [dockerAvailable, setDockerAvailable] = useState<boolean | null>(null);
|
|
||||||
const [dockerRunning, setDockerRunning] = useState<boolean | null>(null);
|
|
||||||
const [isChecking, setIsChecking] = useState(false);
|
|
||||||
const [requirements, setRequirements] = useState<SystemRequirements | null>(null);
|
|
||||||
const [isCheckingRequirements, setIsCheckingRequirements] = useState(false);
|
|
||||||
const [isInstallingDocker, setIsInstallingDocker] = useState(false);
|
|
||||||
const [isFixing, setIsFixing] = useState(false);
|
|
||||||
const [fixProgress, setFixProgress] = useState<{ message: string; progress: number } | null>(null);
|
|
||||||
const [dockerInstallProgress, setDockerInstallProgress] = useState<{
|
|
||||||
currentStep: number;
|
|
||||||
totalSteps: number;
|
|
||||||
progress: number;
|
|
||||||
currentStepName: string;
|
|
||||||
logs: string[];
|
|
||||||
}>({
|
|
||||||
currentStep: 0,
|
|
||||||
totalSteps: 0,
|
|
||||||
progress: 0,
|
|
||||||
currentStepName: '',
|
|
||||||
logs: [],
|
|
||||||
});
|
|
||||||
const [validationResult, setValidationResult] = useState<ValidationResult | null>(null);
|
|
||||||
const [isValidating, setIsValidating] = useState(false);
|
|
||||||
const [showInstallWizard, setShowInstallWizard] = useState(false);
|
|
||||||
const [showCommandsModal, setShowCommandsModal] = useState(false);
|
|
||||||
const [selectedProblem, setSelectedProblem] = useState<ProblemSolution | null>(null);
|
|
||||||
|
|
||||||
// Verificar Docker ao montar
|
|
||||||
useEffect(() => {
|
|
||||||
checkDocker();
|
|
||||||
checkRequirements();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Listener de eventos de progresso Docker
|
|
||||||
useEffect(() => {
|
|
||||||
let unlistenPromise: Promise<() => void> | null = null;
|
|
||||||
|
|
||||||
if (isInstallingDocker) {
|
|
||||||
unlistenPromise = listen<InstallProgressEvent>('docker-install-progress', (event) => {
|
|
||||||
const data = event.payload;
|
|
||||||
|
|
||||||
switch (data.event_type) {
|
|
||||||
case 'step_start':
|
|
||||||
setDockerInstallProgress(prev => ({
|
|
||||||
...prev,
|
|
||||||
currentStep: data.step || 0,
|
|
||||||
totalSteps: data.total_steps || prev.totalSteps,
|
|
||||||
currentStepName: data.step_name || '',
|
|
||||||
progress: data.progress,
|
|
||||||
}));
|
|
||||||
if (data.message) {
|
|
||||||
setDockerInstallProgress(prev => ({
|
|
||||||
...prev,
|
|
||||||
logs: [...prev.logs.slice(-49), data.message!],
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'log':
|
|
||||||
if (data.log_line) {
|
|
||||||
setDockerInstallProgress(prev => ({
|
|
||||||
...prev,
|
|
||||||
logs: [...prev.logs.slice(-49), data.log_line!],
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'step_complete':
|
|
||||||
setDockerInstallProgress(prev => ({
|
|
||||||
...prev,
|
|
||||||
progress: data.progress,
|
|
||||||
}));
|
|
||||||
if (data.message) {
|
|
||||||
setDockerInstallProgress(prev => ({
|
|
||||||
...prev,
|
|
||||||
logs: [...prev.logs.slice(-49), data.message!],
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'error':
|
|
||||||
toast({
|
|
||||||
title: 'Erro na instalação',
|
|
||||||
description: data.message || 'Erro desconhecido',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
setIsInstallingDocker(false);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'complete':
|
|
||||||
setDockerInstallProgress(prev => ({ ...prev, progress: 100 }));
|
|
||||||
setIsInstallingDocker(false);
|
|
||||||
toast({
|
|
||||||
title: 'Docker instalado',
|
|
||||||
description: 'Docker foi instalado com sucesso!',
|
|
||||||
});
|
|
||||||
setTimeout(() => {
|
|
||||||
validateDocker();
|
|
||||||
checkDocker();
|
|
||||||
}, 1000);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
if (unlistenPromise) {
|
|
||||||
unlistenPromise.then(fn => fn());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, [isInstallingDocker, toast]);
|
|
||||||
|
|
||||||
// Listener de eventos de correção
|
|
||||||
useEffect(() => {
|
|
||||||
let unlistenPromise: Promise<() => void> | null = null;
|
|
||||||
|
|
||||||
if (isFixing) {
|
|
||||||
unlistenPromise = listen<FixProgressEvent>('docker-fix-progress', (event) => {
|
|
||||||
const data = event.payload;
|
|
||||||
|
|
||||||
switch (data.event_type) {
|
|
||||||
case 'start':
|
|
||||||
setFixProgress({ message: data.message, progress: 0 });
|
|
||||||
break;
|
|
||||||
case 'progress':
|
|
||||||
setFixProgress({ message: data.message, progress: data.progress || 0 });
|
|
||||||
break;
|
|
||||||
case 'complete':
|
|
||||||
setFixProgress({ message: data.message, progress: 100 });
|
|
||||||
setTimeout(() => {
|
|
||||||
setIsFixing(false);
|
|
||||||
setFixProgress(null);
|
|
||||||
checkRequirements();
|
|
||||||
toast({
|
|
||||||
title: 'Correção concluída',
|
|
||||||
description: data.message,
|
|
||||||
});
|
|
||||||
}, 1500);
|
|
||||||
break;
|
|
||||||
case 'error':
|
|
||||||
setIsFixing(false);
|
|
||||||
setFixProgress(null);
|
|
||||||
toast({
|
|
||||||
title: 'Erro na correção',
|
|
||||||
description: data.message,
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
if (unlistenPromise) {
|
|
||||||
unlistenPromise.then(fn => fn());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, [isFixing, toast]);
|
|
||||||
|
|
||||||
const checkDocker = async () => {
|
|
||||||
setIsChecking(true);
|
|
||||||
try {
|
|
||||||
const available = await invoke<boolean>('check_docker_available');
|
|
||||||
setDockerAvailable(available);
|
|
||||||
|
|
||||||
if (available) {
|
|
||||||
const running = await invoke<boolean>('check_docker_running');
|
|
||||||
setDockerRunning(running);
|
|
||||||
} else {
|
|
||||||
setDockerRunning(false);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error checking Docker:', error);
|
|
||||||
setDockerAvailable(false);
|
|
||||||
setDockerRunning(false);
|
|
||||||
} finally {
|
|
||||||
setIsChecking(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const checkRequirements = async () => {
|
|
||||||
setIsCheckingRequirements(true);
|
|
||||||
try {
|
|
||||||
const reqs = await invoke<SystemRequirements>('check_docker_requirements');
|
|
||||||
setRequirements(reqs);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error checking requirements:', error);
|
|
||||||
setRequirements({
|
|
||||||
status: 'fail',
|
|
||||||
os: 'unknown',
|
|
||||||
arch: 'unknown',
|
|
||||||
ram_mb: 0,
|
|
||||||
disk_gb: 0,
|
|
||||||
cpu_cores: 0,
|
|
||||||
issues: ['Erro ao verificar requisitos do sistema'],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsCheckingRequirements(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleFixRequirements = async () => {
|
|
||||||
if (!requirements || requirements.issues.length === 0) {
|
|
||||||
toast({
|
|
||||||
title: 'Nada para corrigir',
|
|
||||||
description: 'Não há problemas encontrados que possam ser corrigidos automaticamente',
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsFixing(true);
|
|
||||||
setFixProgress({ message: 'Preparando correção...', progress: 0 });
|
|
||||||
|
|
||||||
try {
|
|
||||||
await invoke('fix_docker_requirements', {
|
|
||||||
os: requirements.os,
|
|
||||||
issues: requirements.issues,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fixing requirements:', error);
|
|
||||||
setIsFixing(false);
|
|
||||||
setFixProgress(null);
|
|
||||||
toast({
|
|
||||||
title: 'Erro na correção',
|
|
||||||
description: error instanceof Error ? error.message : 'Erro desconhecido',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleInstallDocker = async () => {
|
|
||||||
setIsInstallingDocker(true);
|
|
||||||
setDockerInstallProgress({
|
|
||||||
currentStep: 0,
|
|
||||||
totalSteps: 0,
|
|
||||||
progress: 0,
|
|
||||||
currentStepName: '',
|
|
||||||
logs: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
await invoke('install_docker');
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Docker installation error:', error);
|
|
||||||
toast({
|
|
||||||
title: 'Erro na instalação',
|
|
||||||
description: error instanceof Error ? error.message : 'Erro desconhecido durante instalação do Docker',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
setIsInstallingDocker(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const validateDocker = async () => {
|
|
||||||
setIsValidating(true);
|
|
||||||
setValidationResult(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await invoke<ValidationResult>('validate_docker_installation');
|
|
||||||
setValidationResult(result);
|
|
||||||
|
|
||||||
if (result.status === 'pass' || result.status === 'partial') {
|
|
||||||
setDockerAvailable(true);
|
|
||||||
setDockerRunning(true);
|
|
||||||
toast({
|
|
||||||
title: 'Docker validado',
|
|
||||||
description: 'Docker está funcionando corretamente',
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
toast({
|
|
||||||
title: 'Validação falhou',
|
|
||||||
description: 'Alguns testes de validação falharam',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Validation error:', error);
|
|
||||||
toast({
|
|
||||||
title: 'Erro na validação',
|
|
||||||
description: error instanceof Error ? error.message : 'Erro ao validar Docker',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsValidating(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
const getStatusIcon = (status: 'pass' | 'fail' | 'warn') => {
|
|
||||||
switch (status) {
|
|
||||||
case 'pass':
|
|
||||||
return <CheckCircle2 className="w-5 h-5 text-green-500" />;
|
|
||||||
case 'fail':
|
|
||||||
return <XCircle className="w-5 h-5 text-red-500" />;
|
|
||||||
case 'warn':
|
|
||||||
return <AlertCircle className="w-5 h-5 text-yellow-500" />;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{/* Status do Docker */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="pb-3">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Server className="w-5 h-5 text-primary" />
|
|
||||||
<CardTitle className="text-lg">Status do Docker</CardTitle>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={checkDocker}
|
|
||||||
disabled={isChecking}
|
|
||||||
>
|
|
||||||
<RefreshCw className={cn("w-4 h-4 mr-1", isChecking && "animate-spin")} />
|
|
||||||
Atualizar
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<CardDescription>
|
|
||||||
Verifique se Docker está instalado e rodando
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-4">
|
|
||||||
{isChecking ? (
|
|
||||||
<div className="flex items-center justify-center py-6">
|
|
||||||
<Loader2 className="w-5 h-5 animate-spin text-primary mr-2" />
|
|
||||||
<span className="text-sm text-muted-foreground">Verificando...</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div className={cn(
|
|
||||||
"p-4 rounded-lg border-2 transition-colors",
|
|
||||||
dockerAvailable
|
|
||||||
? "border-green-500/50 bg-green-500/10 dark:bg-green-500/20"
|
|
||||||
: "border-red-500/50 bg-red-500/10 dark:bg-red-500/20"
|
|
||||||
)}>
|
|
||||||
<div className="flex items-center justify-between mb-2">
|
|
||||||
<span className="text-sm font-semibold text-foreground">Instalação</span>
|
|
||||||
{dockerAvailable ? (
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-green-600 dark:text-green-400" />
|
|
||||||
) : (
|
|
||||||
<XCircle className="w-5 h-5 text-red-600 dark:text-red-400" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className={cn(
|
|
||||||
dockerAvailable
|
|
||||||
? "text-green-700 dark:text-green-300 border-green-600 dark:border-green-400 bg-green-100 dark:bg-green-500/20"
|
|
||||||
: "text-red-700 dark:text-red-300 border-red-600 dark:border-red-400 bg-red-100 dark:bg-red-500/20"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{dockerAvailable ? 'Instalado' : 'Não Instalado'}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className={cn(
|
|
||||||
"p-4 rounded-lg border-2 transition-colors",
|
|
||||||
dockerRunning
|
|
||||||
? "border-green-500/50 bg-green-500/10 dark:bg-green-500/20"
|
|
||||||
: "border-red-500/50 bg-red-500/10 dark:bg-red-500/20"
|
|
||||||
)}>
|
|
||||||
<div className="flex items-center justify-between mb-2">
|
|
||||||
<span className="text-sm font-semibold text-foreground">Serviço</span>
|
|
||||||
{dockerRunning ? (
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-green-600 dark:text-green-400" />
|
|
||||||
) : (
|
|
||||||
<XCircle className="w-5 h-5 text-red-600 dark:text-red-400" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className={cn(
|
|
||||||
dockerRunning
|
|
||||||
? "text-green-700 dark:text-green-300 border-green-600 dark:border-green-400 bg-green-100 dark:bg-green-500/20"
|
|
||||||
: "text-red-700 dark:text-red-300 border-red-600 dark:border-red-400 bg-red-100 dark:bg-red-500/20"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{dockerRunning ? 'Rodando' : 'Parado'}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{dockerAvailable === false && (
|
|
||||||
<Alert variant="destructive">
|
|
||||||
<AlertCircle className="w-4 h-4" />
|
|
||||||
<AlertDescription>
|
|
||||||
Docker não está instalado. Instale-o para usar SearXNG.
|
|
||||||
</AlertDescription>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{dockerAvailable && !dockerRunning && (
|
|
||||||
<Alert>
|
|
||||||
<AlertCircle className="w-4 h-4" />
|
|
||||||
<AlertDescription>
|
|
||||||
Docker está instalado mas não está rodando. Inicie o Docker Desktop.
|
|
||||||
</AlertDescription>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Requisitos do Sistema */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="pb-3">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Shield className="w-5 h-5 text-primary" />
|
|
||||||
<CardTitle className="text-lg">Requisitos do Sistema</CardTitle>
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
{requirements && requirements.issues.length > 0 && (
|
|
||||||
<Button
|
|
||||||
variant="default"
|
|
||||||
size="sm"
|
|
||||||
onClick={handleFixRequirements}
|
|
||||||
disabled={isFixing || isCheckingRequirements}
|
|
||||||
>
|
|
||||||
<Wrench className="w-4 h-4 mr-1" />
|
|
||||||
Corrigir
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={checkRequirements}
|
|
||||||
disabled={isCheckingRequirements}
|
|
||||||
>
|
|
||||||
<RefreshCw className={cn("w-4 h-4 mr-1", isCheckingRequirements && "animate-spin")} />
|
|
||||||
Verificar
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<CardDescription>
|
|
||||||
Verifique se seu sistema atende aos requisitos para Docker
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-4">
|
|
||||||
{isCheckingRequirements ? (
|
|
||||||
<div className="flex items-center justify-center py-6">
|
|
||||||
<Loader2 className="w-5 h-5 animate-spin text-primary mr-2" />
|
|
||||||
<span className="text-sm text-muted-foreground">Verificando requisitos...</span>
|
|
||||||
</div>
|
|
||||||
) : requirements ? (
|
|
||||||
<>
|
|
||||||
{/* Status Geral */}
|
|
||||||
<div className={cn(
|
|
||||||
"p-4 rounded-lg border-2 flex items-center justify-between",
|
|
||||||
requirements.status === 'pass' && "border-green-500/50 bg-green-500/10 dark:bg-green-500/20",
|
|
||||||
requirements.status === 'warn' && "border-yellow-500/50 bg-yellow-500/10 dark:bg-yellow-500/20",
|
|
||||||
requirements.status === 'fail' && "border-red-500/50 bg-red-500/10 dark:bg-red-500/20"
|
|
||||||
)}>
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
{getStatusIcon(requirements.status)}
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold text-foreground">Status Geral</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{requirements.status === 'pass' && 'Sistema compatível'}
|
|
||||||
{requirements.status === 'warn' && 'Avisos encontrados'}
|
|
||||||
{requirements.status === 'fail' && 'Problemas encontrados'}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<Badge className={cn(
|
|
||||||
requirements.status === 'pass' && "bg-green-500",
|
|
||||||
requirements.status === 'warn' && "bg-yellow-500",
|
|
||||||
requirements.status === 'fail' && "bg-red-500"
|
|
||||||
)}>
|
|
||||||
{requirements.status === 'pass' && 'Compatível'}
|
|
||||||
{requirements.status === 'warn' && 'Avisos'}
|
|
||||||
{requirements.status === 'fail' && 'Incompatível'}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Especificações do Sistema */}
|
|
||||||
<div className="grid grid-cols-2 gap-3">
|
|
||||||
<div className="p-3 rounded-lg border bg-muted/30">
|
|
||||||
<div className="flex items-center gap-2 mb-1">
|
|
||||||
<MemoryStick className="w-4 h-4 text-muted-foreground" />
|
|
||||||
<span className="text-xs text-muted-foreground">RAM</span>
|
|
||||||
</div>
|
|
||||||
<p className="text-sm font-medium">{(requirements.ram_mb / 1024).toFixed(1)} GB</p>
|
|
||||||
</div>
|
|
||||||
<div className="p-3 rounded-lg border bg-muted/30">
|
|
||||||
<div className="flex items-center gap-2 mb-1">
|
|
||||||
<HardDrive className="w-4 h-4 text-muted-foreground" />
|
|
||||||
<span className="text-xs text-muted-foreground">Disco Livre</span>
|
|
||||||
</div>
|
|
||||||
<p className="text-sm font-medium">{requirements.disk_gb} GB</p>
|
|
||||||
</div>
|
|
||||||
<div className="p-3 rounded-lg border bg-muted/30">
|
|
||||||
<div className="flex items-center gap-2 mb-1">
|
|
||||||
<Cpu className="w-4 h-4 text-muted-foreground" />
|
|
||||||
<span className="text-xs text-muted-foreground">CPU Cores</span>
|
|
||||||
</div>
|
|
||||||
<p className="text-sm font-medium">{requirements.cpu_cores}</p>
|
|
||||||
</div>
|
|
||||||
<div className="p-3 rounded-lg border bg-muted/30">
|
|
||||||
<div className="flex items-center gap-2 mb-1">
|
|
||||||
<Server className="w-4 h-4 text-muted-foreground" />
|
|
||||||
<span className="text-xs text-muted-foreground">Sistema</span>
|
|
||||||
</div>
|
|
||||||
<p className="text-sm font-medium">{requirements.os} ({requirements.arch})</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Progresso de Correção */}
|
|
||||||
{isFixing && fixProgress && (
|
|
||||||
<div className="space-y-2 p-4 rounded-lg border bg-blue-50 border-blue-200">
|
|
||||||
<div className="flex items-center justify-between text-sm">
|
|
||||||
<span className="font-medium">{fixProgress.message}</span>
|
|
||||||
<span>{fixProgress.progress}%</span>
|
|
||||||
</div>
|
|
||||||
<Progress value={fixProgress.progress} className="h-2" />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Problemas */}
|
|
||||||
{requirements.issues.length > 0 && (
|
|
||||||
<Alert variant="destructive">
|
|
||||||
<AlertCircle className="w-4 h-4" />
|
|
||||||
<AlertDescription>
|
|
||||||
<p className="font-medium mb-2">Problemas Encontrados:</p>
|
|
||||||
<ul className="space-y-2 text-sm">
|
|
||||||
{requirements.issues.map((issue, idx) => {
|
|
||||||
const solution = findProblemSolution(issue, requirements.os);
|
|
||||||
return (
|
|
||||||
<li key={idx} className="flex items-start justify-between gap-2">
|
|
||||||
<span className="flex-1">{issue}</span>
|
|
||||||
{solution && (
|
|
||||||
<div className="flex gap-1 shrink-0">
|
|
||||||
{solution.commands && solution.commands.length > 0 && (
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => {
|
|
||||||
setSelectedProblem(solution);
|
|
||||||
setShowCommandsModal(true);
|
|
||||||
}}
|
|
||||||
className="h-7 text-xs"
|
|
||||||
>
|
|
||||||
<Terminal className="w-3 h-3 mr-1" />
|
|
||||||
Comandos
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{solution.links.length > 0 && (
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="outline"
|
|
||||||
onClick={async () => {
|
|
||||||
if (solution.links[0]) {
|
|
||||||
try {
|
|
||||||
await invoke('open_url', { url: solution.links[0].url });
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error opening URL:', error);
|
|
||||||
window.open(solution.links[0].url, '_blank', 'noopener,noreferrer');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
className="h-7 text-xs"
|
|
||||||
>
|
|
||||||
<ExternalLink className="w-3 h-3 mr-1" />
|
|
||||||
Docs
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</li>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</ul>
|
|
||||||
</AlertDescription>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Avisos */}
|
|
||||||
{requirements.warnings.length > 0 && (
|
|
||||||
<Alert>
|
|
||||||
<AlertCircle className="w-4 h-4" />
|
|
||||||
<AlertDescription>
|
|
||||||
<p className="font-medium mb-2">Avisos:</p>
|
|
||||||
<ul className="space-y-2 text-sm">
|
|
||||||
{requirements.warnings.map((warning, idx) => {
|
|
||||||
const solution = findProblemSolution(warning, requirements.os);
|
|
||||||
return (
|
|
||||||
<li key={idx} className="flex items-start justify-between gap-2">
|
|
||||||
<span className="flex-1">{warning}</span>
|
|
||||||
{solution && (
|
|
||||||
<div className="flex gap-1 shrink-0">
|
|
||||||
{solution.commands && solution.commands.length > 0 && (
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => {
|
|
||||||
setSelectedProblem(solution);
|
|
||||||
setShowCommandsModal(true);
|
|
||||||
}}
|
|
||||||
className="h-7 text-xs"
|
|
||||||
>
|
|
||||||
<Terminal className="w-3 h-3 mr-1" />
|
|
||||||
Comandos
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{solution.links.length > 0 && (
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="outline"
|
|
||||||
onClick={async () => {
|
|
||||||
if (solution.links[0]) {
|
|
||||||
try {
|
|
||||||
await invoke('open_url', { url: solution.links[0].url });
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error opening URL:', error);
|
|
||||||
window.open(solution.links[0].url, '_blank', 'noopener,noreferrer');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
className="h-7 text-xs"
|
|
||||||
>
|
|
||||||
<ExternalLink className="w-3 h-3 mr-1" />
|
|
||||||
Docs
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</li>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</ul>
|
|
||||||
</AlertDescription>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
) : null}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Instalação Docker */}
|
|
||||||
{dockerAvailable === false && (
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="pb-3">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Download className="w-5 h-5 text-primary" />
|
|
||||||
<CardTitle className="text-lg">Instalar Docker</CardTitle>
|
|
||||||
</div>
|
|
||||||
<CardDescription>
|
|
||||||
Instale Docker automaticamente ou manualmente
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-4">
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => {
|
|
||||||
window.open('https://www.docker.com/products/docker-desktop', '_blank');
|
|
||||||
}}
|
|
||||||
className="flex-1"
|
|
||||||
>
|
|
||||||
<ExternalLink className="w-4 h-4 mr-2" />
|
|
||||||
Instalação Manual
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="default"
|
|
||||||
onClick={handleInstallDocker}
|
|
||||||
disabled={isInstallingDocker || requirements?.status === 'fail'}
|
|
||||||
className="flex-1"
|
|
||||||
>
|
|
||||||
{isInstallingDocker ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
|
||||||
Instalando...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Zap className="w-4 h-4 mr-2" />
|
|
||||||
Instalar Agora
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isInstallingDocker && (
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex items-center justify-between text-sm">
|
|
||||||
<span className="font-medium">{dockerInstallProgress.currentStepName || 'Instalando Docker...'}</span>
|
|
||||||
<span className="text-muted-foreground">{dockerInstallProgress.progress}%</span>
|
|
||||||
</div>
|
|
||||||
<Progress value={dockerInstallProgress.progress} className="h-2" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{dockerInstallProgress.logs.length > 0 && (
|
|
||||||
<div className="bg-black text-green-400 font-mono text-xs p-3 rounded-lg h-40 overflow-y-auto">
|
|
||||||
{dockerInstallProgress.logs.map((log, idx) => (
|
|
||||||
<div key={idx}>{log}</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Validação */}
|
|
||||||
{dockerAvailable && (
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="pb-3">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-primary" />
|
|
||||||
<CardTitle className="text-lg">Validação</CardTitle>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={validateDocker}
|
|
||||||
disabled={isValidating}
|
|
||||||
>
|
|
||||||
{isValidating ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="w-4 h-4 mr-1 animate-spin" />
|
|
||||||
Validando...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<RefreshCw className="w-4 h-4 mr-1" />
|
|
||||||
Validar
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<CardDescription>
|
|
||||||
Execute testes para verificar se Docker está funcionando corretamente
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
{validationResult ? (
|
|
||||||
<div className="space-y-2">
|
|
||||||
{validationResult.tests.map((test, idx) => (
|
|
||||||
<div
|
|
||||||
key={idx}
|
|
||||||
className={cn(
|
|
||||||
"flex items-center justify-between p-3 rounded-lg border",
|
|
||||||
test.status === 'pass' && "bg-green-50 border-green-200",
|
|
||||||
test.status === 'warn' && "bg-yellow-50 border-yellow-200",
|
|
||||||
test.status === 'fail' && "bg-red-50 border-red-200"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="flex-1">
|
|
||||||
<p className="text-sm font-medium">{test.name}</p>
|
|
||||||
{test.message && (
|
|
||||||
<p className="text-xs text-muted-foreground mt-1">{test.message}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{test.status === 'pass' ? (
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-green-500 flex-shrink-0" />
|
|
||||||
) : test.status === 'warn' ? (
|
|
||||||
<AlertCircle className="w-5 h-5 text-yellow-500 flex-shrink-0" />
|
|
||||||
) : (
|
|
||||||
<XCircle className="w-5 h-5 text-red-500 flex-shrink-0" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
{validationResult.docker_version && (
|
|
||||||
<p className="text-xs text-muted-foreground mt-2">
|
|
||||||
Docker {validationResult.docker_version} instalado
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<p className="text-sm text-muted-foreground text-center py-4">
|
|
||||||
Clique em "Validar" para executar os testes
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Botão para configurar SearXNG */}
|
|
||||||
{dockerAvailable && dockerRunning && (
|
|
||||||
<Card>
|
|
||||||
<CardContent className="pt-6">
|
|
||||||
<Button
|
|
||||||
variant="default"
|
|
||||||
onClick={() => setShowInstallWizard(true)}
|
|
||||||
className="w-full"
|
|
||||||
size="lg"
|
|
||||||
>
|
|
||||||
<Settings className="w-5 h-5 mr-2" />
|
|
||||||
Configurar SearXNG
|
|
||||||
</Button>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{showInstallWizard && (
|
|
||||||
<SearxngInstallWizard
|
|
||||||
onComplete={() => {
|
|
||||||
setShowInstallWizard(false);
|
|
||||||
checkDocker();
|
|
||||||
toast({
|
|
||||||
title: 'SearXNG configurado',
|
|
||||||
description: 'SearXNG foi instalado e configurado com sucesso!',
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
onCancel={() => setShowInstallWizard(false)}
|
|
||||||
initialUrl="http://localhost:8080"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<DockerCommandsModal
|
|
||||||
open={showCommandsModal}
|
|
||||||
onOpenChange={setShowCommandsModal}
|
|
||||||
problem={selectedProblem}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,244 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
|
||||||
import { Label } from '@/components/ui/label';
|
|
||||||
import { Switch } from '@/components/ui/switch';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
|
||||||
import { Slider } from '@/components/ui/slider';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { useSettingsStore } from '@/store/settings-store';
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
|
||||||
import { Zap, Cpu } from 'lucide-react';
|
|
||||||
|
|
||||||
interface LocalGgufModel {
|
|
||||||
path: string;
|
|
||||||
name: string;
|
|
||||||
size: number;
|
|
||||||
quantization?: string;
|
|
||||||
architecture?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function RuntimeSettingsPanel() {
|
|
||||||
const { runtime, llamaCppParams, setRuntime, setLlamaCppParams } = useSettingsStore();
|
|
||||||
const [localModels, setLocalModels] = useState<LocalGgufModel[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
loadLocalModels();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const loadLocalModels = async () => {
|
|
||||||
try {
|
|
||||||
setLoading(true);
|
|
||||||
const models = await invoke<LocalGgufModel[]>('list_local_gguf_models');
|
|
||||||
setLocalModels(models);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to load local GGUF models:', error);
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const hasLocalModels = localModels.length > 0;
|
|
||||||
const isLlamaCppAvailable = hasLocalModels;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Runtime de Modelos</CardTitle>
|
|
||||||
<CardDescription>
|
|
||||||
Escolha entre Ollama (servidor externo) ou llama.cpp nativo (mais rápido, sem servidor)
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-6">
|
|
||||||
{/* Toggle de Runtime */}
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="space-y-0.5">
|
|
||||||
<Label htmlFor="runtime-toggle">Usar llama.cpp nativo</Label>
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
{runtime === 'ollama'
|
|
||||||
? 'Usando Ollama como runtime (requer servidor externo)'
|
|
||||||
: 'Usando llama.cpp nativo (mais rápido, sem servidor externo)'}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<TooltipProvider>
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<Badge variant={runtime === 'ollama' ? 'default' : 'secondary'} className="gap-1">
|
|
||||||
{runtime === 'ollama' ? (
|
|
||||||
<>
|
|
||||||
<span>🦙</span> Ollama
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Zap className="h-3 w-3" />
|
|
||||||
llama.cpp
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Badge>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent>
|
|
||||||
{runtime === 'ollama'
|
|
||||||
? 'Usando Ollama como runtime (requer servidor externo)'
|
|
||||||
: 'Usando llama.cpp nativo (mais rápido, sem servidor externo)'}
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</TooltipProvider>
|
|
||||||
<Switch
|
|
||||||
id="runtime-toggle"
|
|
||||||
checked={runtime === 'llama-cpp'}
|
|
||||||
onCheckedChange={(checked) => setRuntime(checked ? 'llama-cpp' : 'ollama')}
|
|
||||||
disabled={!isLlamaCppAvailable}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{!isLlamaCppAvailable && (
|
|
||||||
<div className="rounded-md bg-yellow-50 dark:bg-yellow-900/20 p-3 text-sm text-yellow-800 dark:text-yellow-200">
|
|
||||||
<p>
|
|
||||||
Nenhum modelo GGUF local encontrado. Baixe modelos do Hugging Face para usar llama.cpp nativo.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{loading && (
|
|
||||||
<div className="text-sm text-muted-foreground">Carregando modelos locais...</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{hasLocalModels && (
|
|
||||||
<div className="rounded-md bg-muted p-3">
|
|
||||||
<p className="text-sm font-medium mb-2">
|
|
||||||
Modelos GGUF locais encontrados: {localModels.length}
|
|
||||||
</p>
|
|
||||||
<div className="space-y-1">
|
|
||||||
{localModels.slice(0, 5).map((model, idx) => (
|
|
||||||
<div key={idx} className="text-xs text-muted-foreground">
|
|
||||||
• {model.name} {model.quantization && `(${model.quantization})`}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
{localModels.length > 5 && (
|
|
||||||
<div className="text-xs text-muted-foreground">
|
|
||||||
... e mais {localModels.length - 5} modelo(s)
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Configurações do llama.cpp */}
|
|
||||||
{runtime === 'llama-cpp' && (
|
|
||||||
<div className="space-y-4 pt-4 border-t">
|
|
||||||
<div>
|
|
||||||
<Label>Camadas GPU (n_gpu_layers)</Label>
|
|
||||||
<p className="text-sm text-muted-foreground mb-2">
|
|
||||||
Número de camadas para carregar na GPU. 0 = CPU apenas
|
|
||||||
</p>
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<Slider
|
|
||||||
value={[llamaCppParams.nGpuLayers]}
|
|
||||||
onValueChange={([value]) =>
|
|
||||||
setLlamaCppParams({ nGpuLayers: value })
|
|
||||||
}
|
|
||||||
min={0}
|
|
||||||
max={100}
|
|
||||||
step={1}
|
|
||||||
className="flex-1"
|
|
||||||
/>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
value={llamaCppParams.nGpuLayers}
|
|
||||||
onChange={(e) =>
|
|
||||||
setLlamaCppParams({ nGpuLayers: parseInt(e.target.value) || 0 })
|
|
||||||
}
|
|
||||||
className="w-20"
|
|
||||||
min={0}
|
|
||||||
max={100}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label>Tamanho do Contexto (n_ctx)</Label>
|
|
||||||
<p className="text-sm text-muted-foreground mb-2">
|
|
||||||
Tamanho máximo do contexto em tokens
|
|
||||||
</p>
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<Slider
|
|
||||||
value={[llamaCppParams.nCtx]}
|
|
||||||
onValueChange={([value]) =>
|
|
||||||
setLlamaCppParams({ nCtx: value })
|
|
||||||
}
|
|
||||||
min={512}
|
|
||||||
max={32768}
|
|
||||||
step={512}
|
|
||||||
className="flex-1"
|
|
||||||
/>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
value={llamaCppParams.nCtx}
|
|
||||||
onChange={(e) =>
|
|
||||||
setLlamaCppParams({ nCtx: parseInt(e.target.value) || 4096 })
|
|
||||||
}
|
|
||||||
className="w-24"
|
|
||||||
min={512}
|
|
||||||
max={32768}
|
|
||||||
step={512}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label>Threads</Label>
|
|
||||||
<p className="text-sm text-muted-foreground mb-2">
|
|
||||||
Número de threads (0 = automático)
|
|
||||||
</p>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
value={llamaCppParams.threads || 0}
|
|
||||||
onChange={(e) =>
|
|
||||||
setLlamaCppParams({ threads: parseInt(e.target.value) || 0 })
|
|
||||||
}
|
|
||||||
className="w-32"
|
|
||||||
min={0}
|
|
||||||
max={32}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label>Temperatura</Label>
|
|
||||||
<p className="text-sm text-muted-foreground mb-2">
|
|
||||||
Controla a aleatoriedade das respostas (0.0 - 2.0)
|
|
||||||
</p>
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<Slider
|
|
||||||
value={[llamaCppParams.temperature]}
|
|
||||||
onValueChange={([value]) =>
|
|
||||||
setLlamaCppParams({ temperature: value })
|
|
||||||
}
|
|
||||||
min={0}
|
|
||||||
max={2}
|
|
||||||
step={0.1}
|
|
||||||
className="flex-1"
|
|
||||||
/>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
value={llamaCppParams.temperature}
|
|
||||||
onChange={(e) =>
|
|
||||||
setLlamaCppParams({ temperature: parseFloat(e.target.value) || 0.7 })
|
|
||||||
}
|
|
||||||
className="w-20"
|
|
||||||
min={0}
|
|
||||||
max={2}
|
|
||||||
step={0.1}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,209 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Switch } from '@/components/ui/switch';
|
|
||||||
import { Label } from '@/components/ui/label';
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
|
||||||
import { useToast } from '@/hooks/use-toast';
|
|
||||||
import { Loader2, Save, Search, Shield } from 'lucide-react';
|
|
||||||
|
|
||||||
interface SearchConfig {
|
|
||||||
region: string;
|
|
||||||
safe_search: string;
|
|
||||||
max_results: number;
|
|
||||||
enabled: boolean;
|
|
||||||
log_search_content: boolean;
|
|
||||||
retention_days: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SearchSettingsPanel() {
|
|
||||||
const { toast } = useToast();
|
|
||||||
const [config, setConfig] = useState<SearchConfig | null>(null);
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [isSaving, setIsSaving] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
loadConfig();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const loadConfig = async () => {
|
|
||||||
setIsLoading(true);
|
|
||||||
try {
|
|
||||||
const loadedConfig = await invoke<SearchConfig>('load_search_config_command');
|
|
||||||
setConfig(loadedConfig);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to load Search config:', error);
|
|
||||||
toast({
|
|
||||||
title: 'Error loading configuration',
|
|
||||||
description: String(error),
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSave = async () => {
|
|
||||||
if (!config) return;
|
|
||||||
|
|
||||||
setIsSaving(true);
|
|
||||||
try {
|
|
||||||
await invoke('save_search_config_command', { config });
|
|
||||||
toast({
|
|
||||||
title: 'Configuration saved',
|
|
||||||
description: 'Search settings have been updated successfully.',
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to save Search config:', error);
|
|
||||||
toast({
|
|
||||||
title: 'Error saving configuration',
|
|
||||||
description: String(error),
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsSaving(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (isLoading) {
|
|
||||||
return (
|
|
||||||
<div className="flex items-center justify-center p-8">
|
|
||||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!config) {
|
|
||||||
return (
|
|
||||||
<div className="text-center p-8 text-muted-foreground">
|
|
||||||
Failed to load configuration.
|
|
||||||
<Button variant="outline" className="ml-4" onClick={loadConfig}>Retry</Button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<CardTitle className="flex items-center gap-2">
|
|
||||||
<Search className="h-5 w-5" />
|
|
||||||
DuckDuckGo Search Integration
|
|
||||||
</CardTitle>
|
|
||||||
<CardDescription>
|
|
||||||
Configure anonymous web search settings provided by DuckDuckGo.
|
|
||||||
</CardDescription>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<Switch
|
|
||||||
checked={config.enabled}
|
|
||||||
onCheckedChange={(checked) => setConfig({ ...config, enabled: checked })}
|
|
||||||
id="search-enabled"
|
|
||||||
/>
|
|
||||||
<Label htmlFor="search-enabled">Enabled</Label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-4">
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="region">Region</Label>
|
|
||||||
<Select
|
|
||||||
value={config.region}
|
|
||||||
onValueChange={(val) => setConfig({ ...config, region: val })}
|
|
||||||
>
|
|
||||||
<SelectTrigger id="region">
|
|
||||||
<SelectValue placeholder="Select region" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="wt-wt">Global (wt-wt)</SelectItem>
|
|
||||||
<SelectItem value="us-en">United States (us-en)</SelectItem>
|
|
||||||
<SelectItem value="uk-en">United Kingdom (uk-en)</SelectItem>
|
|
||||||
<SelectItem value="br-pt">Brazil (br-pt)</SelectItem>
|
|
||||||
<SelectItem value="de-de">Germany (de-de)</SelectItem>
|
|
||||||
<SelectItem value="fr-fr">France (fr-fr)</SelectItem>
|
|
||||||
<SelectItem value="es-es">Spain (es-es)</SelectItem>
|
|
||||||
<SelectItem value="it-it">Italy (it-it)</SelectItem>
|
|
||||||
<SelectItem value="jp-jp">Japan (jp-jp)</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="safe-search" className="flex items-center gap-2">
|
|
||||||
<Shield className="h-3 w-3" /> Safe Search
|
|
||||||
</Label>
|
|
||||||
<Select
|
|
||||||
value={config.safe_search}
|
|
||||||
onValueChange={(val) => setConfig({ ...config, safe_search: val })}
|
|
||||||
>
|
|
||||||
<SelectTrigger id="safe-search">
|
|
||||||
<SelectValue placeholder="Select safe search level" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="on">Strict (On)</SelectItem>
|
|
||||||
<SelectItem value="moderate">Moderate</SelectItem>
|
|
||||||
<SelectItem value="off">Off</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="max-results">Max Results</Label>
|
|
||||||
<Input
|
|
||||||
id="max-results"
|
|
||||||
type="number"
|
|
||||||
value={config.max_results}
|
|
||||||
onChange={(e) => setConfig({ ...config, max_results: parseInt(e.target.value) || 10 })}
|
|
||||||
min={1}
|
|
||||||
max={50}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="retention">Log Retention (days)</Label>
|
|
||||||
<Input
|
|
||||||
id="retention"
|
|
||||||
type="number"
|
|
||||||
value={config.retention_days}
|
|
||||||
onChange={(e) => setConfig({ ...config, retention_days: parseInt(e.target.value) || 30 })}
|
|
||||||
min={1}
|
|
||||||
max={365}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-4 pt-4 border-t">
|
|
||||||
<h3 className="text-sm font-medium">Privacy</h3>
|
|
||||||
<div className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm">
|
|
||||||
<div className="space-y-0.5">
|
|
||||||
<Label className="text-sm">Log Search Content</Label>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
Store query text in local history
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Switch
|
|
||||||
checked={config.log_search_content}
|
|
||||||
onCheckedChange={(checked) => setConfig({ ...config, log_search_content: checked })}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-end pt-4">
|
|
||||||
<Button onClick={handleSave} disabled={isSaving}>
|
|
||||||
{isSaving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Save className="mr-2 h-4 w-4" />}
|
|
||||||
Save Settings
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,881 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Label } from '@/components/ui/label';
|
|
||||||
import { Checkbox } from '@/components/ui/checkbox';
|
|
||||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import { Progress } from '@/components/ui/progress';
|
|
||||||
import {
|
|
||||||
CheckCircle2,
|
|
||||||
XCircle,
|
|
||||||
Loader2,
|
|
||||||
ArrowLeft,
|
|
||||||
ArrowRight,
|
|
||||||
AlertCircle,
|
|
||||||
ExternalLink,
|
|
||||||
Download,
|
|
||||||
Settings,
|
|
||||||
Play,
|
|
||||||
Square,
|
|
||||||
X
|
|
||||||
} from 'lucide-react';
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
|
||||||
import { listen } from '@tauri-apps/api/event';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
|
|
||||||
interface SearxngInstallWizardProps {
|
|
||||||
onComplete: () => void;
|
|
||||||
onCancel: () => void;
|
|
||||||
initialUrl?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
type Step = 0 | 1 | 2 | 3 | 4 | 5;
|
|
||||||
|
|
||||||
interface SystemRequirements {
|
|
||||||
status: 'pass' | 'fail' | 'warn';
|
|
||||||
os: string;
|
|
||||||
arch: string;
|
|
||||||
ram_mb: number;
|
|
||||||
disk_gb: number;
|
|
||||||
cpu_cores: number;
|
|
||||||
kernel_version?: string;
|
|
||||||
issues: string[];
|
|
||||||
warnings: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface InstallProgressEvent {
|
|
||||||
event_type: 'step_start' | 'log' | 'step_complete' | 'error' | 'complete';
|
|
||||||
step?: number;
|
|
||||||
step_name?: string;
|
|
||||||
total_steps?: number;
|
|
||||||
progress: number;
|
|
||||||
message?: string;
|
|
||||||
log_line?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ValidationResult {
|
|
||||||
status: 'pass' | 'fail' | 'partial';
|
|
||||||
tests: Array<{
|
|
||||||
name: string;
|
|
||||||
status: 'pass' | 'fail' | 'warn';
|
|
||||||
message?: string;
|
|
||||||
}>;
|
|
||||||
docker_version?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SearxngInstallWizard({ onComplete, onCancel, initialUrl = 'http://localhost:8080' }: SearxngInstallWizardProps) {
|
|
||||||
const [currentStep, setCurrentStep] = useState<Step>(0);
|
|
||||||
const [requirements, setRequirements] = useState<SystemRequirements | null>(null);
|
|
||||||
const [isCheckingRequirements, setIsCheckingRequirements] = useState(false);
|
|
||||||
const [dockerAvailable, setDockerAvailable] = useState<boolean | null>(null);
|
|
||||||
const [dockerRunning, setDockerRunning] = useState<boolean | null>(null);
|
|
||||||
const [isChecking, setIsChecking] = useState(false);
|
|
||||||
const [url, setUrl] = useState(initialUrl);
|
|
||||||
const [port, setPort] = useState('8080');
|
|
||||||
const [autoStart, setAutoStart] = useState(true);
|
|
||||||
const [installProgress, setInstallProgress] = useState<string>('');
|
|
||||||
const [isInstalling, setIsInstalling] = useState(false);
|
|
||||||
const [installError, setInstallError] = useState<string | null>(null);
|
|
||||||
const [dockerInstallProgress, setDockerInstallProgress] = useState<{
|
|
||||||
currentStep: number;
|
|
||||||
totalSteps: number;
|
|
||||||
progress: number;
|
|
||||||
currentStepName: string;
|
|
||||||
logs: string[];
|
|
||||||
}>({
|
|
||||||
currentStep: 0,
|
|
||||||
totalSteps: 0,
|
|
||||||
progress: 0,
|
|
||||||
currentStepName: '',
|
|
||||||
logs: [],
|
|
||||||
});
|
|
||||||
const [isInstallingDocker, setIsInstallingDocker] = useState(false);
|
|
||||||
const [validationResult, setValidationResult] = useState<ValidationResult | null>(null);
|
|
||||||
const [isValidating, setIsValidating] = useState(false);
|
|
||||||
const [verificationStatus, setVerificationStatus] = useState<'checking' | 'success' | 'error' | null>(null);
|
|
||||||
const [verificationError, setVerificationError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
// Step 0: Verificar Requisitos
|
|
||||||
useEffect(() => {
|
|
||||||
if (currentStep === 0) {
|
|
||||||
checkRequirements();
|
|
||||||
}
|
|
||||||
}, [currentStep]);
|
|
||||||
|
|
||||||
// Step 1: Verificar Docker
|
|
||||||
useEffect(() => {
|
|
||||||
if (currentStep === 1) {
|
|
||||||
checkDocker();
|
|
||||||
}
|
|
||||||
}, [currentStep]);
|
|
||||||
|
|
||||||
// Listener de eventos de progresso Docker
|
|
||||||
useEffect(() => {
|
|
||||||
let unlistenPromise: Promise<() => void> | null = null;
|
|
||||||
|
|
||||||
if (isInstallingDocker) {
|
|
||||||
unlistenPromise = listen<InstallProgressEvent>('docker-install-progress', (event) => {
|
|
||||||
const data = event.payload;
|
|
||||||
|
|
||||||
switch (data.event_type) {
|
|
||||||
case 'step_start':
|
|
||||||
setDockerInstallProgress(prev => ({
|
|
||||||
...prev,
|
|
||||||
currentStep: data.step || 0,
|
|
||||||
totalSteps: data.total_steps || prev.totalSteps,
|
|
||||||
currentStepName: data.step_name || '',
|
|
||||||
progress: data.progress,
|
|
||||||
}));
|
|
||||||
if (data.message) {
|
|
||||||
setDockerInstallProgress(prev => ({
|
|
||||||
...prev,
|
|
||||||
logs: [...prev.logs.slice(-49), data.message!],
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'log':
|
|
||||||
if (data.log_line) {
|
|
||||||
setDockerInstallProgress(prev => ({
|
|
||||||
...prev,
|
|
||||||
logs: [...prev.logs.slice(-49), data.log_line!],
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'step_complete':
|
|
||||||
setDockerInstallProgress(prev => ({
|
|
||||||
...prev,
|
|
||||||
progress: data.progress,
|
|
||||||
}));
|
|
||||||
if (data.message) {
|
|
||||||
setDockerInstallProgress(prev => ({
|
|
||||||
...prev,
|
|
||||||
logs: [...prev.logs.slice(-49), data.message!],
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'error':
|
|
||||||
setInstallError(data.message || 'Erro desconhecido');
|
|
||||||
setIsInstallingDocker(false);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'complete':
|
|
||||||
setDockerInstallProgress(prev => ({ ...prev, progress: 100 }));
|
|
||||||
setIsInstallingDocker(false);
|
|
||||||
// Validar instalação após conclusão
|
|
||||||
setTimeout(() => {
|
|
||||||
validateDocker();
|
|
||||||
}, 1000);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
if (unlistenPromise) {
|
|
||||||
unlistenPromise.then(fn => fn());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, [isInstallingDocker]);
|
|
||||||
|
|
||||||
const checkRequirements = async () => {
|
|
||||||
setIsCheckingRequirements(true);
|
|
||||||
try {
|
|
||||||
const reqs = await invoke<SystemRequirements>('check_docker_requirements');
|
|
||||||
setRequirements(reqs);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error checking requirements:', error);
|
|
||||||
setRequirements({
|
|
||||||
status: 'fail',
|
|
||||||
os: 'unknown',
|
|
||||||
arch: 'unknown',
|
|
||||||
ram_mb: 0,
|
|
||||||
disk_gb: 0,
|
|
||||||
cpu_cores: 0,
|
|
||||||
issues: ['Erro ao verificar requisitos do sistema'],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsCheckingRequirements(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const checkDocker = async () => {
|
|
||||||
setIsChecking(true);
|
|
||||||
try {
|
|
||||||
const available = await invoke<boolean>('check_docker_available');
|
|
||||||
setDockerAvailable(available);
|
|
||||||
|
|
||||||
if (available) {
|
|
||||||
const running = await invoke<boolean>('check_docker_running');
|
|
||||||
setDockerRunning(running);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error checking Docker:', error);
|
|
||||||
setDockerAvailable(false);
|
|
||||||
setDockerRunning(false);
|
|
||||||
} finally {
|
|
||||||
setIsChecking(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleNext = () => {
|
|
||||||
if (currentStep < 5) {
|
|
||||||
setCurrentStep((prev) => (prev + 1) as Step);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleBack = () => {
|
|
||||||
if (currentStep > 0) {
|
|
||||||
setCurrentStep((prev) => (prev - 1) as Step);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleInstallDocker = async () => {
|
|
||||||
setIsInstallingDocker(true);
|
|
||||||
setInstallError(null);
|
|
||||||
setDockerInstallProgress({
|
|
||||||
currentStep: 0,
|
|
||||||
totalSteps: 0,
|
|
||||||
progress: 0,
|
|
||||||
currentStepName: '',
|
|
||||||
logs: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
await invoke('install_docker');
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Docker installation error:', error);
|
|
||||||
setInstallError(error instanceof Error ? error.message : 'Erro desconhecido durante instalação do Docker');
|
|
||||||
setIsInstallingDocker(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const validateDocker = async () => {
|
|
||||||
setIsValidating(true);
|
|
||||||
setValidationResult(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await invoke<ValidationResult>('validate_docker_installation');
|
|
||||||
setValidationResult(result);
|
|
||||||
|
|
||||||
if (result.status === 'pass' || result.status === 'partial') {
|
|
||||||
// Docker validado, atualizar estado
|
|
||||||
setDockerAvailable(true);
|
|
||||||
setDockerRunning(true);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Validation error:', error);
|
|
||||||
setValidationResult({
|
|
||||||
status: 'fail',
|
|
||||||
tests: [{
|
|
||||||
name: 'Validação',
|
|
||||||
status: 'fail',
|
|
||||||
message: error instanceof Error ? error.message : 'Erro ao validar Docker',
|
|
||||||
}],
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsValidating(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleInstall = async () => {
|
|
||||||
setIsInstalling(true);
|
|
||||||
setInstallError(null);
|
|
||||||
setInstallProgress('Iniciando instalação...');
|
|
||||||
|
|
||||||
try {
|
|
||||||
setInstallProgress('Baixando imagem SearXNG...');
|
|
||||||
await invoke('install_searxng', { url, port: parseInt(port, 10) });
|
|
||||||
|
|
||||||
setInstallProgress('Criando container...');
|
|
||||||
// Installation is handled by install_searxng command
|
|
||||||
|
|
||||||
setInstallProgress('Iniciando serviços...');
|
|
||||||
await invoke('start_searxng');
|
|
||||||
|
|
||||||
setInstallProgress('Instalação concluída!');
|
|
||||||
setTimeout(() => {
|
|
||||||
handleNext();
|
|
||||||
}, 1000);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Installation error:', error);
|
|
||||||
setInstallError(error instanceof Error ? error.message : 'Erro desconhecido durante instalação');
|
|
||||||
} finally {
|
|
||||||
setIsInstalling(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleVerify = async () => {
|
|
||||||
setVerificationStatus('checking');
|
|
||||||
setVerificationError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const isAvailable = await invoke<boolean>('check_searxng_status', { url });
|
|
||||||
|
|
||||||
if (isAvailable) {
|
|
||||||
setVerificationStatus('success');
|
|
||||||
setTimeout(() => {
|
|
||||||
onComplete();
|
|
||||||
}, 1500);
|
|
||||||
} else {
|
|
||||||
setVerificationStatus('error');
|
|
||||||
setVerificationError('SearXNG não está respondendo. Verifique se o container está rodando.');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
setVerificationStatus('error');
|
|
||||||
setVerificationError(error instanceof Error ? error.message : 'Erro ao verificar SearXNG');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const renderStep = () => {
|
|
||||||
switch (currentStep) {
|
|
||||||
case 0:
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div className="text-center space-y-2">
|
|
||||||
<h3 className="text-lg font-semibold">Verificação de Requisitos do Sistema</h3>
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
Verificando se seu sistema atende aos requisitos para instalação do Docker.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isCheckingRequirements ? (
|
|
||||||
<div className="flex items-center justify-center py-8">
|
|
||||||
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
|
||||||
<span className="ml-3 text-sm text-muted-foreground">Verificando requisitos...</span>
|
|
||||||
</div>
|
|
||||||
) : requirements ? (
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="p-4 rounded-lg border bg-muted/30">
|
|
||||||
<div className="flex items-center justify-between mb-4">
|
|
||||||
<span className="font-medium text-lg">Status Geral</span>
|
|
||||||
{requirements.status === 'pass' ? (
|
|
||||||
<Badge className="bg-green-500">Compatível</Badge>
|
|
||||||
) : requirements.status === 'warn' ? (
|
|
||||||
<Badge className="bg-yellow-500">Avisos</Badge>
|
|
||||||
) : (
|
|
||||||
<Badge className="bg-red-500">Incompatível</Badge>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-4 mt-4">
|
|
||||||
<div>
|
|
||||||
<p className="text-xs text-muted-foreground">Sistema Operacional</p>
|
|
||||||
<p className="font-medium">{requirements.os} ({requirements.arch})</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="text-xs text-muted-foreground">RAM</p>
|
|
||||||
<p className="font-medium">{(requirements.ram_mb / 1024).toFixed(1)} GB</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="text-xs text-muted-foreground">Disco Livre</p>
|
|
||||||
<p className="font-medium">{requirements.disk_gb} GB</p>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="text-xs text-muted-foreground">CPU Cores</p>
|
|
||||||
<p className="font-medium">{requirements.cpu_cores}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{requirements.kernel_version && (
|
|
||||||
<div className="mt-4">
|
|
||||||
<p className="text-xs text-muted-foreground">Versão do Kernel</p>
|
|
||||||
<p className="font-medium">{requirements.kernel_version}</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{requirements.issues.length > 0 && (
|
|
||||||
<Alert variant="destructive">
|
|
||||||
<AlertCircle className="w-4 h-4" />
|
|
||||||
<AlertDescription>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<p className="font-medium">Problemas Encontrados:</p>
|
|
||||||
<ul className="list-disc list-inside space-y-1 text-sm">
|
|
||||||
{requirements.issues.map((issue, idx) => (
|
|
||||||
<li key={idx}>{issue}</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</AlertDescription>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{requirements.warnings.length > 0 && (
|
|
||||||
<Alert>
|
|
||||||
<AlertCircle className="w-4 h-4" />
|
|
||||||
<AlertDescription>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<p className="font-medium">Avisos:</p>
|
|
||||||
<ul className="list-disc list-inside space-y-1 text-sm">
|
|
||||||
{requirements.warnings.map((warning, idx) => (
|
|
||||||
<li key={idx}>{warning}</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</AlertDescription>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex gap-3">
|
|
||||||
<Button variant="outline" onClick={checkRequirements} disabled={isCheckingRequirements}>
|
|
||||||
Verificar Novamente
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={handleNext}
|
|
||||||
disabled={requirements.status === 'fail'}
|
|
||||||
className="ml-auto"
|
|
||||||
>
|
|
||||||
Continuar
|
|
||||||
<ArrowRight className="w-4 h-4 ml-2" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
case 1:
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div className="text-center space-y-2">
|
|
||||||
<h3 className="text-lg font-semibold">Verificação de Docker</h3>
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
SearXNG requer Docker para funcionar. Vamos verificar se está instalado e rodando.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isChecking ? (
|
|
||||||
<div className="flex items-center justify-center py-8">
|
|
||||||
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
|
||||||
<span className="ml-3 text-sm text-muted-foreground">Verificando Docker...</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="p-4 rounded-lg border bg-muted/30">
|
|
||||||
<div className="flex items-center justify-between mb-2">
|
|
||||||
<span className="font-medium">Docker Instalado</span>
|
|
||||||
{dockerAvailable === null ? (
|
|
||||||
<Loader2 className="w-4 h-4 animate-spin" />
|
|
||||||
) : dockerAvailable ? (
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-green-500" />
|
|
||||||
) : (
|
|
||||||
<XCircle className="w-5 h-5 text-red-500" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{dockerAvailable === false && (
|
|
||||||
<p className="text-xs text-muted-foreground mt-2">
|
|
||||||
Docker não está instalado. Você precisa instalá-lo primeiro.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{dockerAvailable && (
|
|
||||||
<div className="p-4 rounded-lg border bg-muted/30">
|
|
||||||
<div className="flex items-center justify-between mb-2">
|
|
||||||
<span className="font-medium">Docker Rodando</span>
|
|
||||||
{dockerRunning === null ? (
|
|
||||||
<Loader2 className="w-4 h-4 animate-spin" />
|
|
||||||
) : dockerRunning ? (
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-green-500" />
|
|
||||||
) : (
|
|
||||||
<XCircle className="w-5 h-5 text-red-500" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{dockerRunning === false && (
|
|
||||||
<p className="text-xs text-muted-foreground mt-2">
|
|
||||||
Docker está instalado mas não está rodando. Inicie o Docker Desktop.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{dockerAvailable === false && (
|
|
||||||
<Alert>
|
|
||||||
<AlertCircle className="w-4 h-4" />
|
|
||||||
<AlertDescription>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<p>Docker não está instalado. Você pode instalá-lo agora ou manualmente.</p>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Button
|
|
||||||
variant="default"
|
|
||||||
size="sm"
|
|
||||||
onClick={handleInstallDocker}
|
|
||||||
disabled={isInstallingDocker}
|
|
||||||
>
|
|
||||||
{isInstallingDocker ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
|
||||||
Instalando...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Download className="w-4 h-4 mr-2" />
|
|
||||||
Instalar Docker Agora
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => {
|
|
||||||
window.open('https://www.docker.com/products/docker-desktop', '_blank');
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<ExternalLink className="w-4 h-4 mr-2" />
|
|
||||||
Instalar Manualmente
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</AlertDescription>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{isInstallingDocker && (
|
|
||||||
<div className="space-y-4 mt-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex items-center justify-between text-sm">
|
|
||||||
<span>{dockerInstallProgress.currentStepName || 'Instalando Docker...'}</span>
|
|
||||||
<span>{dockerInstallProgress.progress}%</span>
|
|
||||||
</div>
|
|
||||||
<Progress value={dockerInstallProgress.progress} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{dockerInstallProgress.logs.length > 0 && (
|
|
||||||
<div className="bg-black text-green-400 font-mono text-xs p-4 rounded-lg h-48 overflow-y-auto">
|
|
||||||
{dockerInstallProgress.logs.map((log, idx) => (
|
|
||||||
<div key={idx}>{log}</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{validationResult && (
|
|
||||||
<div className="space-y-2 mt-4">
|
|
||||||
<h4 className="font-medium">Resultados da Validação:</h4>
|
|
||||||
{validationResult.tests.map((test, idx) => (
|
|
||||||
<div key={idx} className="flex items-center justify-between p-2 rounded border bg-muted/30">
|
|
||||||
<span className="text-sm">{test.name}</span>
|
|
||||||
{test.status === 'pass' ? (
|
|
||||||
<CheckCircle2 className="w-4 h-4 text-green-500" />
|
|
||||||
) : test.status === 'warn' ? (
|
|
||||||
<AlertCircle className="w-4 h-4 text-yellow-500" />
|
|
||||||
) : (
|
|
||||||
<XCircle className="w-4 h-4 text-red-500" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
{validationResult.docker_version && (
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
Docker {validationResult.docker_version} instalado
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex gap-3">
|
|
||||||
<Button variant="outline" onClick={checkDocker} disabled={isChecking}>
|
|
||||||
Verificar Novamente
|
|
||||||
</Button>
|
|
||||||
{validationResult && (validationResult.status === 'pass' || validationResult.status === 'partial') && (
|
|
||||||
<Button
|
|
||||||
onClick={handleNext}
|
|
||||||
className="ml-auto"
|
|
||||||
>
|
|
||||||
Continuar
|
|
||||||
<ArrowRight className="w-4 h-4 ml-2" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{!validationResult && dockerAvailable && dockerRunning && (
|
|
||||||
<Button
|
|
||||||
onClick={handleNext}
|
|
||||||
className="ml-auto"
|
|
||||||
>
|
|
||||||
Continuar
|
|
||||||
<ArrowRight className="w-4 h-4 ml-2" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{!dockerAvailable && !isInstallingDocker && (
|
|
||||||
<Button
|
|
||||||
onClick={handleNext}
|
|
||||||
variant="outline"
|
|
||||||
className="ml-auto"
|
|
||||||
>
|
|
||||||
Pular Instalação Docker
|
|
||||||
<ArrowRight className="w-4 h-4 ml-2" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
case 2:
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div className="text-center space-y-2">
|
|
||||||
<h3 className="text-lg font-semibold">Configuração</h3>
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
Configure a URL e porta onde SearXNG será acessível.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="searxng-url">URL do SearXNG</Label>
|
|
||||||
<Input
|
|
||||||
id="searxng-url"
|
|
||||||
value={url}
|
|
||||||
onChange={(e) => setUrl(e.target.value)}
|
|
||||||
placeholder="http://localhost:8080"
|
|
||||||
/>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
URL completa onde o SearXNG estará acessível
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="searxng-port">Porta</Label>
|
|
||||||
<Input
|
|
||||||
id="searxng-port"
|
|
||||||
type="number"
|
|
||||||
value={port}
|
|
||||||
onChange={(e) => setPort(e.target.value)}
|
|
||||||
placeholder="8080"
|
|
||||||
min="1024"
|
|
||||||
max="65535"
|
|
||||||
/>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
Porta que será usada pelo container (padrão: 8080)
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center space-x-2 p-4 rounded-lg border bg-muted/30">
|
|
||||||
<Checkbox
|
|
||||||
id="auto-start"
|
|
||||||
checked={autoStart}
|
|
||||||
onCheckedChange={(checked) => setAutoStart(checked === true)}
|
|
||||||
/>
|
|
||||||
<Label htmlFor="auto-start" className="cursor-pointer">
|
|
||||||
Iniciar automaticamente com o OllaHub
|
|
||||||
</Label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex gap-3">
|
|
||||||
<Button variant="outline" onClick={handleBack}>
|
|
||||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
|
||||||
Voltar
|
|
||||||
</Button>
|
|
||||||
<Button onClick={handleNext} className="ml-auto">
|
|
||||||
Continuar
|
|
||||||
<ArrowRight className="w-4 h-4 ml-2" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
case 3:
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div className="text-center space-y-2">
|
|
||||||
<h3 className="text-lg font-semibold">Instalação do SearXNG</h3>
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
Instalando e configurando SearXNG. Isso pode levar alguns minutos.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isInstalling ? (
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="p-4 rounded-lg border bg-muted/30">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<Loader2 className="w-5 h-5 animate-spin text-primary" />
|
|
||||||
<div className="flex-1">
|
|
||||||
<p className="font-medium">{installProgress}</p>
|
|
||||||
<div className="mt-2 h-2 bg-muted rounded-full overflow-hidden">
|
|
||||||
<div className="h-full bg-primary animate-pulse" style={{ width: '60%' }} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : installError ? (
|
|
||||||
<Alert variant="destructive">
|
|
||||||
<XCircle className="w-4 h-4" />
|
|
||||||
<AlertDescription>
|
|
||||||
<p className="font-medium mb-2">Erro durante instalação</p>
|
|
||||||
<p className="text-sm">{installError}</p>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={handleInstall}
|
|
||||||
className="mt-3"
|
|
||||||
>
|
|
||||||
Tentar Novamente
|
|
||||||
</Button>
|
|
||||||
</AlertDescription>
|
|
||||||
</Alert>
|
|
||||||
) : (
|
|
||||||
<div className="p-4 rounded-lg border bg-green-500/10 border-green-500/20">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-green-500" />
|
|
||||||
<div>
|
|
||||||
<p className="font-medium">Instalação concluída!</p>
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
SearXNG foi instalado com sucesso.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex gap-3">
|
|
||||||
<Button variant="outline" onClick={handleBack} disabled={isInstalling}>
|
|
||||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
|
||||||
Voltar
|
|
||||||
</Button>
|
|
||||||
{!isInstalling && !installError && (
|
|
||||||
<Button onClick={handleNext} className="ml-auto">
|
|
||||||
Continuar
|
|
||||||
<ArrowRight className="w-4 h-4 ml-2" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{isInstalling && (
|
|
||||||
<Button variant="outline" onClick={onCancel} className="ml-auto">
|
|
||||||
Cancelar
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
case 5:
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div className="text-center space-y-2">
|
|
||||||
<h3 className="text-lg font-semibold">Verificação</h3>
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
Verificando se SearXNG está funcionando corretamente.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{verificationStatus === null && (
|
|
||||||
<div className="p-4 rounded-lg border bg-muted/30 text-center">
|
|
||||||
<p className="text-sm text-muted-foreground mb-4">
|
|
||||||
Clique em "Verificar" para testar a conexão com SearXNG.
|
|
||||||
</p>
|
|
||||||
<Button onClick={handleVerify} size="lg">
|
|
||||||
<Play className="w-4 h-4 mr-2" />
|
|
||||||
Verificar
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{verificationStatus === 'checking' && (
|
|
||||||
<div className="p-4 rounded-lg border bg-muted/30">
|
|
||||||
<div className="flex items-center justify-center gap-3">
|
|
||||||
<Loader2 className="w-5 h-5 animate-spin text-primary" />
|
|
||||||
<span>Verificando conexão...</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{verificationStatus === 'success' && (
|
|
||||||
<div className="p-4 rounded-lg border bg-green-500/10 border-green-500/20">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-green-500" />
|
|
||||||
<div>
|
|
||||||
<p className="font-medium">SearXNG está disponível!</p>
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
A conexão foi estabelecida com sucesso.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{verificationStatus === 'error' && (
|
|
||||||
<Alert variant="destructive">
|
|
||||||
<XCircle className="w-4 h-4" />
|
|
||||||
<AlertDescription>
|
|
||||||
<p className="font-medium mb-2">Falha na verificação</p>
|
|
||||||
<p className="text-sm mb-3">{verificationError || 'SearXNG não está respondendo'}</p>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Button variant="outline" size="sm" onClick={handleVerify}>
|
|
||||||
Tentar Novamente
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={async () => {
|
|
||||||
try {
|
|
||||||
await invoke('start_searxng');
|
|
||||||
setTimeout(handleVerify, 2000);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error starting SearXNG:', error);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Play className="w-4 h-4 mr-2" />
|
|
||||||
Iniciar Container
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</AlertDescription>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex gap-3">
|
|
||||||
<Button variant="outline" onClick={handleBack} disabled={verificationStatus === 'checking'}>
|
|
||||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
|
||||||
Voltar
|
|
||||||
</Button>
|
|
||||||
{verificationStatus === 'success' && (
|
|
||||||
<Button onClick={onComplete} className="ml-auto">
|
|
||||||
Concluir
|
|
||||||
<CheckCircle2 className="w-4 h-4 ml-2" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
|
|
||||||
<Card className="w-full max-w-2xl relative">
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
onClick={onCancel}
|
|
||||||
className="absolute top-2 right-2 sm:top-4 sm:right-4 z-10"
|
|
||||||
aria-label="Fechar"
|
|
||||||
disabled={isInstalling || isInstallingDocker}
|
|
||||||
>
|
|
||||||
<X className="w-4 h-4" />
|
|
||||||
</Button>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>SearXNG - Instalação</CardTitle>
|
|
||||||
<CardDescription>
|
|
||||||
Passo {currentStep + 1} de 6
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
{renderStep()}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,186 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { CheckCircle2, Shield, Infinity, Globe, Settings, ArrowRight, X, ExternalLink } from 'lucide-react';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
|
|
||||||
interface SearxngOnboardingProps {
|
|
||||||
onInstall: () => void;
|
|
||||||
onSkip: () => void;
|
|
||||||
onLearnMore?: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SearxngOnboarding({ onInstall, onSkip, onLearnMore }: SearxngOnboardingProps) {
|
|
||||||
const benefits = [
|
|
||||||
{
|
|
||||||
icon: Infinity,
|
|
||||||
title: 'Sem limites de queries',
|
|
||||||
description: 'Enquanto Brave API oferece 2000 queries/mês, SearXNG é ilimitado',
|
|
||||||
color: 'text-green-500',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
icon: Shield,
|
|
||||||
title: 'Privacidade total',
|
|
||||||
description: 'Sem rastreamento, sem cookies, sem logs. Seus dados ficam privados',
|
|
||||||
color: 'text-blue-500',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
icon: Globe,
|
|
||||||
title: 'Agrega múltiplos motores',
|
|
||||||
description: 'Combina resultados de Google, Bing, DuckDuckGo e outros em uma única busca',
|
|
||||||
color: 'text-purple-500',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
icon: Settings,
|
|
||||||
title: 'Controle total',
|
|
||||||
description: 'Configure motores, filtros e personalizações conforme sua necessidade',
|
|
||||||
color: 'text-orange-500',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
|
|
||||||
<Card className="w-full max-w-3xl max-h-[90vh] overflow-y-auto relative">
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
onClick={onSkip}
|
|
||||||
className="absolute top-2 right-2 sm:top-4 sm:right-4 z-10"
|
|
||||||
aria-label="Fechar"
|
|
||||||
>
|
|
||||||
<X className="w-4 h-4" />
|
|
||||||
</Button>
|
|
||||||
<CardHeader className="text-center space-y-4 pb-6">
|
|
||||||
<div className="mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
|
|
||||||
<Globe className="w-8 h-8 text-primary" />
|
|
||||||
</div>
|
|
||||||
<CardTitle className="text-2xl sm:text-3xl">SearXNG Self-Hosted</CardTitle>
|
|
||||||
<CardDescription className="text-base">
|
|
||||||
Busca Ilimitada e Privada
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
|
|
||||||
<CardContent className="space-y-6">
|
|
||||||
{/* Por que SearXNG? */}
|
|
||||||
<div className="space-y-4">
|
|
||||||
<h3 className="text-lg font-semibold flex items-center gap-2">
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-green-500" />
|
|
||||||
Por que SearXNG?
|
|
||||||
</h3>
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
||||||
{benefits.map((benefit, idx) => {
|
|
||||||
const Icon = benefit.icon;
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={idx}
|
|
||||||
className="p-4 rounded-lg border border-muted bg-muted/30 hover:bg-muted/50 transition-colors"
|
|
||||||
>
|
|
||||||
<div className="flex items-start gap-3">
|
|
||||||
<Icon className={cn('w-5 h-5 mt-0.5 flex-shrink-0', benefit.color)} />
|
|
||||||
<div className="space-y-1 flex-1">
|
|
||||||
<h4 className="font-medium text-sm">{benefit.title}</h4>
|
|
||||||
<p className="text-xs text-muted-foreground">{benefit.description}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Como Funciona */}
|
|
||||||
<div className="space-y-4">
|
|
||||||
<h3 className="text-lg font-semibold flex items-center gap-2">
|
|
||||||
<Globe className="w-5 h-5 text-blue-500" />
|
|
||||||
Como Funciona
|
|
||||||
</h3>
|
|
||||||
<div className="p-4 rounded-lg border border-muted bg-muted/30">
|
|
||||||
<div className="flex items-center justify-center gap-2 sm:gap-4 flex-wrap">
|
|
||||||
<div className="flex flex-col items-center gap-2">
|
|
||||||
<div className="px-4 py-2 rounded-md bg-blue-500/10 border border-blue-500/20 text-sm font-medium">
|
|
||||||
Brave API
|
|
||||||
</div>
|
|
||||||
<span className="text-xs text-muted-foreground">Tier 1</span>
|
|
||||||
</div>
|
|
||||||
<ArrowRight className="w-5 h-5 text-muted-foreground" />
|
|
||||||
<div className="flex flex-col items-center gap-2">
|
|
||||||
<div className="px-4 py-2 rounded-md bg-green-500/10 border border-green-500/20 text-sm font-medium">
|
|
||||||
SearXNG
|
|
||||||
</div>
|
|
||||||
<span className="text-xs text-muted-foreground">Tier 2</span>
|
|
||||||
</div>
|
|
||||||
<ArrowRight className="w-5 h-5 text-muted-foreground" />
|
|
||||||
<div className="flex flex-col items-center gap-2">
|
|
||||||
<div className="px-4 py-2 rounded-md bg-yellow-500/10 border border-yellow-500/20 text-sm font-medium">
|
|
||||||
DuckDuckGo
|
|
||||||
</div>
|
|
||||||
<span className="text-xs text-muted-foreground">Tier 3</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<p className="text-sm text-muted-foreground mt-4 text-center">
|
|
||||||
SearXNG é usado como fallback quando Brave API esgota sua quota mensal (2000 queries).
|
|
||||||
É completamente opcional e não afeta o uso normal do sistema.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Requisitos */}
|
|
||||||
<div className="space-y-4">
|
|
||||||
<h3 className="text-lg font-semibold flex items-center gap-2">
|
|
||||||
<Settings className="w-5 h-5 text-orange-500" />
|
|
||||||
Requisitos
|
|
||||||
</h3>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex items-start gap-3 p-3 rounded-lg border border-muted bg-muted/30">
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-green-500 mt-0.5 flex-shrink-0" />
|
|
||||||
<div>
|
|
||||||
<p className="font-medium text-sm">Docker instalado e rodando</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
O SearXNG roda em um container Docker. Se não tiver Docker, você pode instalá-lo durante o processo.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-start gap-3 p-3 rounded-lg border border-muted bg-muted/30">
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-green-500 mt-0.5 flex-shrink-0" />
|
|
||||||
<div>
|
|
||||||
<p className="font-medium text-sm">~200MB de RAM</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
O container SearXNG consome aproximadamente 200MB de memória RAM.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-start gap-3 p-3 rounded-lg border border-muted bg-muted/30">
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-green-500 mt-0.5 flex-shrink-0" />
|
|
||||||
<div>
|
|
||||||
<p className="font-medium text-sm">Porta 8080 disponível</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
Por padrão, SearXNG usa a porta 8080. Você pode configurar uma porta diferente se necessário.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Ações */}
|
|
||||||
<div className="flex flex-col sm:flex-row gap-3 pt-4 border-t">
|
|
||||||
<Button onClick={onInstall} className="flex-1" size="lg">
|
|
||||||
<ArrowRight className="w-4 h-4 mr-2" />
|
|
||||||
Instalar Agora
|
|
||||||
</Button>
|
|
||||||
{onLearnMore && (
|
|
||||||
<Button onClick={onLearnMore} variant="outline" className="flex-1" size="lg">
|
|
||||||
<ExternalLink className="w-4 h-4 mr-2" />
|
|
||||||
Saiba Mais
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Button onClick={onSkip} variant="ghost" className="flex-1" size="lg">
|
|
||||||
<X className="w-4 h-4 mr-2" />
|
|
||||||
Pular por Enquanto
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -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,152 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useEffect, useRef, useState } from 'react';
|
|
||||||
import { listen } from '@tauri-apps/api/event';
|
|
||||||
import { Progress } from '@/components/ui/progress';
|
|
||||||
|
|
||||||
interface LogLine {
|
|
||||||
line: string;
|
|
||||||
type: 'stdout' | 'stderr';
|
|
||||||
progress?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface InstallationTerminalProps {
|
|
||||||
onComplete?: () => void;
|
|
||||||
onError?: (error: string) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function InstallationTerminal({ onComplete, onError }: InstallationTerminalProps) {
|
|
||||||
const [logs, setLogs] = useState<LogLine[]>([]);
|
|
||||||
const [progress, setProgress] = useState(0);
|
|
||||||
const scrollRef = useRef<HTMLDivElement>(null);
|
|
||||||
const lastProgressRef = useRef<number>(0);
|
|
||||||
|
|
||||||
// Auto-scroll para última linha
|
|
||||||
useEffect(() => {
|
|
||||||
if (scrollRef.current) {
|
|
||||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
|
||||||
}
|
|
||||||
}, [logs]);
|
|
||||||
|
|
||||||
// Escutar eventos de log
|
|
||||||
useEffect(() => {
|
|
||||||
const unlistenPromise = listen<LogLine>('install-log', (event) => {
|
|
||||||
const logLine = event.payload;
|
|
||||||
|
|
||||||
setLogs(prev => [...prev, logLine]);
|
|
||||||
|
|
||||||
// Atualizar progresso se disponível
|
|
||||||
if (logLine.progress !== undefined) {
|
|
||||||
setProgress(logLine.progress);
|
|
||||||
lastProgressRef.current = logLine.progress;
|
|
||||||
} else {
|
|
||||||
// Tentar extrair progresso da linha de texto
|
|
||||||
const extractedProgress = extractProgressFromText(logLine.line);
|
|
||||||
if (extractedProgress !== null) {
|
|
||||||
setProgress(extractedProgress);
|
|
||||||
lastProgressRef.current = extractedProgress;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verificar se instalação foi concluída
|
|
||||||
const lineLower = logLine.line.toLowerCase();
|
|
||||||
if (lineLower.includes('success') || lineLower.includes('completed') || lineLower.includes('finished')) {
|
|
||||||
setProgress(100);
|
|
||||||
if (onComplete) {
|
|
||||||
setTimeout(() => onComplete(), 500);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verificar se houve erro
|
|
||||||
if (logLine.type === 'stderr' && (lineLower.includes('error') || lineLower.includes('failed'))) {
|
|
||||||
if (onError) {
|
|
||||||
onError(logLine.line);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
unlistenPromise.then(unlisten => unlisten());
|
|
||||||
};
|
|
||||||
}, [onComplete, onError]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-2 sm:space-y-3">
|
|
||||||
<div className="bg-zinc-950 rounded-lg border border-zinc-800 overflow-hidden max-h-[50vh] flex flex-col">
|
|
||||||
<div className="px-2 sm:px-3 py-1.5 sm:py-2 bg-zinc-900 border-b border-zinc-800 flex items-center justify-between gap-2 flex-shrink-0">
|
|
||||||
<div className="flex items-center gap-1.5 sm:gap-2 shrink-0">
|
|
||||||
<div className="w-1.5 h-1.5 sm:w-2 sm:h-2 rounded-full bg-red-500"></div>
|
|
||||||
<div className="w-1.5 h-1.5 sm:w-2 sm:h-2 rounded-full bg-yellow-500"></div>
|
|
||||||
<div className="w-1.5 h-1.5 sm:w-2 sm:h-2 rounded-full bg-green-500"></div>
|
|
||||||
<span className="text-[10px] sm:text-xs text-zinc-400 ml-1 sm:ml-2">Terminal</span>
|
|
||||||
</div>
|
|
||||||
{progress > 0 && (
|
|
||||||
<span className="text-[10px] sm:text-xs text-zinc-400 font-mono shrink-0">{progress}%</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div
|
|
||||||
ref={scrollRef}
|
|
||||||
className="h-48 sm:h-64 md:h-80 flex-1 min-h-0 overflow-y-auto p-2 sm:p-3 font-mono text-[10px] sm:text-xs"
|
|
||||||
style={{
|
|
||||||
scrollbarWidth: 'thin',
|
|
||||||
scrollbarColor: '#3f3f46 #18181b',
|
|
||||||
scrollBehavior: 'smooth'
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{logs.length === 0 ? (
|
|
||||||
<div className="text-zinc-500 text-[10px] sm:text-xs">Aguardando logs...</div>
|
|
||||||
) : (
|
|
||||||
logs.map((log, index) => (
|
|
||||||
<div
|
|
||||||
key={index}
|
|
||||||
className={`
|
|
||||||
${log.type === 'stderr' ? 'text-red-400' : 'text-green-400'}
|
|
||||||
whitespace-pre-wrap
|
|
||||||
break-words
|
|
||||||
`}
|
|
||||||
>
|
|
||||||
{log.line}
|
|
||||||
</div>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{progress > 0 && (
|
|
||||||
<div className="space-y-1">
|
|
||||||
<Progress value={progress} className="h-1.5 sm:h-2" />
|
|
||||||
<div className="text-[10px] sm:text-xs text-muted-foreground text-center">
|
|
||||||
{progress < 100 ? `Instalando... ${progress}%` : 'Instalação concluída'}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extrai progresso percentual de uma linha de texto
|
|
||||||
function extractProgressFromText(line: string): number | null {
|
|
||||||
// Procurar por padrão "Progress: n%" ou "n%"
|
|
||||||
const percentMatch = line.match(/(\d+)%/);
|
|
||||||
if (percentMatch) {
|
|
||||||
const num = parseInt(percentMatch[1], 10);
|
|
||||||
if (num >= 0 && num <= 100) {
|
|
||||||
return num;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mapear keywords para progresso aproximado
|
|
||||||
const lineLower = line.toLowerCase();
|
|
||||||
if (lineLower.includes('downloading')) {
|
|
||||||
return 25;
|
|
||||||
} else if (lineLower.includes('installing')) {
|
|
||||||
return 50;
|
|
||||||
} else if (lineLower.includes('shim') || lineLower.includes('creating')) {
|
|
||||||
return 75;
|
|
||||||
} else if (lineLower.includes('finished') || lineLower.includes('completed') || lineLower.includes('success')) {
|
|
||||||
return 100;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
@@ -1,425 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useEffect, useMemo, useState, useCallback, startTransition } from 'react';
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Progress } from '@/components/ui/progress';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Card, CardContent, CardFooter, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import { useSetupWizard } from '@/hooks/use-setup-wizard';
|
|
||||||
import { useDownloadContext } from '@/contexts/download-context';
|
|
||||||
import { Search, Download, CheckCircle2, AlertCircle, Loader2, Sparkles, ArrowRight } from 'lucide-react';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
|
|
||||||
interface ModelInfo {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
size: string;
|
|
||||||
minRam: number;
|
|
||||||
description?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lista expandida de modelos populares
|
|
||||||
const POPULAR_MODELS: ModelInfo[] = [
|
|
||||||
{ id: 'llama3.2:1b', name: 'Llama 3.2 1B', size: '1.3GB', minRam: 4, description: 'Leve e rápido, ideal para iniciantes' },
|
|
||||||
{ id: 'llama3.2:3b', name: 'Llama 3.2 3B', size: '2.0GB', minRam: 8, description: 'Equilíbrio perfeito entre velocidade e qualidade' },
|
|
||||||
{ id: 'llama3.1:8b', name: 'Llama 3.1 8B', size: '4.7GB', minRam: 16, description: 'Padrão da indústria, alta capacidade' },
|
|
||||||
{ id: 'mistral:latest', name: 'Mistral 7B', size: '4.1GB', minRam: 16, description: 'Excelente para raciocínio e código' },
|
|
||||||
{ id: 'gemma2:9b', name: 'Gemma 2 9B', size: '5.4GB', minRam: 12, description: 'Modelo avançado do Google' },
|
|
||||||
{ id: 'qwen2.5:7b', name: 'Qwen 2.5 7B', size: '4.5GB', minRam: 16, description: 'Multilíngue e versátil' },
|
|
||||||
{ id: 'phi3:mini', name: 'Phi-3 Mini', size: '2.3GB', minRam: 8, description: 'Compacto e eficiente da Microsoft' },
|
|
||||||
{ id: 'deepseek-coder:6.7b', name: 'DeepSeek Coder 6.7B', size: '4.2GB', minRam: 16, description: 'Especializado em programação' },
|
|
||||||
];
|
|
||||||
|
|
||||||
interface ModelDownloadStepProps {
|
|
||||||
onNext: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ModelDownloadStep({ onNext }: ModelDownloadStepProps) {
|
|
||||||
const { state, checkSetupState } = useSetupWizard();
|
|
||||||
const { state: downloadState, startDownload } = useDownloadContext();
|
|
||||||
|
|
||||||
const [searchQuery, setSearchQuery] = useState('');
|
|
||||||
const [customModelInput, setCustomModelInput] = useState('');
|
|
||||||
const [activeModelTag, setActiveModelTag] = useState<string | null>(null);
|
|
||||||
const [installedModels, setInstalledModels] = useState<Set<string>>(new Set());
|
|
||||||
const [customModelInstalled, setCustomModelInstalled] = useState(false);
|
|
||||||
|
|
||||||
// Verificar modelos instalados ao montar
|
|
||||||
useEffect(() => {
|
|
||||||
const checkAllModels = async () => {
|
|
||||||
const installed = new Set<string>();
|
|
||||||
|
|
||||||
// Verificar todos os modelos em paralelo
|
|
||||||
const checks = POPULAR_MODELS.map(async (model) => {
|
|
||||||
try {
|
|
||||||
const isInstalled = await invoke<boolean>('check_if_model_installed_command', { name: model.id });
|
|
||||||
if (isInstalled) {
|
|
||||||
installed.add(model.id);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`Erro ao verificar ${model.id}:`, error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
await Promise.all(checks);
|
|
||||||
startTransition(() => {
|
|
||||||
setInstalledModels(installed);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
checkAllModels();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Verificar modelo customizado quando o usuário digita
|
|
||||||
useEffect(() => {
|
|
||||||
const checkCustomModel = async () => {
|
|
||||||
const modelTag = customModelInput.trim();
|
|
||||||
if (!modelTag) {
|
|
||||||
setCustomModelInstalled(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const isInstalled = await invoke<boolean>('check_if_model_installed_command', { name: modelTag });
|
|
||||||
setCustomModelInstalled(isInstalled);
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`Erro ao verificar modelo customizado ${modelTag}:`, error);
|
|
||||||
setCustomModelInstalled(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Debounce: aguardar 500ms após o usuário parar de digitar
|
|
||||||
const timer = setTimeout(checkCustomModel, 500);
|
|
||||||
return () => clearTimeout(timer);
|
|
||||||
}, [customModelInput]);
|
|
||||||
|
|
||||||
// Filtrar modelos baseado na pesquisa
|
|
||||||
const filteredModels = useMemo(() => {
|
|
||||||
if (!searchQuery.trim()) return POPULAR_MODELS;
|
|
||||||
const query = searchQuery.toLowerCase();
|
|
||||||
return POPULAR_MODELS.filter(
|
|
||||||
model =>
|
|
||||||
model.name.toLowerCase().includes(query) ||
|
|
||||||
model.id.toLowerCase().includes(query) ||
|
|
||||||
model.description?.toLowerCase().includes(query)
|
|
||||||
);
|
|
||||||
}, [searchQuery]);
|
|
||||||
|
|
||||||
// Progresso do download ativo
|
|
||||||
const activeProgress = useMemo(() => {
|
|
||||||
if (!downloadState.isDownloading || downloadState.currentModel !== activeModelTag) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
percent: downloadState.progress.percent,
|
|
||||||
downloaded: downloadState.progress.downloadedBytes,
|
|
||||||
total: downloadState.progress.totalBytes,
|
|
||||||
downloadedFormatted: downloadState.progress.downloadedFormatted,
|
|
||||||
totalFormatted: downloadState.progress.totalFormatted,
|
|
||||||
status: downloadState.progress.status,
|
|
||||||
speed: downloadState.progress.speed,
|
|
||||||
};
|
|
||||||
}, [downloadState, activeModelTag]);
|
|
||||||
|
|
||||||
// Atualizar lista de instalados e limpar activeModelTag quando download completar
|
|
||||||
useEffect(() => {
|
|
||||||
if (downloadState.isSuccess && activeModelTag) {
|
|
||||||
const modelTag = activeModelTag;
|
|
||||||
// Adicionar modelo à lista de instalados usando startTransition para evitar cascading renders
|
|
||||||
startTransition(() => {
|
|
||||||
setInstalledModels(prev => new Set([...prev, modelTag]));
|
|
||||||
// Verificar também o modelo customizado se for o caso
|
|
||||||
if (modelTag === customModelInput.trim()) {
|
|
||||||
setCustomModelInstalled(true);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
// Limpar activeModelTag após um pequeno delay para garantir que o estado foi atualizado
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
setActiveModelTag(null);
|
|
||||||
}, 100);
|
|
||||||
return () => clearTimeout(timer);
|
|
||||||
}
|
|
||||||
}, [downloadState.isSuccess, activeModelTag, customModelInput]);
|
|
||||||
|
|
||||||
// Verificar estado do setup quando download completar
|
|
||||||
useEffect(() => {
|
|
||||||
if (downloadState.isSuccess || (!downloadState.isDownloading && downloadState.progress.percent === 100 && downloadState.progress.status === 'success')) {
|
|
||||||
checkSetupState().catch(console.error);
|
|
||||||
}
|
|
||||||
}, [downloadState.isSuccess, downloadState.isDownloading, downloadState.progress.percent, downloadState.progress.status, checkSetupState]);
|
|
||||||
|
|
||||||
const handleModelDownload = useCallback(async (modelTag: string) => {
|
|
||||||
if (downloadState.isDownloading) {
|
|
||||||
console.warn('Download já em andamento');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setActiveModelTag(modelTag);
|
|
||||||
try {
|
|
||||||
await startDownload(modelTag);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao iniciar download:', error);
|
|
||||||
setActiveModelTag(null);
|
|
||||||
}
|
|
||||||
}, [downloadState.isDownloading, startDownload]);
|
|
||||||
|
|
||||||
const handleCustomDownload = useCallback(async () => {
|
|
||||||
const modelTag = customModelInput.trim();
|
|
||||||
if (!modelTag) return;
|
|
||||||
|
|
||||||
await handleModelDownload(modelTag);
|
|
||||||
setCustomModelInput('');
|
|
||||||
}, [customModelInput, handleModelDownload]);
|
|
||||||
|
|
||||||
if (state.modelDownloaded) {
|
|
||||||
return (
|
|
||||||
<Card className="w-full max-w-2xl mx-auto border-zinc-800 bg-zinc-950/50 backdrop-blur-sm shadow-2xl">
|
|
||||||
<CardHeader className="p-6 sm:p-8">
|
|
||||||
<CardTitle className="text-2xl font-bold text-white flex items-center gap-2 mb-2">
|
|
||||||
<CheckCircle2 className="w-6 h-6 text-emerald-500 shrink-0" />
|
|
||||||
<span>Modelo Instalado</span>
|
|
||||||
</CardTitle>
|
|
||||||
<CardDescription className="text-zinc-400 mb-8 text-base">
|
|
||||||
Modelo {state.modelName || 'padrão'} pronto para uso.
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="px-6 sm:px-8 pb-6 sm:pb-8 pt-0 space-y-6">
|
|
||||||
<div className="flex items-start sm:items-center gap-3 p-4 bg-emerald-950/30 rounded-lg border border-emerald-900/50">
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-emerald-400 shrink-0" />
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm font-medium text-emerald-100">Download concluído com sucesso!</p>
|
|
||||||
<p className="text-xs text-emerald-300 mt-1">Avançando para o próximo passo...</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className="w-full max-w-6xl mx-auto border-zinc-800 bg-zinc-950/50 backdrop-blur-sm shadow-2xl max-h-[calc(100vh-20rem)] flex flex-col">
|
|
||||||
<CardHeader className="p-6 sm:p-8 flex-shrink-0">
|
|
||||||
<CardTitle className="text-xl font-bold text-white flex items-center gap-2 mb-1">
|
|
||||||
<Download className="w-6 h-6 shrink-0" />
|
|
||||||
<span>Download do Modelo</span>
|
|
||||||
</CardTitle>
|
|
||||||
<CardDescription className="text-zinc-400 text-xs">
|
|
||||||
Escolha um modelo e/ou informe uma tag custom para baixar.
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
|
|
||||||
<CardContent className="px-6 sm:px-8 pb-4 sm:pb-6 pt-0 space-y-4 flex-1 min-h-0 overflow-y-auto">
|
|
||||||
<div className="flex flex-col md:flex-row gap-3 mb-2">
|
|
||||||
<div className="relative flex-1">
|
|
||||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
|
||||||
<Input
|
|
||||||
type="text"
|
|
||||||
placeholder="Pesquisar modelos..."
|
|
||||||
value={searchQuery}
|
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
|
||||||
className="pl-9 h-10 text-sm"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-2 md:w-1/3">
|
|
||||||
<Input
|
|
||||||
type="text"
|
|
||||||
placeholder="Tag custom (ex: deepseek-coder:6.7b)"
|
|
||||||
value={customModelInput}
|
|
||||||
onChange={(e) => setCustomModelInput(e.target.value)}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === 'Enter') {
|
|
||||||
handleCustomDownload();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
disabled={downloadState.isDownloading}
|
|
||||||
className="flex-1 h-10 text-sm"
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
onClick={handleCustomDownload}
|
|
||||||
disabled={!customModelInput.trim() || downloadState.isDownloading || customModelInstalled}
|
|
||||||
variant={customModelInstalled ? 'outline' : 'default'}
|
|
||||||
className={cn(
|
|
||||||
"gap-2 h-10 px-4 text-sm",
|
|
||||||
customModelInstalled && "border-emerald-500/30 text-emerald-400 bg-emerald-500/10"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{downloadState.isDownloading && activeModelTag === customModelInput.trim() ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="w-4 h-4 animate-spin" />
|
|
||||||
Baixando
|
|
||||||
</>
|
|
||||||
) : customModelInstalled ? (
|
|
||||||
<>
|
|
||||||
<CheckCircle2 className="w-4 h-4" />
|
|
||||||
Já Instalado
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Download className="w-4 h-4" />
|
|
||||||
Baixar
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Lista de Modelos Recomendados */}
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="flex items-center gap-2 mt-2 mb-2">
|
|
||||||
<Sparkles className="w-4 h-4 text-primary" />
|
|
||||||
<h3 className="text-xs font-semibold">Modelos Recomendados</h3>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-2 lg:grid-cols-3 gap-3 min-h-[300px] max-h-[450px] overflow-y-auto pr-2 scrollbar-thin scrollbar-thumb-zinc-800 custom-scrollbar">
|
|
||||||
{filteredModels.length === 0 ? (
|
|
||||||
<div className="col-span-1 sm:col-span-2 text-center py-12 text-sm text-muted-foreground">
|
|
||||||
Nenhum modelo encontrado para “{searchQuery}”
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
filteredModels.map((model) => {
|
|
||||||
const isActive = activeModelTag === model.id;
|
|
||||||
const isDownloading = downloadState.isDownloading && isActive;
|
|
||||||
const progress = isActive ? activeProgress : null;
|
|
||||||
const isInstalled = installedModels.has(model.id);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card
|
|
||||||
key={model.id}
|
|
||||||
className={cn(
|
|
||||||
'relative border border-zinc-800 bg-zinc-900/50 hover:bg-zinc-900 transition-all',
|
|
||||||
isDownloading && 'border-emerald-500/50',
|
|
||||||
isInstalled && !isDownloading && 'border-emerald-500/30 bg-emerald-500/5'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="p-3 space-y-2">
|
|
||||||
<div className="flex items-start justify-between gap-2">
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<h4 className="font-bold text-sm truncate">{model.name}</h4>
|
|
||||||
{isInstalled && (
|
|
||||||
<Badge variant="outline" className="border-emerald-500/30 text-emerald-400 bg-emerald-500/10 text-[10px] px-1.5 py-0">
|
|
||||||
<CheckCircle2 className="w-3 h-3 mr-1" />
|
|
||||||
Instalado
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<p className="hidden md:block text-[11px] text-muted-foreground mt-1 line-clamp-1">
|
|
||||||
{model.description || ''}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Badge variant="outline" className="shrink-0 text-[10px] sm:text-xs">
|
|
||||||
{model.size}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center justify-between text-[10px] sm:text-xs text-muted-foreground gap-2">
|
|
||||||
<span className="truncate">Mín. {model.minRam}GB RAM</span>
|
|
||||||
<code className="text-[9px] sm:text-[10px] bg-muted px-1 sm:px-1.5 py-0.5 rounded shrink-0 truncate max-w-[120px] sm:max-w-none">
|
|
||||||
{model.id}
|
|
||||||
</code>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isDownloading && progress && (
|
|
||||||
<div className="space-y-1 pt-2 border-t border-zinc-800/50">
|
|
||||||
<div className="flex items-center justify-between text-xs">
|
|
||||||
<span className="text-muted-foreground">
|
|
||||||
{progress.status || 'Baixando...'}
|
|
||||||
</span>
|
|
||||||
{progress.speed && (
|
|
||||||
<span className="font-mono text-[10px] text-muted-foreground">
|
|
||||||
{progress.speed}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<Progress
|
|
||||||
value={progress.total > 0 && progress.percent !== null ? progress.percent : undefined}
|
|
||||||
className="h-1"
|
|
||||||
/>
|
|
||||||
{progress.total > 0 && (
|
|
||||||
<div className="flex justify-between text-[10px] text-muted-foreground/70">
|
|
||||||
<span>
|
|
||||||
{progress.downloadedFormatted} / {progress.totalFormatted}
|
|
||||||
</span>
|
|
||||||
<span>{progress.percent ?? 0}%</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Button
|
|
||||||
onClick={() => handleModelDownload(model.id)}
|
|
||||||
disabled={downloadState.isDownloading || isInstalled}
|
|
||||||
variant={isInstalled ? 'outline' : isDownloading ? 'outline' : 'default'}
|
|
||||||
className={cn(
|
|
||||||
"w-full gap-2 h-8 text-xs",
|
|
||||||
isInstalled && "border-emerald-500/30 text-emerald-400 bg-emerald-500/10 hover:bg-emerald-500/20"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{isDownloading ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="w-3 h-3 animate-spin" />
|
|
||||||
<span className="hidden sm:inline">Baixando...</span>
|
|
||||||
</>
|
|
||||||
) : isInstalled ? (
|
|
||||||
<>
|
|
||||||
<CheckCircle2 className="w-3 h-3" />
|
|
||||||
<span className="hidden sm:inline">Já Instalado</span>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Download className="w-3 h-3" />
|
|
||||||
<span className="hidden sm:inline">Baixar</span>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
})
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Mensagens de Erro */}
|
|
||||||
{state.lastError && (
|
|
||||||
<div className="flex items-start gap-3 p-4 bg-red-50 dark:bg-red-950/20 rounded-lg border border-red-200 dark:border-red-900/50">
|
|
||||||
<AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 shrink-0" />
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm font-medium text-red-900 dark:text-red-100">Erro no download</p>
|
|
||||||
<p className="text-xs text-red-700 dark:text-red-300 mt-1 break-words">{state.lastError}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* SLIM FOOTER NAVIGATION */}
|
|
||||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 pt-4 mt-4 border-t border-zinc-800 bg-zinc-950/50 backdrop-blur-sm flex-shrink-0">
|
|
||||||
<div className="text-xs text-zinc-500">
|
|
||||||
<span>Selecione um modelo ou pule para configurar depois.</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-3 w-full sm:w-auto">
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
onClick={onNext}
|
|
||||||
className="text-zinc-400 hover:text-white hover:bg-zinc-800 flex-1 sm:flex-initial"
|
|
||||||
disabled={downloadState.isDownloading}
|
|
||||||
>
|
|
||||||
Pular etapa
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={onNext}
|
|
||||||
className="bg-white text-black hover:bg-zinc-200 px-8 flex-1 sm:flex-initial"
|
|
||||||
disabled={downloadState.isDownloading}
|
|
||||||
>
|
|
||||||
Continuar <ArrowRight className="w-4 h-4 ml-2" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
<CardFooter className="p-6 sm:p-8 pt-0 border-t-0 flex-shrink-0 hidden">
|
|
||||||
{/* Footer vazio - mantido para compatibilidade, mas conteúdo movido para CardContent */}
|
|
||||||
</CardFooter>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -8,7 +8,6 @@ import { RECOMMENDED_MODELS, ModelRecommendation } from "@/lib/recommendation";
|
|||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } 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";
|
||||||
import { startTransition } from "react";
|
|
||||||
|
|
||||||
interface ModelSelectorProps {
|
interface ModelSelectorProps {
|
||||||
recommendation: ModelRecommendation;
|
recommendation: ModelRecommendation;
|
||||||
@@ -31,7 +30,6 @@ export function ModelSelector({ recommendation, onComplete }: ModelSelectorProps
|
|||||||
const [downloadProgress, setDownloadProgress] = useState(0);
|
const [downloadProgress, setDownloadProgress] = useState(0);
|
||||||
const [downloadStatus, setDownloadStatus] = useState("");
|
const [downloadStatus, setDownloadStatus] = useState("");
|
||||||
const [downloadInfo, setDownloadInfo] = useState<DownloadInfo | null>(null);
|
const [downloadInfo, setDownloadInfo] = useState<DownloadInfo | null>(null);
|
||||||
const [isNavigating, setIsNavigating] = useState(false);
|
|
||||||
|
|
||||||
const selectedModel = RECOMMENDED_MODELS.find(m => m.id === selectedModelId) || RECOMMENDED_MODELS[0];
|
const selectedModel = RECOMMENDED_MODELS.find(m => m.id === selectedModelId) || RECOMMENDED_MODELS[0];
|
||||||
|
|
||||||
@@ -82,11 +80,10 @@ export function ModelSelector({ recommendation, onComplete }: ModelSelectorProps
|
|||||||
|
|
||||||
// Se chegou a 100% ou success, marcar como instalado após um pequeno delay
|
// Se chegou a 100% ou success, marcar como instalado após um pequeno delay
|
||||||
if (info.percent === 100 || info.status === "success") {
|
if (info.percent === 100 || info.status === "success") {
|
||||||
setTimeout(async () => {
|
setTimeout(() => {
|
||||||
setIsInstalled(true);
|
setIsInstalled(true);
|
||||||
setIsDownloading(false);
|
setIsDownloading(false);
|
||||||
// Verificar instalação de forma assíncrona sem bloquear
|
checkInstallation(selectedModelId);
|
||||||
checkInstallation(selectedModelId).catch(console.error);
|
|
||||||
}, 500);
|
}, 500);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -106,34 +103,24 @@ export function ModelSelector({ recommendation, onComplete }: ModelSelectorProps
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleNavigate = () => {
|
|
||||||
setIsNavigating(true);
|
|
||||||
// Usar startTransition para navegação não-bloqueante
|
|
||||||
startTransition(() => {
|
|
||||||
onComplete();
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDownload = async () => {
|
const handleDownload = async () => {
|
||||||
// Optimistic UI: atualizar estado imediatamente antes da chamada Tauri
|
|
||||||
setIsDownloading(true);
|
setIsDownloading(true);
|
||||||
setDownloadProgress(0);
|
setDownloadProgress(0);
|
||||||
setDownloadStatus("Iniciando download...");
|
setDownloadStatus("Iniciando download...");
|
||||||
|
try {
|
||||||
// Chamar Tauri em background (não bloquear)
|
await invoke('pull_model', { name: selectedModelId });
|
||||||
invoke('pull_model', { name: selectedModelId })
|
// O status será atualizado pelo listener quando o download completar
|
||||||
.catch((error) => {
|
// Não precisamos setar aqui pois o listener já faz isso
|
||||||
console.error("Download failed", error);
|
} catch (error) {
|
||||||
setDownloadStatus("Falha no download. Tente novamente.");
|
console.error("Download failed", error);
|
||||||
setDownloadProgress(0);
|
setDownloadStatus("Falha no download. Tente novamente.");
|
||||||
setIsDownloading(false);
|
setDownloadProgress(0);
|
||||||
});
|
setIsDownloading(false);
|
||||||
// O status será atualizado pelo listener quando o download completar
|
}
|
||||||
// Não precisamos aguardar aqui pois o listener já faz isso
|
|
||||||
};
|
};
|
||||||
|
|
||||||
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>
|
||||||
@@ -145,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>
|
||||||
)}
|
)}
|
||||||
@@ -157,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>
|
||||||
@@ -172,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
|
||||||
@@ -205,22 +192,9 @@ export function ModelSelector({ recommendation, onComplete }: ModelSelectorProps
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
<CardFooter>
|
<CardFooter>
|
||||||
{isInstalled ? (
|
{isInstalled ? (
|
||||||
<Button
|
<Button className="w-full h-12 text-lg" onClick={onComplete}>
|
||||||
className="w-full h-12 text-lg"
|
Ir para o Chat
|
||||||
onClick={handleNavigate}
|
<Play className="ml-2 w-5 h-5" />
|
||||||
disabled={isNavigating}
|
|
||||||
>
|
|
||||||
{isNavigating ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="mr-2 h-5 w-5 animate-spin" />
|
|
||||||
Inicializando...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
Ir para o Chat
|
|
||||||
<Play className="ml-2 w-5 h-5" />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
</Button>
|
||||||
) : (
|
) : (
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -1,638 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState, useEffect, useRef } from 'react';
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Progress } from '@/components/ui/progress';
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
|
|
||||||
import { useSetupWizard } from '@/hooks/use-setup-wizard';
|
|
||||||
import { useOllamaDownload } from '@/hooks/use-ollama-download';
|
|
||||||
import { useOllamaCheck } from '@/hooks/use-ollama-check';
|
|
||||||
import { useOperatingSystem } from '@/hooks/use-operating-system';
|
|
||||||
import { InstallationTerminal } from './installation-terminal';
|
|
||||||
import { Loader2, CheckCircle2, AlertCircle, Download, RefreshCw, Shield, Clock, WifiOff, ArrowRight } from 'lucide-react';
|
|
||||||
|
|
||||||
function formatBytes(bytes: number): string {
|
|
||||||
if (bytes === 0) return '0 B';
|
|
||||||
const k = 1024;
|
|
||||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
|
||||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
||||||
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatTime(seconds: number): string {
|
|
||||||
if (seconds < 60) return `${Math.round(seconds)}s`;
|
|
||||||
const minutes = Math.floor(seconds / 60);
|
|
||||||
const secs = Math.round(seconds % 60);
|
|
||||||
return `${minutes}m ${secs}s`;
|
|
||||||
}
|
|
||||||
|
|
||||||
type InstallErrorType = 'ERR_NO_PRIVILEGE' | 'ERR_DOWNLOAD_FAIL' | 'ERR_TIMEOUT' | 'ERR_INSTALL_FAILED';
|
|
||||||
|
|
||||||
function parseInstallError(error: string): InstallErrorType {
|
|
||||||
const errorLower = error.toLowerCase();
|
|
||||||
|
|
||||||
// Verificar privilégios/permissões
|
|
||||||
if (
|
|
||||||
errorLower.includes('privilege') ||
|
|
||||||
errorLower.includes('permission') ||
|
|
||||||
errorLower.includes('elevated') ||
|
|
||||||
errorLower.includes('uac') ||
|
|
||||||
errorLower.includes('administrator') ||
|
|
||||||
errorLower.includes('access denied') ||
|
|
||||||
errorLower.includes('acesso negado')
|
|
||||||
) {
|
|
||||||
return 'ERR_NO_PRIVILEGE';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verificar erros de download/rede
|
|
||||||
if (
|
|
||||||
errorLower.includes('download') ||
|
|
||||||
errorLower.includes('network') ||
|
|
||||||
errorLower.includes('connection') ||
|
|
||||||
errorLower.includes('failed to download') ||
|
|
||||||
errorLower.includes('falha ao baixar') ||
|
|
||||||
errorLower.includes('conexão') ||
|
|
||||||
errorLower.includes('timeout') && (errorLower.includes('download') || errorLower.includes('conexão'))
|
|
||||||
) {
|
|
||||||
return 'ERR_DOWNLOAD_FAIL';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verificar timeout
|
|
||||||
if (
|
|
||||||
errorLower.includes('timeout') ||
|
|
||||||
errorLower.includes('90 segundos') ||
|
|
||||||
errorLower.includes('timed out') ||
|
|
||||||
errorLower.includes('tempo esgotado')
|
|
||||||
) {
|
|
||||||
return 'ERR_TIMEOUT';
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'ERR_INSTALL_FAILED';
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ErrorDisplayProps {
|
|
||||||
errorType: InstallErrorType;
|
|
||||||
errorMessage: string;
|
|
||||||
onRetry: () => void;
|
|
||||||
isRetrying: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
function ErrorDisplay({ errorType, errorMessage, onRetry, isRetrying }: ErrorDisplayProps) {
|
|
||||||
switch (errorType) {
|
|
||||||
case 'ERR_NO_PRIVILEGE':
|
|
||||||
return (
|
|
||||||
<Card className="border-amber-200 dark:border-amber-900 bg-amber-50 dark:bg-amber-950/20">
|
|
||||||
<CardHeader className="pb-3 sm:pb-6">
|
|
||||||
<div className="flex items-start gap-2 sm:gap-3">
|
|
||||||
<Shield className="w-4 h-4 sm:w-5 sm:h-5 text-amber-600 dark:text-amber-400 mt-0.5 shrink-0" />
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<CardTitle className="text-sm sm:text-base text-amber-900 dark:text-amber-100">
|
|
||||||
Permissões Administrativas Necessárias
|
|
||||||
</CardTitle>
|
|
||||||
<CardDescription className="text-xs sm:text-sm text-amber-700 dark:text-amber-300 mt-1 sm:mt-2">
|
|
||||||
O Windows solicitou permissões de administrador para instalar o Ollama.
|
|
||||||
</CardDescription>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-3 sm:space-y-4">
|
|
||||||
<div className="bg-white dark:bg-zinc-900 p-3 sm:p-4 rounded-lg border border-amber-200 dark:border-amber-800">
|
|
||||||
<p className="text-xs sm:text-sm font-medium text-foreground mb-2">O que fazer:</p>
|
|
||||||
<ol className="list-decimal list-inside space-y-1 text-xs sm:text-sm text-muted-foreground">
|
|
||||||
<li>Verifique se apareceu um prompt do Windows pedindo permissões</li>
|
|
||||||
<li>Clique em "Sim" ou "Allow" no prompt de UAC (User Account Control)</li>
|
|
||||||
<li>Aguarde alguns segundos para a instalação continuar</li>
|
|
||||||
<li>Se o prompt não apareceu, tente executar o OllaHub como administrador</li>
|
|
||||||
</ol>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
onClick={onRetry}
|
|
||||||
disabled={isRetrying}
|
|
||||||
variant="outline"
|
|
||||||
className="w-full sm:w-auto"
|
|
||||||
>
|
|
||||||
{isRetrying ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
|
||||||
Verificando...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<RefreshCw className="w-4 h-4 mr-2" />
|
|
||||||
Verificar Novamente
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
<p className="text-xs text-muted-foreground text-center">
|
|
||||||
{errorMessage}
|
|
||||||
</p>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
|
|
||||||
case 'ERR_DOWNLOAD_FAIL':
|
|
||||||
return (
|
|
||||||
<Card className="border-red-200 dark:border-red-900 bg-red-50 dark:bg-red-950/20">
|
|
||||||
<CardHeader className="pb-3 sm:pb-6">
|
|
||||||
<div className="flex items-start gap-2 sm:gap-3">
|
|
||||||
<WifiOff className="w-4 h-4 sm:w-5 sm:h-5 text-red-600 dark:text-red-400 mt-0.5 shrink-0" />
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<CardTitle className="text-sm sm:text-base text-red-900 dark:text-red-100">
|
|
||||||
Erro ao Baixar Instalador
|
|
||||||
</CardTitle>
|
|
||||||
<CardDescription className="text-xs sm:text-sm text-red-700 dark:text-red-300 mt-1 sm:mt-2">
|
|
||||||
Não foi possível baixar o instalador do Ollama. Verifique sua conexão com a internet.
|
|
||||||
</CardDescription>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-3 sm:space-y-4">
|
|
||||||
<div className="bg-white dark:bg-zinc-900 p-3 sm:p-4 rounded-lg border border-red-200 dark:border-red-800">
|
|
||||||
<p className="text-xs sm:text-sm text-muted-foreground break-words">
|
|
||||||
{errorMessage}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
onClick={onRetry}
|
|
||||||
disabled={isRetrying}
|
|
||||||
variant="outline"
|
|
||||||
className="w-full sm:w-auto"
|
|
||||||
>
|
|
||||||
{isRetrying ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
|
||||||
Tentando Novamente...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<RefreshCw className="w-4 h-4 mr-2" />
|
|
||||||
Tentar Novamente
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
|
|
||||||
case 'ERR_TIMEOUT':
|
|
||||||
return (
|
|
||||||
<Card className="border-orange-200 dark:border-orange-900 bg-orange-50 dark:bg-orange-950/20">
|
|
||||||
<CardHeader className="pb-3 sm:pb-6">
|
|
||||||
<div className="flex items-start gap-2 sm:gap-3">
|
|
||||||
<Clock className="w-4 h-4 sm:w-5 sm:h-5 text-orange-600 dark:text-orange-400 mt-0.5 shrink-0" />
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<CardTitle className="text-sm sm:text-base text-orange-900 dark:text-orange-100">
|
|
||||||
Instalação Demorando Mais do Que o Esperado
|
|
||||||
</CardTitle>
|
|
||||||
<CardDescription className="text-xs sm:text-sm text-orange-700 dark:text-orange-300 mt-1 sm:mt-2">
|
|
||||||
A instalação pode ainda estar em andamento em segundo plano.
|
|
||||||
</CardDescription>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-3 sm:space-y-4">
|
|
||||||
<div className="bg-white dark:bg-zinc-900 p-3 sm:p-4 rounded-lg border border-orange-200 dark:border-orange-800">
|
|
||||||
<p className="text-xs sm:text-sm text-muted-foreground mb-2 break-words">
|
|
||||||
O processo de instalação pode levar alguns minutos. Se o Ollama estiver sendo instalado,
|
|
||||||
você pode verificar o status manualmente.
|
|
||||||
</p>
|
|
||||||
<p className="text-[10px] sm:text-xs text-muted-foreground break-words">
|
|
||||||
{errorMessage}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
onClick={onRetry}
|
|
||||||
disabled={isRetrying}
|
|
||||||
variant="outline"
|
|
||||||
className="w-full sm:w-auto"
|
|
||||||
>
|
|
||||||
{isRetrying ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
|
||||||
Verificando...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<RefreshCw className="w-4 h-4 mr-2" />
|
|
||||||
Verificar Novamente
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
|
|
||||||
default:
|
|
||||||
return (
|
|
||||||
<div className="flex items-start gap-2 p-3 sm:p-4 bg-red-50 dark:bg-red-950/20 rounded-lg">
|
|
||||||
<AlertCircle className="w-4 h-4 sm:w-5 sm:h-5 text-red-600 dark:text-red-400 mt-0.5 shrink-0" />
|
|
||||||
<div className="flex-1 space-y-2 sm:space-y-3 min-w-0">
|
|
||||||
<div>
|
|
||||||
<p className="text-sm sm:text-base font-medium text-red-900 dark:text-red-100">Erro na instalação</p>
|
|
||||||
<p className="text-xs sm:text-sm text-red-700 dark:text-red-300 mt-1 break-words">{errorMessage}</p>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
onClick={onRetry}
|
|
||||||
disabled={isRetrying}
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className="w-full sm:w-auto"
|
|
||||||
>
|
|
||||||
{isRetrying ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
|
||||||
Verificando...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<RefreshCw className="w-4 h-4 mr-2" />
|
|
||||||
Verificar Novamente
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type InstallStepState = 'IDLE' | 'INSTALLING' | 'VERIFYING' | 'SUCCESS';
|
|
||||||
|
|
||||||
interface OllamaInstallStepProps {
|
|
||||||
onNext: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function OllamaInstallStep({ onNext }: OllamaInstallStepProps) {
|
|
||||||
const { state, installOllama, checkChocolatey, installChocolatey, installOllamaViaChoco, checkSetupState } = useSetupWizard();
|
|
||||||
const { os: detectedOS } = useOperatingSystem();
|
|
||||||
const downloadState = useOllamaDownload();
|
|
||||||
const ollamaCheck = useOllamaCheck();
|
|
||||||
const [stepState, setStepState] = useState<InstallStepState>('IDLE');
|
|
||||||
const [useChocolatey, setUseChocolatey] = useState(false);
|
|
||||||
const [showTerminal, setShowTerminal] = useState(false);
|
|
||||||
const [isRetrying, setIsRetrying] = useState(false);
|
|
||||||
|
|
||||||
const installationInProgressRef = useRef(false);
|
|
||||||
const hasCheckedInitialRef = useRef(false);
|
|
||||||
|
|
||||||
// Função de polling ativo para aguardar serviço ficar disponível
|
|
||||||
const waitForService = async (maxAttempts = 15): Promise<boolean> => {
|
|
||||||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
||||||
try {
|
|
||||||
const isIntact = await invoke<boolean>('verify_ollama_integrity_command');
|
|
||||||
if (isIntact) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.warn(`Tentativa ${attempt}/${maxAttempts} falhou:`, error);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (attempt < maxAttempts) {
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error('Ollama não ficou disponível após 30 segundos');
|
|
||||||
};
|
|
||||||
|
|
||||||
// Verificação inicial no mount: se Ollama já estiver instalado, ir direto para SUCCESS
|
|
||||||
useEffect(() => {
|
|
||||||
if (hasCheckedInitialRef.current) return;
|
|
||||||
|
|
||||||
const checkInitial = async () => {
|
|
||||||
if (stepState === 'IDLE') {
|
|
||||||
try {
|
|
||||||
const isIntact = await invoke<boolean>('verify_ollama_integrity_command');
|
|
||||||
if (isIntact) {
|
|
||||||
// Se a integridade está OK, atualizar estado do wizard e ir para SUCCESS
|
|
||||||
await checkSetupState();
|
|
||||||
setStepState('SUCCESS');
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Silenciosamente ignorar - usuário ainda não instalou
|
|
||||||
}
|
|
||||||
}
|
|
||||||
hasCheckedInitialRef.current = true;
|
|
||||||
};
|
|
||||||
|
|
||||||
checkInitial();
|
|
||||||
}, [stepState, checkSetupState]);
|
|
||||||
|
|
||||||
// Sincronizar estado do polling com wizard state e atualizar FSM
|
|
||||||
useEffect(() => {
|
|
||||||
if (ollamaCheck.status === 'running' && !state.ollamaRunning) {
|
|
||||||
// Polling detectou que Ollama está rodando, atualizar wizard state
|
|
||||||
checkSetupState().catch(console.error);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Atualizar FSM baseado no status
|
|
||||||
if (stepState === 'VERIFYING' && ollamaCheck.status === 'running' && state.ollamaInstalled && state.ollamaRunning) {
|
|
||||||
setStepState('SUCCESS');
|
|
||||||
ollamaCheck.stopPolling();
|
|
||||||
}
|
|
||||||
}, [ollamaCheck.status, state.ollamaRunning, state.ollamaInstalled, checkSetupState, stepState, ollamaCheck]);
|
|
||||||
|
|
||||||
const handleManualRetry = async () => {
|
|
||||||
setIsRetrying(true);
|
|
||||||
try {
|
|
||||||
await checkSetupState();
|
|
||||||
|
|
||||||
// Se já estiver instalado, ir para SUCCESS
|
|
||||||
if (state.ollamaInstalled && state.ollamaRunning) {
|
|
||||||
setStepState('SUCCESS');
|
|
||||||
} else {
|
|
||||||
// Iniciar verificação manual
|
|
||||||
setStepState('VERIFYING');
|
|
||||||
ollamaCheck.startPolling();
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao verificar novamente:', error);
|
|
||||||
} finally {
|
|
||||||
setIsRetrying(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCheckExisting = async () => {
|
|
||||||
setStepState('VERIFYING');
|
|
||||||
ollamaCheck.startPolling();
|
|
||||||
await checkSetupState();
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleInstall = async () => {
|
|
||||||
if (installationInProgressRef.current) {
|
|
||||||
return; // Evitar múltiplas instalações simultâneas
|
|
||||||
}
|
|
||||||
|
|
||||||
installationInProgressRef.current = true;
|
|
||||||
setStepState('INSTALLING');
|
|
||||||
setShowTerminal(true);
|
|
||||||
|
|
||||||
try {
|
|
||||||
// No Windows, verificar se Chocolatey está disponível
|
|
||||||
if (detectedOS === 'windows') {
|
|
||||||
const hasChoco = await checkChocolatey();
|
|
||||||
if (hasChoco) {
|
|
||||||
setUseChocolatey(true);
|
|
||||||
// Instalar Ollama via Chocolatey
|
|
||||||
await installOllamaViaChoco();
|
|
||||||
// Após instalação, fazer polling ativo
|
|
||||||
setStepState('VERIFYING');
|
|
||||||
await waitForService(15); // 15 tentativas = 30 segundos
|
|
||||||
// Se chegou aqui, Ollama está funcional
|
|
||||||
setStepState('SUCCESS');
|
|
||||||
await checkSetupState(); // Atualizar estado do wizard
|
|
||||||
installationInProgressRef.current = false;
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
// Tentar instalar Chocolatey primeiro
|
|
||||||
try {
|
|
||||||
await installChocolatey();
|
|
||||||
setUseChocolatey(true);
|
|
||||||
await installOllamaViaChoco();
|
|
||||||
// Após instalação, fazer polling ativo
|
|
||||||
setStepState('VERIFYING');
|
|
||||||
await waitForService(15); // 15 tentativas = 30 segundos
|
|
||||||
// Se chegou aqui, Ollama está funcional
|
|
||||||
setStepState('SUCCESS');
|
|
||||||
await checkSetupState(); // Atualizar estado do wizard
|
|
||||||
installationInProgressRef.current = false;
|
|
||||||
return;
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('Falha ao usar Chocolatey, usando instalação direta:', error);
|
|
||||||
setUseChocolatey(false);
|
|
||||||
setShowTerminal(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: instalação direta
|
|
||||||
if (!downloadState.filePath && detectedOS) {
|
|
||||||
await downloadState.handleDownload(detectedOS);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (downloadState.filePath) {
|
|
||||||
await installOllama(downloadState.filePath);
|
|
||||||
} else {
|
|
||||||
await installOllama();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Após instalação, fazer polling ativo
|
|
||||||
setStepState('VERIFYING');
|
|
||||||
await waitForService(15); // 15 tentativas = 30 segundos
|
|
||||||
// Se chegou aqui, Ollama está funcional
|
|
||||||
setStepState('SUCCESS');
|
|
||||||
await checkSetupState(); // Atualizar estado do wizard
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao aguardar serviço:', error);
|
|
||||||
setStepState('IDLE');
|
|
||||||
} finally {
|
|
||||||
installationInProgressRef.current = false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Estado SUCCESS: mostrar mensagem de sucesso e botão Continuar
|
|
||||||
if (stepState === 'SUCCESS' || (state.ollamaInstalled && state.ollamaRunning)) {
|
|
||||||
return (
|
|
||||||
<Card className="w-full max-w-2xl mx-auto border-zinc-800 bg-zinc-950/50 backdrop-blur-sm shadow-2xl">
|
|
||||||
<CardHeader className="p-6 sm:p-8">
|
|
||||||
<CardTitle className="text-2xl font-bold text-white flex items-center gap-2 mb-2">
|
|
||||||
<CheckCircle2 className="w-6 h-6 text-emerald-500 shrink-0" />
|
|
||||||
<span>Instalação Concluída</span>
|
|
||||||
</CardTitle>
|
|
||||||
<CardDescription className="text-zinc-400 mb-8 text-base">
|
|
||||||
Ollama está instalado e rodando com sucesso.
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="px-6 sm:px-8 pb-6 sm:pb-8 pt-0 space-y-6">
|
|
||||||
<div className="flex items-start sm:items-center gap-3 p-4 bg-emerald-950/30 rounded-lg border border-emerald-900/50">
|
|
||||||
<CheckCircle2 className="w-5 h-5 text-emerald-400 shrink-0" />
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm font-medium text-emerald-100">Ollama Service is Running</p>
|
|
||||||
<p className="text-xs text-emerald-300 mt-1">Pronto para continuar com o download de modelos.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
<CardFooter className="flex justify-end p-6 sm:p-8 pt-6 mt-0 border-t border-zinc-800">
|
|
||||||
<Button onClick={onNext} className="w-full sm:w-auto bg-white text-black hover:bg-zinc-200 h-12 px-8 text-base font-medium">
|
|
||||||
Continuar <ArrowRight className="w-4 h-4 ml-2" />
|
|
||||||
</Button>
|
|
||||||
</CardFooter>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Estado IDLE: mostrar card informativo
|
|
||||||
if (stepState === 'IDLE') {
|
|
||||||
return (
|
|
||||||
<Card className="w-full max-w-2xl mx-auto border-zinc-800 bg-zinc-950/50 backdrop-blur-sm shadow-2xl">
|
|
||||||
<CardHeader className="p-6 sm:p-8">
|
|
||||||
<CardTitle className="text-2xl font-bold text-white flex items-center gap-2 mb-2">
|
|
||||||
<Download className="w-6 h-6 shrink-0" />
|
|
||||||
<span>Ollama Engine</span>
|
|
||||||
</CardTitle>
|
|
||||||
<CardDescription className="text-zinc-400 mb-8 text-base">
|
|
||||||
O OllaHub requer o motor Ollama para executar IAs localmente.
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="px-6 sm:px-8 pb-6 sm:pb-8 pt-0 space-y-6">
|
|
||||||
<p className="text-sm text-zinc-400 leading-relaxed">
|
|
||||||
O Ollama é uma ferramenta open-source que permite executar modelos de linguagem grandes (LLMs) diretamente no seu computador, sem necessidade de conexão com a internet.
|
|
||||||
</p>
|
|
||||||
</CardContent>
|
|
||||||
<CardFooter className="flex flex-col sm:flex-row justify-end gap-4 p-6 sm:p-8 pt-6 mt-0 border-t border-zinc-800">
|
|
||||||
<Button onClick={handleCheckExisting} variant="outline" className="w-full sm:w-auto h-12 border-zinc-700 text-zinc-300 hover:bg-zinc-800">
|
|
||||||
Já tenho o Ollama instalado
|
|
||||||
</Button>
|
|
||||||
<Button onClick={handleInstall} className="w-full sm:w-auto bg-white text-black hover:bg-zinc-200 h-12 px-8 text-base font-medium">
|
|
||||||
<Download className="w-4 h-4 mr-2" />
|
|
||||||
Instalar Ollama
|
|
||||||
</Button>
|
|
||||||
</CardFooter>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const errorType = state.lastError ? parseInstallError(state.lastError) : null;
|
|
||||||
const showRetryButton = state.lastError || state.progressStatus === 'error';
|
|
||||||
const showManualRetry = showRetryButton && state.lastError;
|
|
||||||
const hasTerminal = showTerminal && (state.progressStatus === 'installing_chocolatey' || state.progressStatus === 'installing_ollama' || useChocolatey);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className={`w-full max-w-2xl mx-auto border-zinc-800 bg-zinc-950/50 backdrop-blur-sm shadow-2xl ${hasTerminal ? 'max-h-[calc(100vh-16rem)] flex flex-col' : ''}`}>
|
|
||||||
<CardHeader className={`p-6 sm:p-8 ${hasTerminal ? 'flex-shrink-0' : ''}`}>
|
|
||||||
<CardTitle className="text-2xl font-bold text-white flex items-center gap-2 mb-2">
|
|
||||||
{stepState === 'INSTALLING' && <Loader2 className="w-6 h-6 animate-spin" />}
|
|
||||||
{stepState === 'VERIFYING' && <Loader2 className="w-6 h-6 animate-spin" />}
|
|
||||||
{(state.lastError || state.progressStatus === 'error') && <AlertCircle className="w-6 h-6 text-red-500" />}
|
|
||||||
<span>
|
|
||||||
{stepState === 'INSTALLING' ? 'Instalando Ollama...' :
|
|
||||||
stepState === 'VERIFYING' ? 'Verificando Instalação...' :
|
|
||||||
'Instalação em Progresso'}
|
|
||||||
</span>
|
|
||||||
</CardTitle>
|
|
||||||
<CardDescription className="text-zinc-400 mb-8 text-base">
|
|
||||||
Acompanhe o progresso da configuração do ambiente.
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
|
|
||||||
<CardContent className={`px-6 sm:px-8 pb-6 sm:pb-8 pt-0 space-y-6 ${hasTerminal ? 'flex-1 min-h-0 overflow-y-auto' : ''}`}>
|
|
||||||
{/* Terminal integrado para instalação via Chocolatey */}
|
|
||||||
{(showTerminal && (state.progressStatus === 'installing_chocolatey' || state.progressStatus === 'installing_ollama' || useChocolatey)) && (
|
|
||||||
<InstallationTerminal
|
|
||||||
onComplete={() => {
|
|
||||||
setShowTerminal(false);
|
|
||||||
}}
|
|
||||||
onError={(error) => {
|
|
||||||
console.error('Erro na instalação:', error);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Progresso para instalação direta (fallback) */}
|
|
||||||
{state.progressMessage && !showTerminal && (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex items-center justify-between text-sm">
|
|
||||||
<span className="text-muted-foreground">{state.progressMessage}</span>
|
|
||||||
{ollamaCheck.isChecking && (
|
|
||||||
<span className="text-xs text-muted-foreground">
|
|
||||||
Verificando... {formatTime(ollamaCheck.elapsedTime)}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{state.progressStatus === 'installing_ollama' && (
|
|
||||||
<Progress value={undefined} className="h-2" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Feedback do polling em background (estado VERIFYING) */}
|
|
||||||
{stepState === 'VERIFYING' && (
|
|
||||||
<div className="flex items-center gap-2 text-xs sm:text-sm text-muted-foreground p-4 bg-muted/50 rounded-lg">
|
|
||||||
<Loader2 className="w-4 h-4 animate-spin shrink-0" />
|
|
||||||
<span className="break-words">
|
|
||||||
Instalação concluída. Aguardando inicialização do serviço...
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Display de erro granular */}
|
|
||||||
{state.lastError && errorType && (
|
|
||||||
<ErrorDisplay
|
|
||||||
errorType={errorType}
|
|
||||||
errorMessage={state.lastError}
|
|
||||||
onRetry={handleManualRetry}
|
|
||||||
isRetrying={isRetrying}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Botão de retry manual quando não há erro específico */}
|
|
||||||
{showRetryButton && !showManualRetry && (
|
|
||||||
<Button
|
|
||||||
onClick={handleManualRetry}
|
|
||||||
disabled={isRetrying || stepState === 'INSTALLING'}
|
|
||||||
variant="outline"
|
|
||||||
className="w-full"
|
|
||||||
>
|
|
||||||
{isRetrying ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
|
||||||
Verificando...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<RefreshCw className="w-4 h-4 mr-2" />
|
|
||||||
Verificar Novamente
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{downloadState.isDownloading && (
|
|
||||||
<div className="space-y-2 w-full">
|
|
||||||
<div className="flex justify-between text-xs text-muted-foreground">
|
|
||||||
<span className="flex items-center gap-2">
|
|
||||||
{downloadState.status === 'verifying' ? (
|
|
||||||
<Loader2 className="w-3 h-3 animate-spin" />
|
|
||||||
) : (
|
|
||||||
<Download className="w-3 h-3" />
|
|
||||||
)}
|
|
||||||
{downloadState.status === 'verifying'
|
|
||||||
? 'Verificando integridade...'
|
|
||||||
: 'Baixando...'}
|
|
||||||
</span>
|
|
||||||
<span className="font-mono">{downloadState.speed || '0 MB/s'}</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Progress
|
|
||||||
value={downloadState.downloadProgress}
|
|
||||||
className="h-2 w-full transition-all duration-300"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className="flex justify-between text-[10px] text-muted-foreground/70 uppercase font-medium tracking-wider">
|
|
||||||
<span>
|
|
||||||
{formatBytes(downloadState.downloadedBytes)} / {formatBytes(downloadState.totalBytes)}
|
|
||||||
</span>
|
|
||||||
<span>{downloadState.downloadProgress.toFixed(1)}%</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{downloadState.eta > 0 && downloadState.status === 'downloading' && (
|
|
||||||
<div className="text-xs text-muted-foreground text-center">
|
|
||||||
Tempo restante: {formatTime(downloadState.eta)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Estado INSTALLING: mostrar progresso */}
|
|
||||||
{stepState === 'INSTALLING' && (
|
|
||||||
<div className="flex items-center gap-2 text-xs sm:text-sm text-muted-foreground">
|
|
||||||
<Loader2 className="w-4 h-4 animate-spin shrink-0" />
|
|
||||||
<span className="break-words">Instalando Ollama... Isso pode levar alguns minutos.</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
{/* Footer opcional se necessário */}
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useEffect, useState } from 'react';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Card, CardContent, CardFooter, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
|
||||||
import { useSetupWizard } from '@/hooks/use-setup-wizard';
|
|
||||||
import { useSettingsStore } from '@/store/settings-store';
|
|
||||||
import { useRouter } from 'next/navigation';
|
|
||||||
import { CheckCircle2, ArrowRight, AlertCircle, Sparkles, Loader2 } from 'lucide-react';
|
|
||||||
import { startTransition } from 'react';
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
|
||||||
|
|
||||||
export function SetupCompleteStep() {
|
|
||||||
const { state, goToStep } = useSetupWizard();
|
|
||||||
const { setSetupCompleted } = useSettingsStore();
|
|
||||||
const router = useRouter();
|
|
||||||
const [integrityError, setIntegrityError] = useState<string | null>(null);
|
|
||||||
const [isVerifying, setIsVerifying] = useState(true);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const verifyAndComplete = async () => {
|
|
||||||
try {
|
|
||||||
setIsVerifying(true);
|
|
||||||
setIntegrityError(null);
|
|
||||||
|
|
||||||
// Verificar integridade ANTES de marcar como completo
|
|
||||||
const isOllamaIntact = await invoke<boolean>('verify_ollama_integrity_command');
|
|
||||||
|
|
||||||
if (!isOllamaIntact) {
|
|
||||||
// Redirecionar silenciosamente para o passo de instalação do Ollama
|
|
||||||
setIsVerifying(false);
|
|
||||||
goToStep(2);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Só definir flag e redirecionar se Ollama estiver íntegro
|
|
||||||
setSetupCompleted(true);
|
|
||||||
setIsVerifying(false);
|
|
||||||
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
startTransition(() => {
|
|
||||||
router.replace('/chat');
|
|
||||||
});
|
|
||||||
}, 2000);
|
|
||||||
|
|
||||||
return () => clearTimeout(timer);
|
|
||||||
} catch {
|
|
||||||
// Em caso de erro na verificação, redirecionar para instalação
|
|
||||||
setIsVerifying(false);
|
|
||||||
goToStep(2);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
verifyAndComplete();
|
|
||||||
}, [setSetupCompleted, router, goToStep]);
|
|
||||||
|
|
||||||
const handleGoToChat = async () => {
|
|
||||||
try {
|
|
||||||
// Verificar integridade antes de redirecionar manualmente também
|
|
||||||
const isOllamaIntact = await invoke<boolean>('verify_ollama_integrity_command');
|
|
||||||
|
|
||||||
if (!isOllamaIntact) {
|
|
||||||
// Redirecionar para o passo de instalação do Ollama
|
|
||||||
goToStep(2);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setSetupCompleted(true);
|
|
||||||
startTransition(() => {
|
|
||||||
router.replace('/chat');
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
// Em caso de erro na verificação, redirecionar para instalação
|
|
||||||
goToStep(2);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleGoToInstallation = () => {
|
|
||||||
goToStep(2);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className="w-full max-w-2xl mx-auto border-zinc-800 bg-zinc-950/50 backdrop-blur-sm shadow-2xl">
|
|
||||||
<CardHeader className="p-6 sm:p-8">
|
|
||||||
<CardTitle className="text-2xl font-bold text-white flex items-center gap-2 mb-2">
|
|
||||||
{isVerifying ? (
|
|
||||||
<Loader2 className="w-6 h-6 animate-spin shrink-0" />
|
|
||||||
) : integrityError ? (
|
|
||||||
<AlertCircle className="w-6 h-6 text-red-500 shrink-0" />
|
|
||||||
) : (
|
|
||||||
<CheckCircle2 className="w-6 h-6 text-emerald-500 shrink-0" />
|
|
||||||
)}
|
|
||||||
<span>
|
|
||||||
{isVerifying ? 'Verificando Integridade' :
|
|
||||||
integrityError ? 'Erro na Configuração' :
|
|
||||||
'Configuração Completa'}
|
|
||||||
</span>
|
|
||||||
</CardTitle>
|
|
||||||
<CardDescription className="text-zinc-400 mb-8 text-base">
|
|
||||||
{isVerifying ? 'Validando instalação do Ollama...' :
|
|
||||||
integrityError ? 'Encontramos um problema.' :
|
|
||||||
'Tudo pronto para começar a usar o OllaHub.'}
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
|
|
||||||
<CardContent className="px-6 sm:px-8 pb-6 sm:pb-8 pt-0 space-y-6">
|
|
||||||
{isVerifying ? (
|
|
||||||
<div className="flex flex-col items-center justify-center py-6 sm:py-8 space-y-4">
|
|
||||||
<div className="w-16 h-16 rounded-full bg-zinc-900/50 flex items-center justify-center border border-zinc-800">
|
|
||||||
<CheckCircle2 className="w-8 h-8 text-zinc-700 animate-pulse" />
|
|
||||||
</div>
|
|
||||||
<p className="text-sm text-muted-foreground text-center max-w-md">
|
|
||||||
Estamos verificando se o serviço Ollama está respondendo corretamente antes de liberar o acesso.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
) : integrityError ? (
|
|
||||||
<div className="flex flex-col items-center justify-center py-6 sm:py-8 space-y-4">
|
|
||||||
<div className="w-16 h-16 rounded-full bg-red-950/20 flex items-center justify-center border border-red-900/50">
|
|
||||||
<AlertCircle className="w-8 h-8 text-red-500" />
|
|
||||||
</div>
|
|
||||||
<div className="text-center space-y-2 max-w-md">
|
|
||||||
<h3 className="font-semibold text-red-400">Falha na Verificação</h3>
|
|
||||||
<p className="text-sm text-zinc-400">
|
|
||||||
{integrityError}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<div className="flex items-start gap-4 p-6 bg-emerald-950/10 rounded-xl border border-emerald-900/20">
|
|
||||||
<div className="p-3 bg-emerald-500/10 rounded-lg shrink-0">
|
|
||||||
<Sparkles className="w-6 h-6 text-emerald-500" />
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1">
|
|
||||||
<h3 className="font-semibold text-emerald-400 text-lg">Ambiente Configurado</h3>
|
|
||||||
<p className="text-emerald-200/70 text-sm leading-relaxed">
|
|
||||||
Seu assistente de IA local está pronto. Você pode começar a conversar, gerar códigos ou analisar documentos agora mesmo.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-3 p-4 bg-zinc-900/50 rounded-xl border border-zinc-800/50">
|
|
||||||
<p className="text-sm font-medium text-zinc-300 flex items-center gap-2">
|
|
||||||
<CheckCircle2 className="w-4 h-4 text-emerald-500" />
|
|
||||||
Resumo da Instalação:
|
|
||||||
</p>
|
|
||||||
<ul className="text-sm text-zinc-500 space-y-2 pl-6 list-disc marker:text-zinc-700">
|
|
||||||
<li>Hardware compatível detectado</li>
|
|
||||||
{state.ollamaInstalled && <li>Ollama Engine instalado e ativo</li>}
|
|
||||||
{state.modelDownloaded && (
|
|
||||||
<li>Modelo de IA <strong>{state.modelName || 'padrão'}</strong> baixado</li>
|
|
||||||
)}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
|
|
||||||
<CardFooter className="flex justify-end p-6 sm:p-8 pt-6 mt-0 border-t border-zinc-800">
|
|
||||||
<Button
|
|
||||||
onClick={integrityError ? handleGoToInstallation : handleGoToChat}
|
|
||||||
className="w-full sm:w-auto bg-white text-black hover:bg-zinc-200 h-12 px-8 text-base font-medium"
|
|
||||||
disabled={isVerifying}
|
|
||||||
>
|
|
||||||
{isVerifying ? 'Verificando...' : integrityError ? 'Instalar Ollama' : 'Ir para o Chat'}
|
|
||||||
{!isVerifying && !integrityError && <ArrowRight className="w-4 h-4 ml-2" />}
|
|
||||||
</Button>
|
|
||||||
</CardFooter>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useEffect } from 'react';
|
|
||||||
import { useSetupWizard } from '@/hooks/use-setup-wizard';
|
|
||||||
import { SystemCheckStep } from './system-check-step';
|
|
||||||
import { OllamaInstallStep } from './ollama-install-step';
|
|
||||||
import { ModelDownloadStep } from './model-download-step';
|
|
||||||
import { SetupCompleteStep } from './setup-complete-step';
|
|
||||||
import { CheckCircle2 } from 'lucide-react';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
|
|
||||||
const steps = [
|
|
||||||
{ id: 1, title: 'Verificação do Sistema', description: 'Analisando hardware' },
|
|
||||||
{ id: 2, title: 'Instalação do Ollama', description: 'Configurando engine' },
|
|
||||||
{ id: 3, title: 'Download do Modelo', description: 'Baixando modelo padrão' },
|
|
||||||
{ id: 4, title: 'Conclusão', description: 'Tudo pronto!' },
|
|
||||||
];
|
|
||||||
|
|
||||||
export function SetupWizard() {
|
|
||||||
const { state, checkSetupState, goToStep, nextStep } = useSetupWizard();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
checkSetupState();
|
|
||||||
}, [checkSetupState]);
|
|
||||||
|
|
||||||
const handleNext = () => {
|
|
||||||
nextStep();
|
|
||||||
};
|
|
||||||
|
|
||||||
const renderStep = () => {
|
|
||||||
switch (state.currentStep) {
|
|
||||||
case 1:
|
|
||||||
return <SystemCheckStep onNext={handleNext} />;
|
|
||||||
case 2:
|
|
||||||
return <OllamaInstallStep onNext={handleNext} />;
|
|
||||||
case 3:
|
|
||||||
return <ModelDownloadStep onNext={handleNext} />;
|
|
||||||
case 4:
|
|
||||||
return <SetupCompleteStep />;
|
|
||||||
default:
|
|
||||||
return <SystemCheckStep onNext={handleNext} />;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
const containerWidth = state.currentStep === 3 ? 'max-w-6xl' : 'max-w-2xl';
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="h-screen max-h-screen w-full bg-background flex flex-col items-center overflow-y-auto p-4 sm:p-6 lg:p-8">
|
|
||||||
<div className={`w-full ${containerWidth} flex-shrink-0 transition-all duration-500 ease-in-out space-y-4 sm:space-y-6 lg:space-y-8 py-4`}>
|
|
||||||
<div className="text-center space-y-2 flex-shrink-0">
|
|
||||||
<h1 className="text-2xl sm:text-3xl font-bold tracking-tighter">Configuração Inicial</h1>
|
|
||||||
<p className="text-sm sm:text-base text-muted-foreground">
|
|
||||||
Vamos preparar o ambiente ideal para você começar a usar o OllaHub.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className={`w-full ${containerWidth} mx-auto mb-20 sm:mb-24 md:mb-28 px-2 sm:px-0 transition-all duration-500 ease-in-out flex-shrink-0 relative z-0`}>
|
|
||||||
<div className="flex items-center justify-between relative">
|
|
||||||
{steps.map((step, index) => {
|
|
||||||
const isCompleted = state.completedSteps.includes(step.id);
|
|
||||||
const isCurrent = state.currentStep === step.id;
|
|
||||||
const isFuture = !isCompleted && !isCurrent;
|
|
||||||
|
|
||||||
const canNavigate = step.id <= state.currentStep;
|
|
||||||
const maxReachableStep = Math.max(state.currentStep, ...state.completedSteps);
|
|
||||||
const isClickable = canNavigate || step.id === maxReachableStep + 1;
|
|
||||||
const isLineActive = state.currentStep > index + 1 || state.completedSteps.includes(step.id);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div key={step.id} className={cn("contents")}>
|
|
||||||
{/* STEP CIRCLE & LABEL */}
|
|
||||||
<div className="flex flex-col items-center relative z-0 group pb-0 md:pb-0">
|
|
||||||
<div
|
|
||||||
onClick={() => isClickable && step.id !== state.currentStep && goToStep(step.id)}
|
|
||||||
className={cn(
|
|
||||||
"w-10 h-10 sm:w-12 sm:h-12 rounded-full flex items-center justify-center border-2 transition-all duration-300 relative z-0",
|
|
||||||
// Estética dos Círculos
|
|
||||||
isCompleted && "bg-emerald-500 border-emerald-500 text-white",
|
|
||||||
isCurrent && "bg-zinc-900 border-white text-white shadow-[0_0_10px_rgba(255,255,255,0.5)]",
|
|
||||||
isFuture && "bg-zinc-900 border-zinc-800 text-zinc-500",
|
|
||||||
// Interatividade
|
|
||||||
isClickable ? "cursor-pointer" : "cursor-default"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{isCompleted ? (
|
|
||||||
<CheckCircle2 className="w-5 h-5 sm:w-6 sm:h-6" />
|
|
||||||
) : (
|
|
||||||
<span className="text-sm sm:text-base font-bold">{step.id}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Rótulos (Labels) - Desktop Only */}
|
|
||||||
<div className="hidden md:flex absolute top-14 flex-col items-center w-32 text-center z-10">
|
|
||||||
<span className={cn(
|
|
||||||
"text-sm font-medium transition-colors duration-300",
|
|
||||||
isCurrent ? "text-white" : "text-muted-foreground"
|
|
||||||
)}>
|
|
||||||
{step.title}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* LINHA CONECTORA (Entre passos) */}
|
|
||||||
{index < steps.length - 1 && (
|
|
||||||
<div className={cn(
|
|
||||||
"flex-1 h-[2px] mx-2 sm:mx-4 rounded transition-colors duration-500 relative z-0",
|
|
||||||
isLineActive ? "bg-emerald-500" : "bg-zinc-800"
|
|
||||||
)} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="w-full flex-shrink-0 relative z-10">
|
|
||||||
{renderStep()}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { motion } from 'framer-motion';
|
|
||||||
import { CheckCircle2, Cpu, HardDrive, Zap, AlertCircle, ArrowRight } from 'lucide-react';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Card, CardContent, CardFooter, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import { useHardware } from '@/hooks/use-hardware';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
|
|
||||||
// Componente Skeleton simples para loading
|
|
||||||
function Skeleton({ className }: { className?: string }) {
|
|
||||||
return (
|
|
||||||
<div className={cn('animate-pulse bg-zinc-900 rounded-xl', className)} />
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SystemCheckStepProps {
|
|
||||||
onNext: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SystemCheckStep({ onNext }: SystemCheckStepProps) {
|
|
||||||
const { specs, loading } = useHardware();
|
|
||||||
|
|
||||||
const status = loading ? 'checking' : (specs ? 'success' : 'error');
|
|
||||||
const ramGB = specs ? (specs.total_memory / (1024 * 1024 * 1024)).toFixed(1) : 0;
|
|
||||||
const isCompatible = specs ? specs.total_memory >= 4 * 1024 * 1024 * 1024 : false; // Mínimo 4GB
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className="w-full max-w-2xl mx-auto border-zinc-800 bg-zinc-950/50 backdrop-blur-sm shadow-2xl">
|
|
||||||
<CardHeader className="p-6 sm:p-8">
|
|
||||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 sm:gap-0">
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<CardTitle className="text-2xl font-bold text-white flex items-center gap-2 mb-2">
|
|
||||||
<Zap className="w-6 h-6 text-emerald-500 shrink-0" />
|
|
||||||
<span className="truncate">Verificação de Hardware</span>
|
|
||||||
</CardTitle>
|
|
||||||
<CardDescription className="text-zinc-400 mb-8 text-base">
|
|
||||||
Analisando compatibilidade para execução de IA local.
|
|
||||||
</CardDescription>
|
|
||||||
</div>
|
|
||||||
{status === 'success' && isCompatible && (
|
|
||||||
<Badge variant="outline" className="border-emerald-500/30 text-emerald-400 bg-emerald-500/10 px-2 py-1 text-xs shrink-0">
|
|
||||||
Compatível
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
|
|
||||||
<CardContent className="px-6 sm:px-8 pb-6 sm:pb-8 pt-0 space-y-6">
|
|
||||||
{/* Estado de Carregamento ou Grid de Specs */}
|
|
||||||
{status === 'checking' ? (
|
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
|
||||||
<Skeleton className="h-24 w-full" />
|
|
||||||
<Skeleton className="h-24 w-full" />
|
|
||||||
</div>
|
|
||||||
) : specs ? (
|
|
||||||
<motion.div
|
|
||||||
initial={{ opacity: 0, y: 10 }}
|
|
||||||
animate={{ opacity: 1, y: 0 }}
|
|
||||||
className="grid grid-cols-1 sm:grid-cols-2 gap-4"
|
|
||||||
>
|
|
||||||
{/* Card RAM */}
|
|
||||||
<div className="p-4 sm:p-6 rounded-xl bg-zinc-900/50 border border-zinc-800 flex items-start gap-4 hover:border-zinc-700 transition-colors">
|
|
||||||
<div className="p-2 rounded-lg bg-indigo-500/10 text-indigo-400 shrink-0">
|
|
||||||
<HardDrive className="w-6 h-6" />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm font-medium text-zinc-400">Memória RAM</p>
|
|
||||||
<h3 className="text-2xl font-bold text-white mt-1">
|
|
||||||
{ramGB} <span className="text-sm font-normal text-zinc-500">GB</span>
|
|
||||||
</h3>
|
|
||||||
<p className="text-xs text-zinc-500 mt-1">Mínimo recomendado: 16GB</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Card CPU */}
|
|
||||||
<div className="p-4 sm:p-6 rounded-xl bg-zinc-900/50 border border-zinc-800 flex items-start gap-4 hover:border-zinc-700 transition-colors">
|
|
||||||
<div className="p-2 rounded-lg bg-blue-500/10 text-blue-400 shrink-0">
|
|
||||||
<Cpu className="w-6 h-6" />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm font-medium text-zinc-400">Processador</p>
|
|
||||||
<h3 className="text-2xl font-bold text-white mt-1">
|
|
||||||
{specs.cpu_count} <span className="text-sm font-normal text-zinc-500">Núcleos</span>
|
|
||||||
</h3>
|
|
||||||
<p className="text-xs text-zinc-500 mt-1">Alta capacidade de threads</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</motion.div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{/* Feedback Visual */}
|
|
||||||
<div className="pt-6">
|
|
||||||
{status === 'checking' && (
|
|
||||||
<p className="text-sm text-zinc-500 flex items-center gap-2 animate-pulse">
|
|
||||||
<span className="w-2 h-2 rounded-full bg-zinc-500 block" />
|
|
||||||
Escaneando componentes...
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{status === 'success' && (
|
|
||||||
<motion.div
|
|
||||||
initial={{ opacity: 0 }}
|
|
||||||
animate={{ opacity: 1 }}
|
|
||||||
className="flex items-start sm:items-center gap-3 text-sm text-emerald-400 bg-emerald-950/30 p-4 rounded-lg border border-emerald-900/50"
|
|
||||||
>
|
|
||||||
<CheckCircle2 className="w-5 h-5 shrink-0" />
|
|
||||||
<span>Hardware detectado com sucesso. Pronto para instalar o Ollama.</span>
|
|
||||||
</motion.div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{status === 'error' && (
|
|
||||||
<div className="flex items-start sm:items-center gap-3 text-sm text-red-400 bg-red-950/30 p-4 rounded-lg border border-red-900/50">
|
|
||||||
<AlertCircle className="w-5 h-5 shrink-0" />
|
|
||||||
<span>Não foi possível detectar o hardware. Verifique as permissões.</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
|
|
||||||
<CardFooter className="flex justify-end p-6 sm:p-8 pt-6 mt-0 border-t border-zinc-800">
|
|
||||||
<Button
|
|
||||||
onClick={onNext}
|
|
||||||
disabled={status !== 'success'}
|
|
||||||
className="w-full sm:w-auto bg-white text-black hover:bg-zinc-200 h-12 px-8 text-base font-medium"
|
|
||||||
>
|
|
||||||
{status === 'checking' ? 'Verificando...' : 'Continuar'}
|
|
||||||
{status === 'success' && <ArrowRight className="w-4 h-4 ml-2" />}
|
|
||||||
</Button>
|
|
||||||
</CardFooter>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
+8
-43
@@ -4,12 +4,9 @@ import { useEffect, useState } from 'react';
|
|||||||
import { getCurrentWindow } from '@tauri-apps/api/window';
|
import { getCurrentWindow } from '@tauri-apps/api/window';
|
||||||
import { Minus, Square, X } from 'lucide-react';
|
import { Minus, Square, X } from 'lucide-react';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { useSystemHealth } from '@/hooks/use-system-health';
|
|
||||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
|
||||||
|
|
||||||
export function TitleBar() {
|
export function TitleBar() {
|
||||||
const [isMaximized, setIsMaximized] = useState(false);
|
const [isMaximized, setIsMaximized] = useState(false);
|
||||||
const health = useSystemHealth();
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let isMounted = true;
|
let isMounted = true;
|
||||||
@@ -80,76 +77,44 @@ 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-[9999] shrink-0 fixed top-0 left-0 right-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
|
||||||
style={{
|
|
||||||
pointerEvents: 'auto',
|
|
||||||
WebkitAppRegion: 'drag'
|
|
||||||
} as React.CSSProperties & { WebkitAppRegion?: string }}
|
|
||||||
>
|
>
|
||||||
{/* Área de arrasto com logo/título */}
|
{/* Área de arrasto com logo/título */}
|
||||||
<div
|
<div
|
||||||
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
|
||||||
>
|
>
|
||||||
<img
|
<span className="text-xs font-medium text-muted-foreground">
|
||||||
src="/icon.png"
|
|
||||||
alt="OllaHub"
|
|
||||||
className="w-5 h-5 shrink-0"
|
|
||||||
draggable={false}
|
|
||||||
/>
|
|
||||||
<span className="text-sm font-medium text-sidebar-foreground">
|
|
||||||
OllaHub
|
OllaHub
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
{/* Indicador de saúde do sistema */}
|
|
||||||
<TooltipProvider>
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"w-2 h-2 rounded-full shrink-0",
|
|
||||||
health.status === 'healthy' && "bg-green-500",
|
|
||||||
health.status === 'warning' && "bg-yellow-500",
|
|
||||||
health.status === 'critical' && "bg-red-500"
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent side="bottom" className="text-xs">
|
|
||||||
<p>{health.message}</p>
|
|
||||||
<p className="text-muted-foreground mt-1">
|
|
||||||
RAM: {health.ram_percent.toFixed(1)}% | CPU: {health.cpu_percent.toFixed(1)}%
|
|
||||||
</p>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</TooltipProvider>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Controles de janela */}
|
{/* Controles de janela */}
|
||||||
<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>
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
import * as React from "react"
|
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
const alertVariants = cva(
|
|
||||||
"relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
|
|
||||||
{
|
|
||||||
variants: {
|
|
||||||
variant: {
|
|
||||||
default: "bg-background text-foreground",
|
|
||||||
destructive:
|
|
||||||
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
defaultVariants: {
|
|
||||||
variant: "default",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
const Alert = React.forwardRef<
|
|
||||||
HTMLDivElement,
|
|
||||||
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
|
|
||||||
>(({ className, variant = "default", ...props }, ref) => (
|
|
||||||
<div
|
|
||||||
ref={ref}
|
|
||||||
role="alert"
|
|
||||||
className={cn(alertVariants({ variant }), className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
Alert.displayName = "Alert"
|
|
||||||
|
|
||||||
const AlertDescription = React.forwardRef<
|
|
||||||
HTMLParagraphElement,
|
|
||||||
React.HTMLAttributes<HTMLParagraphElement>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<div
|
|
||||||
ref={ref}
|
|
||||||
className={cn("text-sm [&_p]:leading-relaxed", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
AlertDescription.displayName = "AlertDescription"
|
|
||||||
|
|
||||||
export { Alert, AlertDescription }
|
|
||||||
@@ -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,14 +38,9 @@ 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 top-8 left-0 right-0 bottom-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
|
||||||
)}
|
)}
|
||||||
style={{
|
|
||||||
// Garantir que o overlay não bloqueie eventos na área do TitleBar (topo 32px)
|
|
||||||
clipPath: 'inset(0 0 0 0)',
|
|
||||||
pointerEvents: 'auto'
|
|
||||||
}}
|
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
@@ -65,17 +60,16 @@ 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-[calc(50%+16px)] 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
|
||||||
)}
|
)}
|
||||||
style={{ pointerEvents: 'auto' }}
|
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
{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>
|
||||||
@@ -116,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}
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import * as React from "react"
|
|
||||||
import * as PopoverPrimitive from "@radix-ui/react-popover"
|
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
const Popover = PopoverPrimitive.Root
|
|
||||||
|
|
||||||
const PopoverTrigger = PopoverPrimitive.Trigger
|
|
||||||
|
|
||||||
const PopoverContent = React.forwardRef<
|
|
||||||
React.ElementRef<typeof PopoverPrimitive.Content>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
|
|
||||||
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
|
|
||||||
<PopoverPrimitive.Portal>
|
|
||||||
<PopoverPrimitive.Content
|
|
||||||
ref={ref}
|
|
||||||
align={align}
|
|
||||||
sideOffset={sideOffset}
|
|
||||||
className={cn(
|
|
||||||
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none 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
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
</PopoverPrimitive.Portal>
|
|
||||||
))
|
|
||||||
PopoverContent.displayName = PopoverPrimitive.Content.displayName
|
|
||||||
|
|
||||||
export { Popover, PopoverTrigger, PopoverContent }
|
|
||||||
@@ -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}
|
||||||
/>
|
/>
|
||||||
))
|
))
|
||||||
|
|||||||
@@ -1,67 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState } from 'react';
|
|
||||||
import { useOllamaHealth } from '@/contexts/ollama-health-context';
|
|
||||||
import { useSettingsStore } from '@/store/settings-store';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { AlertTriangle, RefreshCw, Power } from 'lucide-react';
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
|
||||||
|
|
||||||
export function ServiceInterruptionOverlay() {
|
|
||||||
const { isOllamaRunning, isChecking, checkNow } = useOllamaHealth();
|
|
||||||
const isSetupCompleted = useSettingsStore((s) => s.isSetupCompleted);
|
|
||||||
const [starting, setStarting] = useState(false);
|
|
||||||
|
|
||||||
const tryStartOllama = async () => {
|
|
||||||
setStarting(true);
|
|
||||||
try {
|
|
||||||
await invoke<boolean>('auto_start_ollama');
|
|
||||||
await checkNow();
|
|
||||||
} catch {}
|
|
||||||
setStarting(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
if (isOllamaRunning || !isSetupCompleted) return null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="fixed inset-0 z-50 bg-black/90 backdrop-blur-sm flex items-center justify-center p-6">
|
|
||||||
<div className="max-w-md w-full border rounded-lg bg-zinc-900 text-white p-6 shadow-xl">
|
|
||||||
<div className="flex items-center gap-3 mb-4">
|
|
||||||
<AlertTriangle className="w-6 h-6 text-yellow-400" />
|
|
||||||
<h2 className="text-lg font-semibold">Conexão com Ollama Perdida</h2>
|
|
||||||
</div>
|
|
||||||
<p className="text-sm text-zinc-300 mb-4">
|
|
||||||
O serviço Ollama não está respondendo. Verifique se ele está aberto.
|
|
||||||
</p>
|
|
||||||
<div className="flex items-center gap-2 mb-6">
|
|
||||||
{isChecking ? (
|
|
||||||
<span className="text-xs text-zinc-400 flex items-center gap-2">
|
|
||||||
<RefreshCw className="w-4 h-4 animate-spin" /> Tentando reconectar...
|
|
||||||
</span>
|
|
||||||
) : (
|
|
||||||
<Button variant="ghost" size="sm" onClick={checkNow}>
|
|
||||||
<RefreshCw className="w-4 h-4" /> Verificar novamente
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<Button onClick={tryStartOllama} disabled={starting} className="flex-1">
|
|
||||||
{starting ? (
|
|
||||||
<>
|
|
||||||
<RefreshCw className="w-4 h-4 animate-spin" /> Iniciando Ollama...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Power className="w-4 h-4" /> Tentar abrir Ollama
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
<Button variant="outline" size="sm" onClick={checkNow}>
|
|
||||||
Testar novamente
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -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>
|
||||||
|
|||||||
@@ -1,117 +0,0 @@
|
|||||||
import * as React from "react"
|
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
const Table = React.forwardRef<
|
|
||||||
HTMLTableElement,
|
|
||||||
React.HTMLAttributes<HTMLTableElement>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<div className="relative w-full overflow-auto">
|
|
||||||
<table
|
|
||||||
ref={ref}
|
|
||||||
className={cn("w-full caption-bottom text-sm", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
))
|
|
||||||
Table.displayName = "Table"
|
|
||||||
|
|
||||||
const TableHeader = React.forwardRef<
|
|
||||||
HTMLTableSectionElement,
|
|
||||||
React.HTMLAttributes<HTMLTableSectionElement>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
|
|
||||||
))
|
|
||||||
TableHeader.displayName = "TableHeader"
|
|
||||||
|
|
||||||
const TableBody = React.forwardRef<
|
|
||||||
HTMLTableSectionElement,
|
|
||||||
React.HTMLAttributes<HTMLTableSectionElement>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<tbody
|
|
||||||
ref={ref}
|
|
||||||
className={cn("[&_tr:last-child]:border-0", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
TableBody.displayName = "TableBody"
|
|
||||||
|
|
||||||
const TableFooter = React.forwardRef<
|
|
||||||
HTMLTableSectionElement,
|
|
||||||
React.HTMLAttributes<HTMLTableSectionElement>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<tfoot
|
|
||||||
ref={ref}
|
|
||||||
className={cn(
|
|
||||||
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
TableFooter.displayName = "TableFooter"
|
|
||||||
|
|
||||||
const TableRow = React.forwardRef<
|
|
||||||
HTMLTableRowElement,
|
|
||||||
React.HTMLAttributes<HTMLTableRowElement>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<tr
|
|
||||||
ref={ref}
|
|
||||||
className={cn(
|
|
||||||
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
TableRow.displayName = "TableRow"
|
|
||||||
|
|
||||||
const TableHead = React.forwardRef<
|
|
||||||
HTMLTableCellElement,
|
|
||||||
React.ThHTMLAttributes<HTMLTableCellElement>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<th
|
|
||||||
ref={ref}
|
|
||||||
className={cn(
|
|
||||||
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
TableHead.displayName = "TableHead"
|
|
||||||
|
|
||||||
const TableCell = React.forwardRef<
|
|
||||||
HTMLTableCellElement,
|
|
||||||
React.TdHTMLAttributes<HTMLTableCellElement>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<td
|
|
||||||
ref={ref}
|
|
||||||
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
TableCell.displayName = "TableCell"
|
|
||||||
|
|
||||||
const TableCaption = React.forwardRef<
|
|
||||||
HTMLTableCaptionElement,
|
|
||||||
React.HTMLAttributes<HTMLTableCaptionElement>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<caption
|
|
||||||
ref={ref}
|
|
||||||
className={cn("mt-4 text-sm text-muted-foreground", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
TableCaption.displayName = "TableCaption"
|
|
||||||
|
|
||||||
export {
|
|
||||||
Table,
|
|
||||||
TableHeader,
|
|
||||||
TableBody,
|
|
||||||
TableFooter,
|
|
||||||
TableHead,
|
|
||||||
TableRow,
|
|
||||||
TableCell,
|
|
||||||
TableCaption,
|
|
||||||
}
|
|
||||||
@@ -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,346 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { createContext, useContext, useState, useEffect, useRef, useCallback, ReactNode } from 'react';
|
|
||||||
import { listen } from '@tauri-apps/api/event';
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
|
||||||
|
|
||||||
// Helper para formatar bytes em formato legível (KB, MB, GB)
|
|
||||||
function formatBytes(bytes: number): string {
|
|
||||||
if (bytes === 0) return '0 B';
|
|
||||||
const k = 1024;
|
|
||||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
|
||||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
||||||
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper para formatar velocidade em formato legível
|
|
||||||
function formatSpeed(bytesPerSec: number): string {
|
|
||||||
if (bytesPerSec === 0) return '0 B/s';
|
|
||||||
const k = 1024;
|
|
||||||
const sizes = ['B/s', 'KB/s', 'MB/s', 'GB/s'];
|
|
||||||
const i = Math.floor(Math.log(bytesPerSec) / Math.log(k));
|
|
||||||
return `${parseFloat((bytesPerSec / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper para parsear string formatada (ex: "552 MB") para bytes
|
|
||||||
function parseFormattedBytes(formatted: string): number {
|
|
||||||
if (!formatted || typeof formatted !== 'string') return 0;
|
|
||||||
|
|
||||||
const match = formatted.match(/([\d.]+)\s*(B|KB|MB|GB)/i);
|
|
||||||
if (!match) return 0;
|
|
||||||
|
|
||||||
const value = parseFloat(match[1]);
|
|
||||||
const unit = match[2].toUpperCase();
|
|
||||||
const multiplier =
|
|
||||||
unit === 'GB' ? 1024 * 1024 * 1024 :
|
|
||||||
unit === 'MB' ? 1024 * 1024 :
|
|
||||||
unit === 'KB' ? 1024 : 1;
|
|
||||||
|
|
||||||
return value * multiplier;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface DownloadProgress {
|
|
||||||
percent: number | null; // null = indeterminado
|
|
||||||
downloadedBytes: number; // em bytes
|
|
||||||
totalBytes: number; // em bytes
|
|
||||||
downloadedFormatted: string; // "552 MB"
|
|
||||||
totalFormatted: string; // "1.2 GB"
|
|
||||||
speed: string; // "25 MB/s" (calculado no frontend)
|
|
||||||
status: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface DownloadState {
|
|
||||||
isDownloading: boolean;
|
|
||||||
isSuccess: boolean; // NOVO: indica se download foi concluído com sucesso
|
|
||||||
progress: DownloadProgress;
|
|
||||||
currentModel: string | null;
|
|
||||||
error: string | null;
|
|
||||||
isCancelling: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface DownloadContextType {
|
|
||||||
state: DownloadState;
|
|
||||||
startDownload: (modelName: string) => Promise<void>;
|
|
||||||
cancelDownload: () => void;
|
|
||||||
clearError: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
const DownloadContext = createContext<DownloadContextType | undefined>(undefined);
|
|
||||||
|
|
||||||
export function DownloadProvider({ children }: { children: ReactNode }) {
|
|
||||||
const [state, setState] = useState<DownloadState>({
|
|
||||||
isDownloading: false,
|
|
||||||
isSuccess: false,
|
|
||||||
progress: {
|
|
||||||
percent: null,
|
|
||||||
downloadedBytes: 0,
|
|
||||||
totalBytes: 0,
|
|
||||||
downloadedFormatted: '0 B',
|
|
||||||
totalFormatted: '0 B',
|
|
||||||
speed: '0 B/s',
|
|
||||||
status: '',
|
|
||||||
},
|
|
||||||
currentModel: null,
|
|
||||||
error: null,
|
|
||||||
isCancelling: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
const abortControllerRef = useRef<AbortController | null>(null);
|
|
||||||
const unlistenRef = useRef<(() => void) | null>(null);
|
|
||||||
const isCancellingRef = useRef(false);
|
|
||||||
const lastDownloadedBytesRef = useRef<number>(0);
|
|
||||||
const lastUpdateTimeRef = useRef<number>(0);
|
|
||||||
|
|
||||||
// Sincronizar ref com estado
|
|
||||||
useEffect(() => {
|
|
||||||
isCancellingRef.current = state.isCancelling;
|
|
||||||
}, [state.isCancelling]);
|
|
||||||
|
|
||||||
// Escutar eventos de progresso do download
|
|
||||||
useEffect(() => {
|
|
||||||
if (!state.isDownloading) {
|
|
||||||
// Limpar listener quando não estiver baixando
|
|
||||||
if (unlistenRef.current) {
|
|
||||||
unlistenRef.current();
|
|
||||||
unlistenRef.current = null;
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const setupListener = async () => {
|
|
||||||
const unlisten = await listen<string>('download-progress', (event) => {
|
|
||||||
if (isCancellingRef.current) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(event.payload);
|
|
||||||
|
|
||||||
const status = data.status || '';
|
|
||||||
|
|
||||||
// Usar percent do backend diretamente (já calculado corretamente)
|
|
||||||
// Se não estiver disponível e tivermos completed/total, calcular
|
|
||||||
let percent: number | null = data.percent !== undefined ? data.percent : null;
|
|
||||||
|
|
||||||
// Parsear valores formatados do backend para bytes
|
|
||||||
let downloadedBytes = 0;
|
|
||||||
let totalBytes = 0;
|
|
||||||
|
|
||||||
if (data.downloaded) {
|
|
||||||
downloadedBytes = typeof data.downloaded === 'string'
|
|
||||||
? parseFormattedBytes(data.downloaded)
|
|
||||||
: data.downloaded;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.total) {
|
|
||||||
totalBytes = typeof data.total === 'string'
|
|
||||||
? parseFormattedBytes(data.total)
|
|
||||||
: data.total;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Se percent não veio do backend mas temos valores brutos, calcular
|
|
||||||
if (percent === null && totalBytes > 0 && downloadedBytes > 0) {
|
|
||||||
percent = Math.round((downloadedBytes / totalBytes) * 100);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Se total for 0 ou indefinido, percent fica null (indeterminado)
|
|
||||||
if (totalBytes === 0) {
|
|
||||||
percent = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Calcular velocidade em tempo real usando refs
|
|
||||||
const now = Date.now();
|
|
||||||
let calculatedSpeed = '0 B/s';
|
|
||||||
|
|
||||||
if (downloadedBytes > 0) {
|
|
||||||
// Primeira atualização: inicializar timestamp
|
|
||||||
if (lastUpdateTimeRef.current === 0) {
|
|
||||||
lastUpdateTimeRef.current = now;
|
|
||||||
lastDownloadedBytesRef.current = downloadedBytes;
|
|
||||||
// Usar velocidade do backend se disponível, senão 0
|
|
||||||
calculatedSpeed = data.speed || '0 B/s';
|
|
||||||
} else {
|
|
||||||
const deltaTime = (now - lastUpdateTimeRef.current) / 1000; // em segundos
|
|
||||||
|
|
||||||
if (deltaTime > 0 && downloadedBytes > lastDownloadedBytesRef.current) {
|
|
||||||
const deltaBytes = downloadedBytes - lastDownloadedBytesRef.current;
|
|
||||||
const bytesPerSec = deltaBytes / deltaTime;
|
|
||||||
calculatedSpeed = formatSpeed(bytesPerSec);
|
|
||||||
} else {
|
|
||||||
// Sem mudança ou tempo inválido, manter velocidade anterior ou do backend
|
|
||||||
calculatedSpeed = data.speed || '0 B/s';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Atualizar refs para próximo cálculo
|
|
||||||
lastDownloadedBytesRef.current = downloadedBytes;
|
|
||||||
lastUpdateTimeRef.current = now;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Formatar valores para exibição
|
|
||||||
const downloadedFormatted = downloadedBytes > 0 ? formatBytes(downloadedBytes) : (data.downloaded || '0 B');
|
|
||||||
const totalFormatted = totalBytes > 0 ? formatBytes(totalBytes) : (data.total || '0 B');
|
|
||||||
|
|
||||||
// Determinar se é sucesso
|
|
||||||
const isSuccess = status === 'success' || percent === 100;
|
|
||||||
|
|
||||||
setState(prev => ({
|
|
||||||
...prev,
|
|
||||||
isSuccess: isSuccess,
|
|
||||||
isDownloading: !isSuccess,
|
|
||||||
progress: {
|
|
||||||
percent: percent !== null ? percent : prev.progress.percent,
|
|
||||||
downloadedBytes: downloadedBytes || prev.progress.downloadedBytes,
|
|
||||||
totalBytes: totalBytes || prev.progress.totalBytes,
|
|
||||||
downloadedFormatted: downloadedFormatted,
|
|
||||||
totalFormatted: totalFormatted,
|
|
||||||
speed: calculatedSpeed,
|
|
||||||
status: status || prev.progress.status,
|
|
||||||
},
|
|
||||||
isCancelling: false,
|
|
||||||
}));
|
|
||||||
|
|
||||||
if (isSuccess) {
|
|
||||||
// Não resetar progresso - manter em 100% para feedback visual
|
|
||||||
setState(prev => ({
|
|
||||||
...prev,
|
|
||||||
isDownloading: false,
|
|
||||||
isSuccess: true,
|
|
||||||
progress: {
|
|
||||||
...prev.progress,
|
|
||||||
percent: 100,
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
if (unlistenRef.current) {
|
|
||||||
unlistenRef.current();
|
|
||||||
unlistenRef.current = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao processar evento de progresso:', error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
unlistenRef.current = unlisten;
|
|
||||||
};
|
|
||||||
|
|
||||||
setupListener();
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
if (unlistenRef.current) {
|
|
||||||
unlistenRef.current();
|
|
||||||
unlistenRef.current = null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, [state.isDownloading, state.isCancelling]);
|
|
||||||
|
|
||||||
const startDownload = useCallback(async (modelName: string) => {
|
|
||||||
if (state.isDownloading) {
|
|
||||||
console.warn('Download já em andamento');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Resetar refs para cálculo de velocidade
|
|
||||||
lastDownloadedBytesRef.current = 0;
|
|
||||||
lastUpdateTimeRef.current = Date.now();
|
|
||||||
|
|
||||||
setState({
|
|
||||||
isDownloading: true,
|
|
||||||
isSuccess: false,
|
|
||||||
progress: {
|
|
||||||
percent: null,
|
|
||||||
downloadedBytes: 0,
|
|
||||||
totalBytes: 0,
|
|
||||||
downloadedFormatted: '0 B',
|
|
||||||
totalFormatted: '0 B',
|
|
||||||
speed: '0 B/s',
|
|
||||||
status: 'Iniciando download...',
|
|
||||||
},
|
|
||||||
currentModel: modelName,
|
|
||||||
error: null,
|
|
||||||
isCancelling: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
abortControllerRef.current = new AbortController();
|
|
||||||
|
|
||||||
try {
|
|
||||||
await invoke('download_default_model_command', { modelName });
|
|
||||||
} catch (error) {
|
|
||||||
const errorMsg = error instanceof Error ? error.message : 'Erro desconhecido durante download';
|
|
||||||
setState(prev => ({
|
|
||||||
...prev,
|
|
||||||
isDownloading: false,
|
|
||||||
isSuccess: false,
|
|
||||||
error: errorMsg,
|
|
||||||
isCancelling: false,
|
|
||||||
}));
|
|
||||||
|
|
||||||
if (unlistenRef.current) {
|
|
||||||
unlistenRef.current();
|
|
||||||
unlistenRef.current = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [state.isDownloading]);
|
|
||||||
|
|
||||||
const cancelDownload = useCallback(async () => {
|
|
||||||
if (!state.isDownloading) return;
|
|
||||||
|
|
||||||
setState(prev => ({
|
|
||||||
...prev,
|
|
||||||
isCancelling: true,
|
|
||||||
}));
|
|
||||||
|
|
||||||
try {
|
|
||||||
await invoke('cancel_download');
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Falha ao cancelar no backend:', error);
|
|
||||||
}
|
|
||||||
|
|
||||||
setState(prev => ({
|
|
||||||
...prev,
|
|
||||||
isDownloading: false,
|
|
||||||
isCancelling: false,
|
|
||||||
progress: {
|
|
||||||
...prev.progress,
|
|
||||||
status: 'Cancelado',
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
if (unlistenRef.current) {
|
|
||||||
unlistenRef.current();
|
|
||||||
unlistenRef.current = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Limpar AbortController local
|
|
||||||
if (abortControllerRef.current) {
|
|
||||||
abortControllerRef.current = null;
|
|
||||||
}
|
|
||||||
}, [state.isDownloading]);
|
|
||||||
|
|
||||||
const clearError = useCallback(() => {
|
|
||||||
setState(prev => ({
|
|
||||||
...prev,
|
|
||||||
error: null,
|
|
||||||
}));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<DownloadContext.Provider
|
|
||||||
value={{
|
|
||||||
state,
|
|
||||||
startDownload,
|
|
||||||
cancelDownload,
|
|
||||||
clearError,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</DownloadContext.Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useDownloadContext() {
|
|
||||||
const context = useContext(DownloadContext);
|
|
||||||
if (context === undefined) {
|
|
||||||
throw new Error('useDownloadContext deve ser usado dentro de DownloadProvider');
|
|
||||||
}
|
|
||||||
return context;
|
|
||||||
}
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { createContext, useContext, useEffect, useMemo, useRef, useState, ReactNode } from 'react';
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
|
||||||
import { usePathname } from 'next/navigation';
|
|
||||||
import { useSettingsStore } from '@/store/settings-store';
|
|
||||||
|
|
||||||
interface OllamaHealthContextType {
|
|
||||||
isOllamaRunning: boolean;
|
|
||||||
lastCheckedAt: number | null;
|
|
||||||
isChecking: boolean;
|
|
||||||
checkNow: () => Promise<void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const OllamaHealthContext = createContext<OllamaHealthContextType | undefined>(undefined);
|
|
||||||
|
|
||||||
export function OllamaHealthProvider({ children }: { children: ReactNode }) {
|
|
||||||
const [isOllamaRunning, setIsOllamaRunning] = useState<boolean>(true);
|
|
||||||
const [lastCheckedAt, setLastCheckedAt] = useState<number | null>(null);
|
|
||||||
const [isChecking, setIsChecking] = useState<boolean>(false);
|
|
||||||
const intervalRef = useRef<NodeJS.Timeout | null>(null);
|
|
||||||
const mountedRef = useRef<boolean>(false);
|
|
||||||
const pathname = usePathname();
|
|
||||||
const isSetupCompleted = useSettingsStore((s) => s.isSetupCompleted);
|
|
||||||
|
|
||||||
const shouldPoll = useMemo(() => {
|
|
||||||
if (!isSetupCompleted) return false;
|
|
||||||
if (!pathname) return true;
|
|
||||||
return !pathname.startsWith('/setup');
|
|
||||||
}, [pathname, isSetupCompleted]);
|
|
||||||
|
|
||||||
const checkNow = async () => {
|
|
||||||
try {
|
|
||||||
if (!mountedRef.current) return;
|
|
||||||
setIsChecking(true);
|
|
||||||
const ok = await invoke<boolean>('check_ollama_heartbeat');
|
|
||||||
if (!mountedRef.current) return;
|
|
||||||
setIsOllamaRunning(!!ok);
|
|
||||||
setLastCheckedAt(Date.now());
|
|
||||||
} catch {
|
|
||||||
if (!mountedRef.current) return;
|
|
||||||
setIsOllamaRunning(false);
|
|
||||||
setLastCheckedAt(Date.now());
|
|
||||||
} finally {
|
|
||||||
if (!mountedRef.current) return;
|
|
||||||
setIsChecking(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
mountedRef.current = true;
|
|
||||||
return () => {
|
|
||||||
mountedRef.current = false;
|
|
||||||
if (intervalRef.current) {
|
|
||||||
clearInterval(intervalRef.current);
|
|
||||||
intervalRef.current = null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!shouldPoll) {
|
|
||||||
if (intervalRef.current) {
|
|
||||||
clearInterval(intervalRef.current);
|
|
||||||
intervalRef.current = null;
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// primeira verificação imediata após mount
|
|
||||||
setTimeout(() => { checkNow(); }, 0);
|
|
||||||
// polling
|
|
||||||
intervalRef.current = setInterval(() => { if (mountedRef.current) { checkNow(); } }, 3000);
|
|
||||||
return () => {
|
|
||||||
if (intervalRef.current) {
|
|
||||||
clearInterval(intervalRef.current);
|
|
||||||
intervalRef.current = null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, [shouldPoll]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<OllamaHealthContext.Provider value={{ isOllamaRunning, lastCheckedAt, isChecking, checkNow }}>
|
|
||||||
{children}
|
|
||||||
</OllamaHealthContext.Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useOllamaHealth() {
|
|
||||||
const ctx = useContext(OllamaHealthContext);
|
|
||||||
if (!ctx) throw new Error('useOllamaHealth deve ser usado dentro de OllamaHealthProvider');
|
|
||||||
return ctx;
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
{
|
|
||||||
"version": "0.1.0",
|
|
||||||
"generatedAt": "2025-11-28T03:22:48.992Z",
|
|
||||||
"releases": []
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
version: "3.7"
|
|
||||||
|
|
||||||
services:
|
|
||||||
searxng:
|
|
||||||
image: searxng/searxng:latest
|
|
||||||
container_name: ollaHub_searxng
|
|
||||||
ports:
|
|
||||||
- "8080:8080"
|
|
||||||
volumes:
|
|
||||||
- searxng_data:/etc/searxng:rw
|
|
||||||
environment:
|
|
||||||
- SEARXNG_BASE_URL=http://localhost:8080/
|
|
||||||
restart: unless-stopped
|
|
||||||
networks:
|
|
||||||
- searxng_network
|
|
||||||
|
|
||||||
redis:
|
|
||||||
image: redis:alpine
|
|
||||||
container_name: ollaHub_searxng_redis
|
|
||||||
command: redis-server --save "" --appendonly "no"
|
|
||||||
networks:
|
|
||||||
- searxng_network
|
|
||||||
tmpfs:
|
|
||||||
- /var/lib/redis
|
|
||||||
|
|
||||||
volumes:
|
|
||||||
searxng_data:
|
|
||||||
|
|
||||||
networks:
|
|
||||||
searxng_network:
|
|
||||||
driver: bridge
|
|
||||||
+10
-21
@@ -49,14 +49,6 @@ export function useAppUpdater(): AppUpdaterState {
|
|||||||
|
|
||||||
// Verificar atualizações
|
// Verificar atualizações
|
||||||
const checkUpdate = useCallback(async () => {
|
const checkUpdate = useCallback(async () => {
|
||||||
<<<<<<< HEAD
|
|
||||||
// Ignorar verificação de updates em ambiente de desenvolvimento
|
|
||||||
if (process.env.NODE_ENV === 'development') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
=======
|
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
setIsChecking(true);
|
setIsChecking(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
@@ -95,31 +87,28 @@ export function useAppUpdater(): AppUpdaterState {
|
|||||||
const update = await checkForUpdate();
|
const update = await checkForUpdate();
|
||||||
|
|
||||||
if (update?.available) {
|
if (update?.available) {
|
||||||
|
// Escutar progresso do download
|
||||||
|
const unlisten = await update.on('download-progress', (progress: any) => {
|
||||||
|
setDownloadProgress(progress.progress || 0);
|
||||||
|
});
|
||||||
|
|
||||||
// Baixar e instalar atualização
|
// Baixar e instalar atualização
|
||||||
// O progresso pode ser monitorado via eventos do Tauri se necessário
|
|
||||||
await update.downloadAndInstall();
|
await update.downloadAndInstall();
|
||||||
|
|
||||||
// Após downloadAndInstall(), o app será reiniciado automaticamente
|
unlisten();
|
||||||
// Não é necessário chamar installAndRestart() que não existe na API
|
|
||||||
|
// Reiniciar aplicativo após instalação
|
||||||
|
await update.installAndRestart();
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to install update:', err);
|
console.error('Failed to install update:', err);
|
||||||
setError(err instanceof Error ? err.message : 'Erro ao instalar atualização');
|
setError(err instanceof Error ? err.message : 'Erro ao instalar atualização');
|
||||||
setIsDownloading(false);
|
setIsDownloading(false);
|
||||||
setDownloadProgress(0);
|
|
||||||
}
|
}
|
||||||
}, [updateAvailable]);
|
}, [updateAvailable]);
|
||||||
|
|
||||||
// Verificação automática periódica (a cada 6 horas)
|
// Verificação automática periódica (a cada 6 horas)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
<<<<<<< HEAD
|
|
||||||
// Ignorar verificação automática em desenvolvimento
|
|
||||||
if (process.env.NODE_ENV === 'development') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
=======
|
|
||||||
>>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5
|
|
||||||
if (!autoCheckEnabled) return;
|
if (!autoCheckEnabled) return;
|
||||||
|
|
||||||
// Verificar imediatamente ao montar (com delay para não interferir no carregamento)
|
// Verificar imediatamente ao montar (com delay para não interferir no carregamento)
|
||||||
|
|||||||
@@ -15,8 +15,7 @@ export function useAutoLabelingModel() {
|
|||||||
|
|
||||||
const checkAndDownload = async () => {
|
const checkAndDownload = async () => {
|
||||||
try {
|
try {
|
||||||
// O comando Tauri é check_if_model_installed_command, mas o Tauri remove o sufixo _command
|
const installed = await invoke<boolean>('check_if_model_installed', { name: TARGET_MODEL });
|
||||||
const installed = await invoke<boolean>('check_if_model_installed_command', { name: TARGET_MODEL });
|
|
||||||
if (installed) {
|
if (installed) {
|
||||||
setIsReady(true);
|
setIsReady(true);
|
||||||
return;
|
return;
|
||||||
@@ -50,25 +49,6 @@ export function useAutoLabelingModel() {
|
|||||||
setIsDownloading(false);
|
setIsDownloading(false);
|
||||||
setIsReady(true);
|
setIsReady(true);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Detectar erros de conexão/rede e tratá-los silenciosamente
|
|
||||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
||||||
const isConnectionError =
|
|
||||||
errorMessage.toLowerCase().includes('connection') ||
|
|
||||||
errorMessage.toLowerCase().includes('network') ||
|
|
||||||
errorMessage.toLowerCase().includes('econnrefused') ||
|
|
||||||
errorMessage.toLowerCase().includes('timeout') ||
|
|
||||||
errorMessage.toLowerCase().includes('failed to connect') ||
|
|
||||||
errorMessage.toLowerCase().includes('connection refused');
|
|
||||||
|
|
||||||
if (isConnectionError) {
|
|
||||||
// Erro de conexão: Ollama está offline - tratar silenciosamente
|
|
||||||
// Não logar console.error para não poluir o console
|
|
||||||
setIsDownloading(false);
|
|
||||||
setIsReady(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Outros erros: manter log atual para debug
|
|
||||||
console.error("Failed to setup auto-labeling model:", error);
|
console.error("Failed to setup auto-labeling model:", error);
|
||||||
setIsDownloading(false);
|
setIsDownloading(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,17 +37,24 @@ export function useBatchVerify() {
|
|||||||
|
|
||||||
const callLLM = async (model: string, prompt: string, json = false) => {
|
const callLLM = async (model: string, prompt: string, json = false) => {
|
||||||
try {
|
try {
|
||||||
const { invoke } = await import('@tauri-apps/api/core');
|
const response = await fetch('http://localhost:11434/api/generate', {
|
||||||
const response = await invoke<string>('generate_completion', {
|
method: 'POST',
|
||||||
model,
|
headers: { 'Content-Type': 'application/json' },
|
||||||
prompt,
|
body: JSON.stringify({
|
||||||
options: {
|
model,
|
||||||
temperature: 0.3,
|
prompt,
|
||||||
num_predict: 1024,
|
stream: false,
|
||||||
format: json ? 'json' : undefined,
|
format: json ? 'json' : undefined,
|
||||||
},
|
options: {
|
||||||
|
temperature: 0.3,
|
||||||
|
num_predict: 1024,
|
||||||
|
},
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
return response;
|
|
||||||
|
if (!response.ok) throw new Error('Failed to call LLM');
|
||||||
|
const data = await response.json();
|
||||||
|
return data.response;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('LLM Call Error:', e);
|
console.error('LLM Call Error:', e);
|
||||||
throw e;
|
throw e;
|
||||||
|
|||||||
+45
-18
@@ -254,15 +254,29 @@ export function useChatStorage() {
|
|||||||
const generateTitleFromUserMessage = async (userMessage: string): Promise<string> => {
|
const generateTitleFromUserMessage = async (userMessage: string): Promise<string> => {
|
||||||
// Generate title immediately from user's first message
|
// Generate title immediately from user's first message
|
||||||
try {
|
try {
|
||||||
const { invoke } = await import('@tauri-apps/api/core');
|
const response = await fetch('http://localhost:11434/api/chat', {
|
||||||
let title = await invoke<string>('generate_chat_completion', {
|
method: 'POST',
|
||||||
model: TITLE_MODEL,
|
headers: { 'Content-Type': 'application/json' },
|
||||||
messages: [
|
body: JSON.stringify({
|
||||||
{ role: 'system', content: 'Generate a short title (3-5 words) for a chat conversation based on this user message. Output ONLY the title, no explanation.' },
|
model: TITLE_MODEL,
|
||||||
{ role: 'user', content: userMessage }
|
messages: [
|
||||||
],
|
{ role: 'system', content: 'Generate a short title (3-5 words) for a chat conversation based on this user message. Output ONLY the title, no explanation.' },
|
||||||
options: undefined,
|
{ role: 'user', content: userMessage }
|
||||||
|
],
|
||||||
|
stream: false,
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
// If model not available, use fallback
|
||||||
|
if (response.status === 404 || response.status >= 500) {
|
||||||
|
throw new Error(`Model ${TITLE_MODEL} not available (status: ${response.status})`);
|
||||||
|
}
|
||||||
|
throw new Error(`Title generation failed with status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
let title = data.message?.content?.trim() || "";
|
||||||
|
|
||||||
// If empty from start, use fallback
|
// If empty from start, use fallback
|
||||||
if (!title || title.length === 0) {
|
if (!title || title.length === 0) {
|
||||||
@@ -306,17 +320,30 @@ export function useChatStorage() {
|
|||||||
content: removeMetadataNoise(m.content),
|
content: removeMetadataNoise(m.content),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const { invoke } = await import('@tauri-apps/api/core');
|
const response = await fetch('http://localhost:11434/api/chat', {
|
||||||
const rawTitle = await invoke<string>('generate_chat_completion', {
|
method: 'POST',
|
||||||
model: TITLE_MODEL,
|
headers: { 'Content-Type': 'application/json' },
|
||||||
messages: [
|
body: JSON.stringify({
|
||||||
{ role: 'system', content: 'Summarize the following conversation in 3 to 5 words representing a short title. Output ONLY the title, sem metadados.' },
|
model: TITLE_MODEL,
|
||||||
|
messages: [
|
||||||
|
{ role: 'system', content: 'Summarize the following conversation in 3 to 5 words representing a short title. Output ONLY the title, sem metadados.' },
|
||||||
...sanitizedMessages
|
...sanitizedMessages
|
||||||
],
|
],
|
||||||
options: undefined,
|
stream: false,
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
// If model not found or unavailable, throw to trigger fallback
|
||||||
|
if (response.status === 404 || response.status >= 500) {
|
||||||
|
throw new Error(`Model ${TITLE_MODEL} not available (status: ${response.status})`);
|
||||||
|
}
|
||||||
|
// For other errors, use fallback
|
||||||
|
throw new Error(`Title generation failed with status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
let title = removeMetadataNoise(rawTitle?.trim() || "");
|
const data = await response.json();
|
||||||
|
let title = removeMetadataNoise(data.message?.content?.trim() || "");
|
||||||
|
|
||||||
// If empty from start, throw to trigger fallback
|
// If empty from start, throw to trigger fallback
|
||||||
if (!title || title.length === 0) {
|
if (!title || title.length === 0) {
|
||||||
@@ -365,7 +392,7 @@ export function useChatStorage() {
|
|||||||
const keywords = Array.isArray(msg.metadata.keywords)
|
const keywords = Array.isArray(msg.metadata.keywords)
|
||||||
? msg.metadata.keywords
|
? msg.metadata.keywords
|
||||||
: [];
|
: [];
|
||||||
memoryContext.push(...keywords.filter((k: unknown) => typeof k === 'string'));
|
memoryContext.push(...keywords.filter(k => typeof k === 'string'));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const uniqueMemoryContext = Array.from(new Set(memoryContext));
|
const uniqueMemoryContext = Array.from(new Set(memoryContext));
|
||||||
@@ -430,7 +457,7 @@ export function useChatStorage() {
|
|||||||
const keywords = Array.isArray(msg.metadata.keywords)
|
const keywords = Array.isArray(msg.metadata.keywords)
|
||||||
? msg.metadata.keywords
|
? msg.metadata.keywords
|
||||||
: [];
|
: [];
|
||||||
memoryContext.push(...keywords.filter((k: unknown) => typeof k === 'string'));
|
memoryContext.push(...keywords.filter(k => typeof k === 'string'));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
// Deduplicate
|
// Deduplicate
|
||||||
|
|||||||
+3
-16
@@ -26,8 +26,6 @@ export interface ThinkingMessageMetadata {
|
|||||||
error?: string;
|
error?: string;
|
||||||
timestamp: number;
|
timestamp: number;
|
||||||
duration?: number;
|
duration?: number;
|
||||||
activeQueries?: Array<{ query: string; source: string; round?: number; startedAt: number }>;
|
|
||||||
activeUrls?: Array<{ url: string; title?: string; status: string; source?: string; startedAt: number; duration?: number }>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Message {
|
export interface Message {
|
||||||
@@ -530,21 +528,10 @@ export function useChat() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const stop = async () => {
|
const stop = () => {
|
||||||
try {
|
if (abortControllerRef.current) {
|
||||||
// Cancelar processamento de scraping (prioridade alta)
|
abortControllerRef.current.abort();
|
||||||
try {
|
|
||||||
await invoke('cancel_scraping');
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Erro ao cancelar scraping:', e);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (currentSessionIdRef.current) {
|
|
||||||
await invoke('stop_processing', { sessionId: currentSessionIdRef.current });
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
abortControllerRef.current = null;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+72
-97
@@ -23,7 +23,7 @@ export interface DeepResearchLog {
|
|||||||
timestamp: number;
|
timestamp: number;
|
||||||
input: string;
|
input: string;
|
||||||
rawOutput?: string;
|
rawOutput?: string;
|
||||||
parsedOutput?: unknown;
|
parsedOutput?: any;
|
||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,7 +47,7 @@ function logStep(message: string) {
|
|||||||
log.info(message);
|
log.info(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
function logData(label: string, data: unknown) {
|
function logData(label: string, data: any) {
|
||||||
if (typeof data === 'string' && data.length > 500) {
|
if (typeof data === 'string' && data.length > 500) {
|
||||||
log.info(`${label}: ${data.substring(0, 500)}... [truncated, ${data.length} chars total]`);
|
log.info(`${label}: ${data.substring(0, 500)}... [truncated, ${data.length} chars total]`);
|
||||||
} else if (typeof data === 'object') {
|
} else if (typeof data === 'object') {
|
||||||
@@ -57,7 +57,7 @@ function logData(label: string, data: unknown) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function logError(message: string, error?: unknown) {
|
function logError(message: string, error?: any) {
|
||||||
log.error(`❌ ERROR: ${message}${error ? ` - ${error}` : ''}`);
|
log.error(`❌ ERROR: ${message}${error ? ` - ${error}` : ''}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,17 +75,17 @@ function extractQueriesFromResponse(raw: string): string[] {
|
|||||||
logData('Raw response', raw);
|
logData('Raw response', raw);
|
||||||
|
|
||||||
// 1. Strip markdown code blocks (```json ... ``` or ``` ... ```)
|
// 1. Strip markdown code blocks (```json ... ``` or ``` ... ```)
|
||||||
const cleaned = raw
|
let cleaned = raw
|
||||||
.replace(/```json\s*/gi, '')
|
.replace(/```json\s*/gi, '')
|
||||||
.replace(/```\s*/g, '')
|
.replace(/```\s*/g, '')
|
||||||
.trim();
|
.trim();
|
||||||
|
|
||||||
// 2. Try to parse as JSON
|
// 2. Try to parse as JSON
|
||||||
let parsed: unknown;
|
let parsed: any;
|
||||||
try {
|
try {
|
||||||
parsed = JSON.parse(cleaned);
|
parsed = JSON.parse(cleaned);
|
||||||
logStep('Direct JSON parse successful');
|
logStep('Direct JSON parse successful');
|
||||||
} catch {
|
} catch (e) {
|
||||||
logStep('Direct JSON parse failed, trying to extract JSON from string...');
|
logStep('Direct JSON parse failed, trying to extract JSON from string...');
|
||||||
// If JSON parse fails, try to find JSON-like content in the string
|
// If JSON parse fails, try to find JSON-like content in the string
|
||||||
const jsonMatch = cleaned.match(/\[[\s\S]*\]|\{[\s\S]*\}/);
|
const jsonMatch = cleaned.match(/\[[\s\S]*\]|\{[\s\S]*\}/);
|
||||||
@@ -93,7 +93,7 @@ function extractQueriesFromResponse(raw: string): string[] {
|
|||||||
try {
|
try {
|
||||||
parsed = JSON.parse(jsonMatch[0]);
|
parsed = JSON.parse(jsonMatch[0]);
|
||||||
logStep('Extracted JSON from string successfully');
|
logStep('Extracted JSON from string successfully');
|
||||||
} catch {
|
} catch (e2) {
|
||||||
logError('Could not extract JSON from response');
|
logError('Could not extract JSON from response');
|
||||||
throw new Error('Could not extract JSON from response');
|
throw new Error('Could not extract JSON from response');
|
||||||
}
|
}
|
||||||
@@ -105,7 +105,7 @@ function extractQueriesFromResponse(raw: string): string[] {
|
|||||||
|
|
||||||
// 3. Handle different formats
|
// 3. Handle different formats
|
||||||
if (Array.isArray(parsed)) {
|
if (Array.isArray(parsed)) {
|
||||||
const result = (parsed as unknown[]).filter(item => typeof item === 'string' && (item as string).trim().length > 0) as string[];
|
const result = parsed.filter(item => typeof item === 'string' && item.trim().length > 0);
|
||||||
logSuccess(`Parsed as plain array: ${result.length} queries`);
|
logSuccess(`Parsed as plain array: ${result.length} queries`);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -113,19 +113,17 @@ function extractQueriesFromResponse(raw: string): string[] {
|
|||||||
// 4. Check common object keys used by different models
|
// 4. Check common object keys used by different models
|
||||||
const commonKeys = ['queries', 'query', 'plan', 'searches', 'search_queries', 'questions'];
|
const commonKeys = ['queries', 'query', 'plan', 'searches', 'search_queries', 'questions'];
|
||||||
for (const key of commonKeys) {
|
for (const key of commonKeys) {
|
||||||
const obj = parsed as Record<string, unknown>;
|
if (parsed[key] && Array.isArray(parsed[key])) {
|
||||||
const val = obj[key];
|
const result = parsed[key].filter((item: any) => typeof item === 'string' && item.trim().length > 0);
|
||||||
if (Array.isArray(val)) {
|
|
||||||
const result = (val as unknown[]).filter((item: unknown) => typeof item === 'string' && (item as string).trim().length > 0) as string[];
|
|
||||||
logSuccess(`Found queries under key "${key}": ${result.length} queries`);
|
logSuccess(`Found queries under key "${key}": ${result.length} queries`);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Fallback: find first array value in the object
|
// 5. Fallback: find first array value in the object
|
||||||
for (const val of Object.values(parsed as Record<string, unknown>)) {
|
for (const val of Object.values(parsed)) {
|
||||||
if (Array.isArray(val) && val.length > 0 && typeof (val as unknown[])[0] === 'string') {
|
if (Array.isArray(val) && val.length > 0 && typeof val[0] === 'string') {
|
||||||
const result = (val as unknown[]).filter((item: unknown) => typeof item === 'string' && (item as string).trim().length > 0) as string[];
|
const result = (val as string[]).filter((item: any) => typeof item === 'string' && item.trim().length > 0);
|
||||||
logSuccess(`Found queries in object value: ${result.length} queries`);
|
logSuccess(`Found queries in object value: ${result.length} queries`);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -153,19 +151,29 @@ export function useDeepResearch() {
|
|||||||
logData('Prompt length', `${prompt.length} chars`);
|
logData('Prompt length', `${prompt.length} chars`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { invoke } = await import('@tauri-apps/api/core');
|
const response = await fetch('http://localhost:11434/api/generate', {
|
||||||
const response = await invoke<string>('generate_completion', {
|
method: 'POST',
|
||||||
model,
|
headers: { 'Content-Type': 'application/json' },
|
||||||
prompt,
|
body: JSON.stringify({
|
||||||
options: {
|
model,
|
||||||
temperature: 0.2,
|
prompt,
|
||||||
num_predict: 2048,
|
stream: false,
|
||||||
format: json ? 'json' : undefined,
|
format: json ? 'json' : undefined,
|
||||||
},
|
options: {
|
||||||
|
temperature: 0.2,
|
||||||
|
num_predict: 2048,
|
||||||
|
},
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
logError(`LLM API returned status ${response.status}`);
|
||||||
|
throw new Error('Failed to call LLM');
|
||||||
|
}
|
||||||
|
|
||||||
logSuccess(`LLM response received (${response?.length || 0} chars)`);
|
const data = await response.json();
|
||||||
return response;
|
logSuccess(`LLM response received (${data.response?.length || 0} chars)`);
|
||||||
|
return data.response;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errorMsg = e instanceof Error ? e.message : String(e);
|
const errorMsg = e instanceof Error ? e.message : String(e);
|
||||||
logError('LLM Call Error', errorMsg);
|
logError('LLM Call Error', errorMsg);
|
||||||
@@ -187,7 +195,7 @@ export function useDeepResearch() {
|
|||||||
setState(s => ({ ...s, context }));
|
setState(s => ({ ...s, context }));
|
||||||
return context;
|
return context;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.warn(`Contextual analysis failed, continuing without context: ${error instanceof Error ? error.message : String(error)}`);
|
log.warn('Contextual analysis failed, continuing without context:', error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
@@ -211,7 +219,7 @@ export function useDeepResearch() {
|
|||||||
setState(s => ({ ...s, enrichedQueries: enriched }));
|
setState(s => ({ ...s, enrichedQueries: enriched }));
|
||||||
return enriched;
|
return enriched;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.warn(`Query enrichment failed, continuing without enrichment: ${error instanceof Error ? error.message : String(error)}`);
|
log.warn('Query enrichment failed, continuing without enrichment:', error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
@@ -247,41 +255,40 @@ export function useDeepResearch() {
|
|||||||
plan = [query];
|
plan = [query];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Safety Check
|
||||||
logStep('--- Safety Check ---');
|
logStep('--- Safety Check ---');
|
||||||
const keywords = query.toLowerCase().split(/\s+/).filter(w => w.length > 3);
|
const keywords = query.toLowerCase().split(/\s+/).filter(w => w.length > 3);
|
||||||
logData('Keywords from query', keywords);
|
logData('Keywords from query', keywords);
|
||||||
const isSmallModel = /(?:270m|0\.5b|1b|1\.7b|2b|mini|small|abliterated|uncensored|qwen3|llama2)/i.test(model);
|
|
||||||
if (isSmallModel) {
|
const isRelevant = plan.some(q =>
|
||||||
logStep('Safety Check bypassed for small/experimental model');
|
keywords.some(k => q.toLowerCase().includes(k))
|
||||||
|
);
|
||||||
|
logData('Plan is relevant', isRelevant);
|
||||||
|
|
||||||
|
if (!isRelevant && keywords.length > 0) {
|
||||||
|
logError('Safety Check Failed: Plan is irrelevant to query');
|
||||||
|
logData('Generated plan', plan);
|
||||||
|
logStep('Falling back to original query');
|
||||||
|
addLog({
|
||||||
|
stage: 'decomposition',
|
||||||
|
timestamp: Date.now(),
|
||||||
|
input: prompt,
|
||||||
|
rawOutput: response,
|
||||||
|
parsedOutput: plan,
|
||||||
|
error: 'Safety Check Failed: Plan irrelevant to query'
|
||||||
|
});
|
||||||
|
plan = [query];
|
||||||
} else {
|
} else {
|
||||||
const isRelevant = plan.some(q =>
|
logSuccess(`Decomposition complete: ${plan.length} search queries generated`);
|
||||||
keywords.some(k => q.toLowerCase().includes(k))
|
addLog({
|
||||||
);
|
stage: 'decomposition',
|
||||||
logData('Plan is relevant', isRelevant);
|
timestamp: Date.now(),
|
||||||
if (!isRelevant && keywords.length > 0) {
|
input: prompt,
|
||||||
logError('Safety Check Failed: Plan is irrelevant to query');
|
rawOutput: response,
|
||||||
logData('Generated plan', plan);
|
parsedOutput: plan,
|
||||||
logStep('Falling back to original query');
|
error: parseError
|
||||||
addLog({
|
});
|
||||||
stage: 'decomposition',
|
|
||||||
timestamp: Date.now(),
|
|
||||||
input: prompt,
|
|
||||||
rawOutput: response,
|
|
||||||
parsedOutput: plan,
|
|
||||||
error: 'Safety Check Failed: Plan irrelevant to query'
|
|
||||||
});
|
|
||||||
plan = [query];
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
addLog({
|
|
||||||
stage: 'decomposition',
|
|
||||||
timestamp: Date.now(),
|
|
||||||
input: prompt,
|
|
||||||
rawOutput: response,
|
|
||||||
parsedOutput: plan,
|
|
||||||
error: parseError
|
|
||||||
});
|
|
||||||
logSuccess(`Decomposition complete: ${plan.length} search queries generated`);
|
|
||||||
|
|
||||||
setState(s => ({ ...s, plan }));
|
setState(s => ({ ...s, plan }));
|
||||||
return plan;
|
return plan;
|
||||||
@@ -296,63 +303,31 @@ export function useDeepResearch() {
|
|||||||
|
|
||||||
// --- ADD TO KNOWLEDGE BASE ---
|
// --- ADD TO KNOWLEDGE BASE ---
|
||||||
const addToKnowledgeBase = useCallback((query: string, sources: ScrapedContent[]) => {
|
const addToKnowledgeBase = useCallback((query: string, sources: ScrapedContent[]) => {
|
||||||
logSection('ADDING TO KNOWLEDGE BASE');
|
logStep(`--- Adding to Knowledge Base ---`);
|
||||||
logData('Query', query);
|
logData('Query', query);
|
||||||
logData('Sources count', sources.length);
|
logData('Sources count', sources.length);
|
||||||
logData('Timestamp', new Date().toISOString());
|
|
||||||
|
|
||||||
const entries: ResearchEntry[] = sources.map((src, idx) => ({
|
const entries: ResearchEntry[] = sources.map((src, idx) => ({
|
||||||
id: `${query.substring(0, 10)}-${idx}-${Date.now()}`,
|
id: `${query.substring(0, 10)}-${idx}-${Date.now()}`,
|
||||||
query,
|
query,
|
||||||
sourceUrl: src.url,
|
sourceUrl: src.url,
|
||||||
title: src.title,
|
title: src.title,
|
||||||
content: src.markdown || src.content || '',
|
content: src.markdown,
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Log detalhado de cada fonte
|
|
||||||
sources.forEach((src, idx) => {
|
sources.forEach((src, idx) => {
|
||||||
logStep(`\n--- Source ${idx + 1}/${sources.length} ---`);
|
logStep(` → Source ${idx + 1}: ${src.title} (${src.url})`);
|
||||||
logData('Title', src.title);
|
const contentLength = src.markdown?.length || 0;
|
||||||
logData('URL', src.url);
|
logData(` Content length`, `${contentLength} chars`);
|
||||||
|
|
||||||
const contentLength = src.markdown?.length || src.content?.length || 0;
|
|
||||||
const snippetLength = src.snippet?.length || 0;
|
|
||||||
|
|
||||||
logData('Content length (markdown)', `${contentLength} chars`);
|
|
||||||
logData('Snippet length', `${snippetLength} chars`);
|
|
||||||
logData('Cached', src.cached ? 'Yes' : 'No');
|
|
||||||
|
|
||||||
if (src.markdown && contentLength > 0) {
|
if (src.markdown && contentLength > 0) {
|
||||||
// Log preview mais detalhado
|
const preview = src.markdown.substring(0, 300);
|
||||||
const preview = src.markdown.substring(0, 500);
|
logData(` Preview`, preview + (contentLength > 300 ? '...' : ''));
|
||||||
logData('Content preview', preview + (contentLength > 500 ? '...' : ''));
|
|
||||||
|
|
||||||
// Estatísticas do conteúdo
|
|
||||||
const wordCount = src.markdown.split(/\s+/).length;
|
|
||||||
const paragraphCount = src.markdown.split(/\n\n/).length;
|
|
||||||
logData('Word count', wordCount);
|
|
||||||
logData('Paragraph count', paragraphCount);
|
|
||||||
} else if (src.content && src.content.length > 0) {
|
|
||||||
const preview = src.content.substring(0, 500);
|
|
||||||
logData('Content preview (raw)', preview + (src.content.length > 500 ? '...' : ''));
|
|
||||||
} else {
|
} else {
|
||||||
logError('No content extracted from this source');
|
logStep(` ⚠️ No content extracted`);
|
||||||
}
|
|
||||||
|
|
||||||
// Log snippet se disponível
|
|
||||||
if (src.snippet) {
|
|
||||||
logData('Snippet', src.snippet.substring(0, 200) + (snippetLength > 200 ? '...' : ''));
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Estatísticas agregadas
|
|
||||||
const totalContentLength = entries.reduce((sum, e) => sum + e.content.length, 0);
|
|
||||||
const avgContentLength = entries.length > 0 ? totalContentLength / entries.length : 0;
|
|
||||||
logStep('\n--- Aggregated Statistics ---');
|
|
||||||
logData('Total entries', entries.length);
|
|
||||||
logData('Total content length', `${totalContentLength} chars`);
|
|
||||||
logData('Average content length', `${Math.round(avgContentLength)} chars`);
|
|
||||||
|
|
||||||
setState(s => ({
|
setState(s => ({
|
||||||
...s,
|
...s,
|
||||||
|
|||||||
Loaded 100 of 184 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user