feat: enhance chat and settings functionality with debugging and new features
- Integrated useRouter for navigation in chat and settings pages, improving user experience. - Added detailed debug logging for web context generation and chat payloads to assist in troubleshooting. - Updated settings page to include a hardware dashboard and enhanced sources configuration management. - Implemented auto-start feature for the application and improved task management with new scheduled task options. - Refined user interface components for better accessibility and usability across chat and settings pages.
This commit is contained in:
1 parent
8834ef2b4f
commit
a44d1bba44
18 files changed
+1692
-223
No files matched your search
+38
-2
@@ -25,6 +25,7 @@ import { useSettingsStore } from "@/store/settings-store";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { ImperativePanelHandle } from "react-resizable-panels";
|
||||
import { sanitizeWebSources } from "@/lib/sanitize-web-content";
|
||||
// @ts-ignore
|
||||
@@ -32,6 +33,7 @@ import defaultFormatPrompt from "@/data/prompts/default-format.md";
|
||||
|
||||
|
||||
export default function ChatPage() {
|
||||
const router = useRouter();
|
||||
const { messages, setMessages, sendMessage, isLoading, stop, clearChat } = useChat();
|
||||
const { models } = useLocalModels();
|
||||
const { theme, setTheme } = useTheme();
|
||||
@@ -164,6 +166,25 @@ export default function ChatPage() {
|
||||
removeHiddenText: true,
|
||||
});
|
||||
|
||||
// [DEBUG INJECTION START]
|
||||
console.group('🔍 Debug: Web Context Generation');
|
||||
console.log('1. Raw Sources Count:', scrapedSources.length);
|
||||
console.log('2. Web Context Length:', webContext.length);
|
||||
console.log('3. Is Context Empty?', webContext === '');
|
||||
if (webContext.length > 0) {
|
||||
console.log('4. Context Preview:', webContext.substring(0, 200) + '...');
|
||||
} else {
|
||||
console.warn('⚠️ ALERT: Web Context is EMPTY even with sources!');
|
||||
console.log('4. Sources Details:', scrapedSources.map(s => ({
|
||||
url: s.url,
|
||||
title: s.title,
|
||||
hasMarkdown: !!s.markdown,
|
||||
markdownLength: s.markdown?.length || 0
|
||||
})));
|
||||
}
|
||||
console.groupEnd();
|
||||
// [DEBUG INJECTION END]
|
||||
|
||||
// Log para debug: verificar tamanho do contexto gerado
|
||||
const contextLength = webContext.length;
|
||||
console.debug(`Contexto web gerado (sanitizado): ${contextLength} caracteres de ${scrapedSources.length} fontes`);
|
||||
@@ -221,7 +242,7 @@ export default function ChatPage() {
|
||||
3. **Uso Estrito de Fontes:**
|
||||
- Use SOMENTE as informações do bloco [CONTEXTO WEB RECUPERADO] abaixo para fatos recentes. Não alucine.
|
||||
- Se o contexto trouxer múltiplas notícias diferentes, agrupe-as por temas usando títulos Markdown (ex: "## Economia", "## Política").
|
||||
- Cite as fontes usando [1], [2], [3] ao final das frases quando usar informações do contexto web.
|
||||
- NÃO cite fontes no meio do texto. Use as informações do contexto web naturalmente, sem mencionar [1], [2], [3] ou outras referências numéricas.
|
||||
- Se o contexto não for suficiente para responder completamente, diga isso claramente.
|
||||
|
||||
4. **Formato Jornalístico:**
|
||||
@@ -252,6 +273,16 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
||||
`;
|
||||
}
|
||||
|
||||
// [DEBUG INJECTION START]
|
||||
console.log('5. Enhanced System Prompt Length:', enhancedSystemPrompt.length);
|
||||
console.log('6. Contains "CONTEXTO WEB"?', enhancedSystemPrompt.includes('CONTEXTO WEB RECUPERADO'));
|
||||
if (enhancedSystemPrompt.includes('CONTEXTO WEB RECUPERADO')) {
|
||||
const contextStart = enhancedSystemPrompt.indexOf('CONTEXTO WEB RECUPERADO');
|
||||
console.log('7. Web Context Position:', contextStart);
|
||||
console.log('8. Web Context in Prompt Preview:', enhancedSystemPrompt.substring(contextStart, contextStart + 300) + '...');
|
||||
}
|
||||
// [DEBUG INJECTION END]
|
||||
|
||||
await sendMessage(content, selectedModel, enhancedSystemPrompt);
|
||||
|
||||
// Marcar como completo quando começar a streamar
|
||||
@@ -323,7 +354,12 @@ Ao responder sobre fatos atuais ou notícias, inicie mencionando explicitamente
|
||||
>
|
||||
{theme === "dark" ? <Sun className="w-5 h-5" /> : <Moon className="w-5 h-5" />}
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" className="rounded-lg text-muted-foreground hover:text-foreground">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="rounded-lg text-muted-foreground hover:text-foreground"
|
||||
onClick={() => router.push('/settings')}
|
||||
>
|
||||
<Settings className="w-5 h-5" />
|
||||
</Button>
|
||||
</ResizablePanel>
|
||||
|
||||
+546
-181
@@ -21,10 +21,12 @@ import {
|
||||
} from '@/components/ui/dialog';
|
||||
import { useSettingsStore } from '@/store/settings-store';
|
||||
import { DomainTagsInput } from '@/components/settings/domain-tags-input';
|
||||
import { HardwareDashboard } from '@/components/settings/HardwareDashboard';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window';
|
||||
import { CheckCircle2, XCircle, Loader2, Download, Trash2, Copy, ExternalLink, Plus, X, BookOpen, GraduationCap, Newspaper, Code, DollarSign } from 'lucide-react';
|
||||
import { CheckCircle2, XCircle, Loader2, Download, Trash2, Copy, ExternalLink, Plus, X, BookOpen, GraduationCap, Newspaper, Code, DollarSign, Edit, RotateCcw, Terminal, Power, ArrowLeft } from 'lucide-react';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { SourcesConfig, SourceCategory } from '@/lib/types';
|
||||
|
||||
interface Model {
|
||||
name: string;
|
||||
@@ -35,6 +37,7 @@ interface Model {
|
||||
export default function SettingsPage() {
|
||||
const settings = useSettingsStore();
|
||||
const { toast } = useToast();
|
||||
const router = useRouter();
|
||||
const [isCheckingConnection, setIsCheckingConnection] = useState(false);
|
||||
const [connectionStatus, setConnectionStatus] = useState<'idle' | 'success' | 'error'>('idle');
|
||||
const [availableModels, setAvailableModels] = useState<Model[]>([]);
|
||||
@@ -43,13 +46,37 @@ export default function SettingsPage() {
|
||||
const [showClearDialog, setShowClearDialog] = useState(false);
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
const [isClearing, setIsClearing] = useState(false);
|
||||
const [editingCategory, setEditingCategory] = useState<SourceCategory | null>(null);
|
||||
const [isSavingSources, setIsSavingSources] = useState(false);
|
||||
const [recentLogs, setRecentLogs] = useState<string[]>([]);
|
||||
const [isLoadingLogs, setIsLoadingLogs] = useState(false);
|
||||
|
||||
// Load models and storage path on mount
|
||||
// Load models, storage path, and sources config on mount
|
||||
useEffect(() => {
|
||||
loadModels();
|
||||
loadStoragePath();
|
||||
settings.fetchSources();
|
||||
}, [settings.ollamaUrl]);
|
||||
|
||||
// Load logs periodically
|
||||
useEffect(() => {
|
||||
const loadLogs = async () => {
|
||||
try {
|
||||
setIsLoadingLogs(true);
|
||||
const logs = await invoke<string[]>('get_recent_logs', { lines: 100 });
|
||||
setRecentLogs(logs);
|
||||
} catch (error) {
|
||||
console.error('Failed to load logs:', error);
|
||||
} finally {
|
||||
setIsLoadingLogs(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadLogs();
|
||||
const interval = setInterval(loadLogs, 5000); // Refresh every 5 seconds
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
const loadModels = async () => {
|
||||
setIsLoadingModels(true);
|
||||
try {
|
||||
@@ -135,6 +162,26 @@ export default function SettingsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportAllData = async () => {
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const zipPath = await invoke<string>('export_all_data');
|
||||
toast({
|
||||
title: 'Backup completo exportado',
|
||||
description: `Arquivo salvo em: ${zipPath}`,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to export all data:', error);
|
||||
toast({
|
||||
title: 'Erro na exportação',
|
||||
description: error instanceof Error ? error.message : 'Falha ao exportar',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearHistory = async () => {
|
||||
setIsClearing(true);
|
||||
try {
|
||||
@@ -170,23 +217,50 @@ export default function SettingsPage() {
|
||||
|
||||
return (
|
||||
<div className="container mx-auto py-8 max-w-4xl">
|
||||
<div className="mb-6">
|
||||
<h1 className="text-3xl font-bold">Configurações</h1>
|
||||
<p className="text-muted-foreground mt-2">
|
||||
Gerencie as preferências do OllaHub
|
||||
</p>
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">Configurações</h1>
|
||||
<p className="text-muted-foreground mt-2">
|
||||
Gerencie as preferências do OllaHub
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => router.push('/chat')}
|
||||
className="rounded-lg"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="ai" className="space-y-6">
|
||||
<TabsList className="grid w-full grid-cols-4">
|
||||
<TabsTrigger value="ai">AI & Models</TabsTrigger>
|
||||
<Tabs defaultValue="overview" className="space-y-6">
|
||||
<TabsList className="grid w-full grid-cols-6">
|
||||
<TabsTrigger value="overview">Visão Geral</TabsTrigger>
|
||||
<TabsTrigger value="general">General</TabsTrigger>
|
||||
<TabsTrigger value="web">Web Search</TabsTrigger>
|
||||
<TabsTrigger value="sources">Sources & Knowledge</TabsTrigger>
|
||||
<TabsTrigger value="storage">Data & Storage</TabsTrigger>
|
||||
<TabsTrigger value="tasks">Tasks & Scheduler</TabsTrigger>
|
||||
<TabsTrigger value="system">System & Logs</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* Tab: AI & Models */}
|
||||
<TabsContent value="ai" className="space-y-6">
|
||||
{/* Tab: Visão Geral (Hardware Dashboard) */}
|
||||
<TabsContent value="overview" className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Dashboard de Hardware</CardTitle>
|
||||
<CardDescription>
|
||||
Monitoramento em tempo real do sistema (atualizado a cada 1 segundo)
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<HardwareDashboard />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
{/* Tab: General */}
|
||||
<TabsContent value="general" className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Conexão Ollama</CardTitle>
|
||||
@@ -298,6 +372,30 @@ export default function SettingsPage() {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Inicialização Automática</CardTitle>
|
||||
<CardDescription>
|
||||
Iniciar o OllaHub automaticamente ao iniciar o sistema
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="autostart">Iniciar com o Sistema</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
O aplicativo será iniciado automaticamente ao fazer login
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="autostart"
|
||||
checked={settings.autoStart}
|
||||
onCheckedChange={settings.toggleAutoStart}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
{/* Tab: Web Search */}
|
||||
@@ -344,18 +442,24 @@ export default function SettingsPage() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="timeout">Timeout (segundos)</Label>
|
||||
<Input
|
||||
id="timeout"
|
||||
type="number"
|
||||
min={5}
|
||||
max={30}
|
||||
value={settings.webSearch.timeout}
|
||||
onChange={(e) => settings.setWebSearchTimeout(Number(e.target.value))}
|
||||
disabled={!settings.webSearch.enabled}
|
||||
/>
|
||||
<Label htmlFor="timeout">Scraper Timeout (segundos)</Label>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span>10s</span>
|
||||
<span className="font-medium">{settings.webSearch.timeout}s</span>
|
||||
<span>60s</span>
|
||||
</div>
|
||||
<Slider
|
||||
value={[settings.webSearch.timeout]}
|
||||
onValueChange={([value]) => settings.setWebSearchTimeout(value)}
|
||||
min={10}
|
||||
max={60}
|
||||
step={5}
|
||||
disabled={!settings.webSearch.enabled}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Tempo máximo para carregar cada página
|
||||
Tempo máximo para carregar cada página. Valores maiores podem resolver timeouts, mas aumentam o tempo total de busca.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -372,166 +476,269 @@ export default function SettingsPage() {
|
||||
<TabsContent value="sources" className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Fontes de Conhecimento</CardTitle>
|
||||
<CardDescription>
|
||||
Configure categorias de busca e sites customizados para pesquisa avançada
|
||||
</CardDescription>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>Fontes de Conhecimento</CardTitle>
|
||||
<CardDescription>
|
||||
Configure categorias de busca salvas no sources.json (compartilhável)
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await settings.fetchSources();
|
||||
toast({
|
||||
title: 'Configuração recarregada',
|
||||
description: 'Fontes atualizadas do arquivo sources.json',
|
||||
});
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Erro ao recarregar',
|
||||
description: error instanceof Error ? error.message : 'Falha ao recarregar',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<RotateCcw className="w-4 h-4 mr-2" />
|
||||
Recarregar
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Performance Settings */}
|
||||
<div className="space-y-4 pb-4 border-b">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="max-concurrent">Abas Simultâneas (Performance)</Label>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span>1</span>
|
||||
<span className="font-medium">{settings.webSearch.maxConcurrentTabs}</span>
|
||||
<span>10</span>
|
||||
</div>
|
||||
<Slider
|
||||
value={[settings.webSearch.maxConcurrentTabs]}
|
||||
onValueChange={([value]) => settings.setWebSearchMaxConcurrentTabs(value)}
|
||||
min={1}
|
||||
max={10}
|
||||
step={1}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Número máximo de páginas processadas simultaneamente (mais = mais rápido, mas mais uso de CPU)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="depth-research">Profundidade da Pesquisa</Label>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span>Rápido (5)</span>
|
||||
<span className="font-medium">{settings.webSearch.totalSourcesLimit}</span>
|
||||
<span>Profundo (40)</span>
|
||||
</div>
|
||||
<Slider
|
||||
value={[settings.webSearch.totalSourcesLimit]}
|
||||
onValueChange={([value]) => settings.setWebSearchTotalSourcesLimit(value)}
|
||||
min={5}
|
||||
max={40}
|
||||
step={5}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Número total de fontes a buscar. Mais fontes = mais tempo, mas resultados mais completos.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Categories */}
|
||||
<div className="space-y-4">
|
||||
<Label>Categorias de Busca</Label>
|
||||
<div className="grid gap-4">
|
||||
{settings.webSearch.categories.map((category) => {
|
||||
const iconMap: Record<string, React.ReactNode> = {
|
||||
academic: <GraduationCap className="w-4 h-4" />,
|
||||
news: <Newspaper className="w-4 h-4" />,
|
||||
tech: <Code className="w-4 h-4" />,
|
||||
finance: <DollarSign className="w-4 h-4" />,
|
||||
};
|
||||
|
||||
return (
|
||||
<Card key={category.id} className={category.enabled ? 'border-primary' : ''}>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-start gap-3 flex-1">
|
||||
<div className="mt-1">
|
||||
{iconMap[category.id] || <BookOpen className="w-4 h-4" />}
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Label htmlFor={`category-${category.id}`} className="font-semibold">
|
||||
{category.name}
|
||||
</Label>
|
||||
<Switch
|
||||
id={`category-${category.id}`}
|
||||
checked={category.enabled}
|
||||
onCheckedChange={() => settings.toggleCategory(category.id)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{category.baseSites.map((site) => (
|
||||
<Badge key={site} variant="secondary" className="text-xs">
|
||||
{site}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-2">
|
||||
{category.baseSites.length} sites curados
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Custom Sites */}
|
||||
<div className="space-y-4 pt-4 border-t">
|
||||
<Label>Sites Customizados</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Adicione seus próprios domínios favoritos para busca direcionada
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="custom-site-input"
|
||||
placeholder="exemplo.com"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
const input = e.currentTarget;
|
||||
const value = input.value.trim();
|
||||
if (value) {
|
||||
settings.addCustomSite(value);
|
||||
input.value = '';
|
||||
{settings.sourcesConfig ? (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>Categorias de Busca</Label>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
if (confirm('Restaurar categorias padrão? Isso substituirá a configuração atual.')) {
|
||||
try {
|
||||
const defaultConfig: SourcesConfig = {
|
||||
version: 1,
|
||||
last_updated: new Date().toISOString(),
|
||||
categories: [
|
||||
{
|
||||
id: 'academico',
|
||||
name: 'Acadêmico',
|
||||
base_sites: [
|
||||
'scholar.google.com',
|
||||
'arxiv.org',
|
||||
'pubmed.ncbi.nlm.nih.gov',
|
||||
'ieee.org',
|
||||
'acm.org',
|
||||
],
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
id: 'tech',
|
||||
name: 'Tech',
|
||||
base_sites: [
|
||||
'github.com',
|
||||
'stackoverflow.com',
|
||||
'dev.to',
|
||||
'medium.com',
|
||||
'reddit.com/r/programming',
|
||||
],
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
id: 'news',
|
||||
name: 'News',
|
||||
base_sites: [
|
||||
'news.ycombinator.com',
|
||||
'techcrunch.com',
|
||||
'theverge.com',
|
||||
'arstechnica.com',
|
||||
],
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
id: 'financeiro',
|
||||
name: 'Financeiro',
|
||||
base_sites: [
|
||||
'bloomberg.com',
|
||||
'reuters.com',
|
||||
'financialtimes.com',
|
||||
'wsj.com',
|
||||
],
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
await settings.saveSources(defaultConfig);
|
||||
toast({
|
||||
title: 'Padrões restaurados',
|
||||
description: 'Categorias padrão foram restauradas',
|
||||
});
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Erro ao restaurar',
|
||||
description: error instanceof Error ? error.message : 'Falha ao restaurar',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
const input = document.getElementById('custom-site-input') as HTMLInputElement;
|
||||
const value = input?.value.trim();
|
||||
if (value) {
|
||||
settings.addCustomSite(value);
|
||||
input.value = '';
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
{settings.webSearch.userCustomSites.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{settings.webSearch.userCustomSites.map((site) => (
|
||||
<Badge key={site} variant="outline" className="text-sm">
|
||||
{site}
|
||||
<button
|
||||
onClick={() => settings.removeCustomSite(site)}
|
||||
className="ml-2 hover:text-destructive"
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
}}
|
||||
>
|
||||
<RotateCcw className="w-4 h-4 mr-2" />
|
||||
Restaurar Padrões
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid gap-4">
|
||||
{settings.sourcesConfig.categories.map((category) => {
|
||||
const iconMap: Record<string, React.ReactNode> = {
|
||||
academico: <GraduationCap className="w-4 h-4" />,
|
||||
news: <Newspaper className="w-4 h-4" />,
|
||||
tech: <Code className="w-4 h-4" />,
|
||||
financeiro: <DollarSign className="w-4 h-4" />,
|
||||
};
|
||||
|
||||
return (
|
||||
<Card key={category.id} className={category.enabled ? 'border-primary' : ''}>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-start gap-3 flex-1">
|
||||
<div className="mt-1">
|
||||
{iconMap[category.id] || <BookOpen className="w-4 h-4" />}
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Label className="font-semibold">{category.name}</Label>
|
||||
<Switch
|
||||
checked={category.enabled}
|
||||
onCheckedChange={async () => {
|
||||
const updated = {
|
||||
...settings.sourcesConfig!,
|
||||
categories: settings.sourcesConfig!.categories.map((cat) =>
|
||||
cat.id === category.id ? { ...cat, enabled: !cat.enabled } : cat
|
||||
),
|
||||
};
|
||||
try {
|
||||
await settings.saveSources(updated);
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Erro ao salvar',
|
||||
description: error instanceof Error ? error.message : 'Falha ao salvar',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5 mb-2">
|
||||
{category.base_sites.map((site) => (
|
||||
<Badge key={site} variant="secondary" className="text-xs">
|
||||
{site}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{category.base_sites.length} sites
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setEditingCategory(category)}
|
||||
>
|
||||
<Edit className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-2" />
|
||||
<p>Carregando configuração de fontes...</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Edit Category Dialog */}
|
||||
<Dialog open={!!editingCategory} onOpenChange={(open) => !open && setEditingCategory(null)}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Editar Categoria: {editingCategory?.name}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Adicione ou remova sites desta categoria
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{editingCategory && (
|
||||
<EditCategoryDialog
|
||||
category={editingCategory}
|
||||
onSave={async (updatedCategory) => {
|
||||
if (!settings.sourcesConfig) return;
|
||||
const updated = {
|
||||
...settings.sourcesConfig,
|
||||
categories: settings.sourcesConfig.categories.map((cat) =>
|
||||
cat.id === updatedCategory.id ? updatedCategory : cat
|
||||
),
|
||||
};
|
||||
try {
|
||||
setIsSavingSources(true);
|
||||
await settings.saveSources(updated);
|
||||
setEditingCategory(null);
|
||||
toast({
|
||||
title: 'Categoria atualizada',
|
||||
description: 'Alterações salvas com sucesso',
|
||||
});
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Erro ao salvar',
|
||||
description: error instanceof Error ? error.message : 'Falha ao salvar',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsSavingSources(false);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</TabsContent>
|
||||
|
||||
{/* Tab: Tasks & Scheduler */}
|
||||
<TabsContent value="tasks" className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Tarefas Agendadas</CardTitle>
|
||||
<CardDescription>
|
||||
Gerencie tarefas automáticas que executam em intervalos regulares
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Visualize e gerencie tarefas agendadas no Task Manager
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => router.push('/tasks')}
|
||||
variant="outline"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4 mr-2" />
|
||||
Abrir Task Manager
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
{/* Tab: Data & Storage */}
|
||||
<TabsContent value="storage" className="space-y-6">
|
||||
{/* Tab: System & Logs */}
|
||||
<TabsContent value="system" className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Armazenamento</CardTitle>
|
||||
@@ -564,12 +771,12 @@ export default function SettingsPage() {
|
||||
|
||||
<div className="space-y-4 pt-4 border-t">
|
||||
<div className="space-y-2">
|
||||
<Label>Ações</Label>
|
||||
<div className="flex gap-2">
|
||||
<Label>Backup e Manutenção</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
onClick={handleExportChats}
|
||||
onClick={handleExportAllData}
|
||||
disabled={isExporting}
|
||||
variant="outline"
|
||||
variant="default"
|
||||
>
|
||||
{isExporting ? (
|
||||
<>
|
||||
@@ -579,10 +786,18 @@ export default function SettingsPage() {
|
||||
) : (
|
||||
<>
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
Exportar Todos os Chats
|
||||
Exportar Tudo (Backup Completo)
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleExportChats}
|
||||
disabled={isExporting}
|
||||
variant="outline"
|
||||
>
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
Exportar Apenas Chats
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => setShowClearDialog(true)}
|
||||
variant="destructive"
|
||||
@@ -591,10 +806,84 @@ export default function SettingsPage() {
|
||||
Apagar Histórico
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
O backup completo inclui: chats, tasks.json, sources.json e settings.json
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Logs do Sistema</CardTitle>
|
||||
<CardDescription>
|
||||
Visualize os logs recentes do aplicativo (atualizado a cada 5 segundos)
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="relative">
|
||||
<div className="bg-black text-green-400 font-mono text-xs p-4 rounded-lg h-[400px] overflow-y-auto">
|
||||
{isLoadingLogs ? (
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
Carregando logs...
|
||||
</div>
|
||||
) : recentLogs.length === 0 ? (
|
||||
<div className="text-muted-foreground">Nenhum log disponível</div>
|
||||
) : (
|
||||
recentLogs.map((line, idx) => (
|
||||
<div key={idx} className="mb-1">
|
||||
{line}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Processos do Sistema</CardTitle>
|
||||
<CardDescription>
|
||||
Gerencie processos do Chrome/Chromium que podem ficar "zumbis" após buscas web
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Chrome/Chromium Processes</Label>
|
||||
<p className="text-xs text-muted-foreground mb-4">
|
||||
Se você notar processos Chrome "zumbis" consumindo memória após buscas web, use este botão para forçar o encerramento de todos os processos relacionados.
|
||||
</p>
|
||||
<Button
|
||||
onClick={async () => {
|
||||
try {
|
||||
const killed = await invoke<number>('force_kill_browser');
|
||||
toast({
|
||||
title: killed > 0 ? 'Processos encerrados' : 'Nenhum processo encontrado',
|
||||
description: killed > 0
|
||||
? `${killed} processo(s) Chrome foram encerrados com sucesso.`
|
||||
: 'Não há processos Chrome rodando no momento.',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Erro ao encerrar processos:', error);
|
||||
toast({
|
||||
title: 'Erro ao encerrar processos',
|
||||
description: error instanceof Error ? error.message : 'Falha ao executar comando',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
}}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
>
|
||||
<XCircle className="w-4 h-4 mr-2" />
|
||||
Encerrar Processos Chrome
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
@@ -636,3 +925,79 @@ export default function SettingsPage() {
|
||||
);
|
||||
}
|
||||
|
||||
// Edit Category Dialog Component
|
||||
function EditCategoryDialog({
|
||||
category,
|
||||
onSave
|
||||
}: {
|
||||
category: SourceCategory;
|
||||
onSave: (category: SourceCategory) => void;
|
||||
}) {
|
||||
const [sites, setSites] = useState<string[]>(category.base_sites);
|
||||
const [newSite, setNewSite] = useState('');
|
||||
|
||||
const handleAddSite = () => {
|
||||
const normalized = newSite.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/$/, '');
|
||||
if (normalized && !sites.includes(normalized)) {
|
||||
setSites([...sites, normalized]);
|
||||
setNewSite('');
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveSite = (site: string) => {
|
||||
setSites(sites.filter((s) => s !== site));
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
onSave({
|
||||
...category,
|
||||
base_sites: sites,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Sites da Categoria</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="exemplo.com"
|
||||
value={newSite}
|
||||
onChange={(e) => setNewSite(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleAddSite();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button type="button" variant="outline" onClick={handleAddSite}>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2 mt-2">
|
||||
{sites.map((site) => (
|
||||
<Badge key={site} variant="secondary" className="text-sm">
|
||||
{site}
|
||||
<button
|
||||
onClick={() => handleRemoveSite(site)}
|
||||
className="ml-2 hover:text-destructive"
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onSave(category)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
Salvar Alterações
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+65
-12
@@ -6,7 +6,8 @@ import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Plus, Trash2, Clock, Play, Pause } from 'lucide-react';
|
||||
import { Plus, Trash2, Clock, Play, Pause, CheckCircle2, XCircle } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
@@ -157,13 +158,15 @@ export default function TasksPage() {
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
{task.label}
|
||||
{task.enabled ? (
|
||||
<span className="text-xs bg-green-500/10 text-green-500 px-2 py-1 rounded">
|
||||
<Badge variant="default" className="bg-green-500/10 text-green-500 border-green-500/20">
|
||||
<CheckCircle2 className="w-3 h-3 mr-1" />
|
||||
Ativa
|
||||
</span>
|
||||
</Badge>
|
||||
) : (
|
||||
<span className="text-xs bg-gray-500/10 text-gray-500 px-2 py-1 rounded">
|
||||
<Badge variant="secondary">
|
||||
<XCircle className="w-3 h-3 mr-1" />
|
||||
Pausada
|
||||
</span>
|
||||
</Badge>
|
||||
)}
|
||||
</CardTitle>
|
||||
<CardDescription className="mt-2">
|
||||
@@ -222,9 +225,10 @@ export default function TasksPage() {
|
||||
|
||||
function TaskFormDialog({ onSuccess }: { onSuccess: () => void }) {
|
||||
const [label, setLabel] = useState('');
|
||||
const [scheduleType, setScheduleType] = useState<'daily' | 'weekly' | 'custom'>('daily');
|
||||
const [scheduleType, setScheduleType] = useState<'daily' | 'weekly' | 'hourly' | 'custom'>('daily');
|
||||
const [hour, setHour] = useState('8');
|
||||
const [minute, setMinute] = useState('0');
|
||||
const [intervalHours, setIntervalHours] = useState('1');
|
||||
const [customCron, setCustomCron] = useState('');
|
||||
const [taskType, setTaskType] = useState<'search_and_summarize' | 'just_ping' | 'custom_prompt'>('search_and_summarize');
|
||||
const [query, setQuery] = useState('');
|
||||
@@ -238,8 +242,28 @@ function TaskFormDialog({ onSuccess }: { onSuccess: () => void }) {
|
||||
if (scheduleType === 'custom') {
|
||||
return customCron;
|
||||
}
|
||||
// Diário às hora:minuto
|
||||
return `${minute} ${hour} * * *`;
|
||||
if (scheduleType === 'hourly') {
|
||||
return `0 */${intervalHours} * * *`;
|
||||
}
|
||||
if (scheduleType === 'daily') {
|
||||
return `${minute} ${hour} * * *`;
|
||||
}
|
||||
// Weekly (every Monday at hour:minute)
|
||||
return `${minute} ${hour} * * 1`;
|
||||
};
|
||||
|
||||
const getCronPreview = (): string => {
|
||||
const cron = generateCron();
|
||||
if (scheduleType === 'hourly') {
|
||||
return `A cada ${intervalHours} hora(s)`;
|
||||
}
|
||||
if (scheduleType === 'daily') {
|
||||
return `Todo dia às ${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`;
|
||||
}
|
||||
if (scheduleType === 'weekly') {
|
||||
return `Toda segunda-feira às ${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`;
|
||||
}
|
||||
return cron;
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
@@ -306,10 +330,23 @@ function TaskFormDialog({ onSuccess }: { onSuccess: () => void }) {
|
||||
<SelectContent>
|
||||
<SelectItem value="daily">Diário</SelectItem>
|
||||
<SelectItem value="weekly">Semanal</SelectItem>
|
||||
<SelectItem value="custom">Cron Customizado</SelectItem>
|
||||
<SelectItem value="hourly">A cada X horas</SelectItem>
|
||||
<SelectItem value="custom">Cron Customizado (Avançado)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Cron Preview */}
|
||||
<div className="bg-muted p-3 rounded-lg">
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock className="w-4 h-4 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">Agendamento:</span>
|
||||
<span className="text-sm text-muted-foreground">{getCronPreview()}</span>
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-muted-foreground font-mono">
|
||||
Cron: {generateCron()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{scheduleType === 'custom' ? (
|
||||
<div>
|
||||
@@ -322,13 +359,29 @@ function TaskFormDialog({ onSuccess }: { onSuccess: () => void }) {
|
||||
required
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Formato: minuto hora dia mês dia-da-semana
|
||||
Formato: minuto hora dia mês dia-da-semana (ex: 0 8 * * * = todo dia às 8h)
|
||||
</p>
|
||||
</div>
|
||||
) : scheduleType === 'hourly' ? (
|
||||
<div>
|
||||
<Label htmlFor="interval-hours">Intervalo (horas)</Label>
|
||||
<Input
|
||||
id="interval-hours"
|
||||
type="number"
|
||||
min="1"
|
||||
max="24"
|
||||
value={intervalHours}
|
||||
onChange={(e) => setIntervalHours(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
A task será executada a cada {intervalHours} hora(s)
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="hour">Hora</Label>
|
||||
<Label htmlFor="hour">Hora (0-23)</Label>
|
||||
<Input
|
||||
id="hour"
|
||||
type="number"
|
||||
@@ -340,7 +393,7 @@ function TaskFormDialog({ onSuccess }: { onSuccess: () => void }) {
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="minute">Minuto</Label>
|
||||
<Label htmlFor="minute">Minuto (0-59)</Label>
|
||||
<Input
|
||||
id="minute"
|
||||
type="number"
|
||||
|
||||
Reference in new issue
Block a user