From 55749c07e3186c49253c7fceedc575ebf8ae7a43 Mon Sep 17 00:00:00 2001 From: Evandro Fonseca Junior Date: Fri, 28 Nov 2025 00:38:58 -0300 Subject: [PATCH] chore: refine Next.js configuration and improve error handling - Simplified the Next.js webpack configuration to apply raw-loader for markdown files universally. - Updated build script in package.json to ensure webpack is used during the build process. - Enhanced error logging across various hooks to provide clearer messages when exceptions occur, improving debugging capabilities. --- data/changelog.json | 5 +++++ hooks/use-app-updater.ts | 15 +++++---------- hooks/use-chat-storage.ts | 4 ++-- hooks/use-deep-research.ts | 4 ++-- hooks/use-ollama-download.ts | 8 ++++++++ lib/context-unifier.ts | 5 +++-- lib/contextual-analyzer.ts | 4 ++-- lib/knowledge-base-processor.ts | 4 ++-- lib/query-enricher.ts | 4 ++-- lib/web-search-fallback.ts | 4 ++-- next.config.ts | 22 ++++++++++------------ package.json | 2 +- 12 files changed, 44 insertions(+), 37 deletions(-) create mode 100644 data/changelog.json diff --git a/data/changelog.json b/data/changelog.json new file mode 100644 index 0000000..459b561 --- /dev/null +++ b/data/changelog.json @@ -0,0 +1,5 @@ +{ + "version": "0.1.0", + "generatedAt": "2025-11-28T03:22:48.992Z", + "releases": [] +} \ No newline at end of file diff --git a/hooks/use-app-updater.ts b/hooks/use-app-updater.ts index 96838a6..b124d1d 100644 --- a/hooks/use-app-updater.ts +++ b/hooks/use-app-updater.ts @@ -87,23 +87,18 @@ export function useAppUpdater(): AppUpdaterState { const update = await checkForUpdate(); 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 + // O progresso pode ser monitorado via eventos do Tauri se necessário await update.downloadAndInstall(); - - unlisten(); - - // Reiniciar aplicativo após instalação - await update.installAndRestart(); + + // Após downloadAndInstall(), o app será reiniciado automaticamente + // Não é necessário chamar installAndRestart() que não existe na API } } catch (err) { console.error('Failed to install update:', err); setError(err instanceof Error ? err.message : 'Erro ao instalar atualização'); setIsDownloading(false); + setDownloadProgress(0); } }, [updateAvailable]); diff --git a/hooks/use-chat-storage.ts b/hooks/use-chat-storage.ts index 649be3b..cce2e8f 100644 --- a/hooks/use-chat-storage.ts +++ b/hooks/use-chat-storage.ts @@ -392,7 +392,7 @@ export function useChatStorage() { const keywords = Array.isArray(msg.metadata.keywords) ? msg.metadata.keywords : []; - memoryContext.push(...keywords.filter(k => typeof k === 'string')); + memoryContext.push(...keywords.filter((k: unknown) => typeof k === 'string')); } }); const uniqueMemoryContext = Array.from(new Set(memoryContext)); @@ -457,7 +457,7 @@ export function useChatStorage() { const keywords = Array.isArray(msg.metadata.keywords) ? msg.metadata.keywords : []; - memoryContext.push(...keywords.filter(k => typeof k === 'string')); + memoryContext.push(...keywords.filter((k: unknown) => typeof k === 'string')); } }); // Deduplicate diff --git a/hooks/use-deep-research.ts b/hooks/use-deep-research.ts index bb45b91..2d5efb6 100644 --- a/hooks/use-deep-research.ts +++ b/hooks/use-deep-research.ts @@ -195,7 +195,7 @@ export function useDeepResearch() { setState(s => ({ ...s, context })); return context; } catch (error) { - log.warn('Contextual analysis failed, continuing without context:', error); + log.warn(`Contextual analysis failed, continuing without context: ${error instanceof Error ? error.message : String(error)}`); return null; } }, []); @@ -219,7 +219,7 @@ export function useDeepResearch() { setState(s => ({ ...s, enrichedQueries: enriched })); return enriched; } catch (error) { - log.warn('Query enrichment failed, continuing without enrichment:', error); + log.warn(`Query enrichment failed, continuing without enrichment: ${error instanceof Error ? error.message : String(error)}`); return null; } }, []); diff --git a/hooks/use-ollama-download.ts b/hooks/use-ollama-download.ts index f19bac4..84f3176 100644 --- a/hooks/use-ollama-download.ts +++ b/hooks/use-ollama-download.ts @@ -53,6 +53,8 @@ export function useOllamaDownload() { downloadError: null, filePath: null, isInstalled: false, + isChecking: false, + checkStatus: '', }); try { @@ -66,6 +68,8 @@ export function useOllamaDownload() { downloadError: null, filePath: existingPath, isInstalled: false, + isChecking: false, + checkStatus: '', }); return; } @@ -79,6 +83,8 @@ export function useOllamaDownload() { downloadError: null, filePath, isInstalled: false, + isChecking: false, + checkStatus: '', }); } catch (error) { setState({ @@ -88,6 +94,8 @@ export function useOllamaDownload() { downloadError: error instanceof Error ? error.message : 'Erro desconhecido durante download', filePath: null, isInstalled: false, + isChecking: false, + checkStatus: '', }); } }; diff --git a/lib/context-unifier.ts b/lib/context-unifier.ts index 7b09ed4..8f8d77b 100644 --- a/lib/context-unifier.ts +++ b/lib/context-unifier.ts @@ -156,7 +156,7 @@ export async function extractKeyFacts( entities: f.entities || [], })); } catch (error) { - chatLog.warn(`[ContextUnifier] Erro ao extrair fatos de ${entry.title}:`, error); + chatLog.warn(`[ContextUnifier] Erro ao extrair fatos de ${entry.title}: ${error instanceof Error ? error.message : String(error)}`); // Fallback: criar fato básico do título return [{ fact: entry.title, @@ -273,7 +273,7 @@ export async function unifyContext( // Criar texto unificado const unifiedSections: string[] = []; - const sourceMap = new Map(); + const sourceMap = new Map(); // Agrupar por fonte for (const entry of entries) { @@ -281,6 +281,7 @@ export async function unifyContext( if (entryFacts.length > 0) { sourceMap.set(entry.id, { + id: entry.id, title: entry.title, url: entry.sourceUrl, factsCount: entryFacts.length, diff --git a/lib/contextual-analyzer.ts b/lib/contextual-analyzer.ts index fcb3b13..895e1fb 100644 --- a/lib/contextual-analyzer.ts +++ b/lib/contextual-analyzer.ts @@ -206,11 +206,11 @@ export async function analyzeQueryContext( complexity: analysis.complexity || 'moderate', }; - chatLog.success(`[ContextualAnalysis] Contexto extraído: ${context.intent}, ${context.entities.length} entidades, ${context.topics.length} tópicos`); + chatLog.info(`[ContextualAnalysis] Contexto extraído: ${context.intent}, ${context.entities.length} entidades, ${context.topics.length} tópicos`); return context; } catch (error) { - chatLog.error(`[ContextualAnalysis] Erro ao analisar contexto:`, error); + chatLog.error(`[ContextualAnalysis] Erro ao analisar contexto: ${error instanceof Error ? error.message : String(error)}`); // Fallback: análise básica usando heurísticas return createFallbackContext(query); diff --git a/lib/knowledge-base-processor.ts b/lib/knowledge-base-processor.ts index 6959e27..822fcbd 100644 --- a/lib/knowledge-base-processor.ts +++ b/lib/knowledge-base-processor.ts @@ -24,12 +24,13 @@ export interface CondensationOptions { context?: QueryContext; // Contexto analisado para ranqueamento semântico } -const DEFAULT_OPTIONS: Required = { +const DEFAULT_OPTIONS: Omit, 'context'> & { context?: QueryContext } = { maxTokens: 12000, minRelevanceScore: 0.1, autoSummarize: true, summarizeThreshold: 5000, fallbackToSummarization: true, + context: undefined, }; /** @@ -108,7 +109,6 @@ export function condenseKnowledgeBase( entries.forEach((entry, entryIndex) => { const processed = processContent(entry.content, query, { summarizeThreshold: opts.summarizeThreshold, - autoSummarize: opts.autoSummarize, }); // Atribuir sourceIndex e metadados aos chunks diff --git a/lib/query-enricher.ts b/lib/query-enricher.ts index 1dcc3b9..a2d09f8 100644 --- a/lib/query-enricher.ts +++ b/lib/query-enricher.ts @@ -176,7 +176,7 @@ export async function enrichQueries( result.expanded.length + result.contextual.length; - chatLog.success( + chatLog.info( `[QueryEnricher] ${totalQueries} queries geradas: ` + `${result.literal.length} literal, ${result.semantic.length} semântica, ` + `${result.related.length} relacionadas, ${result.expanded.length} expandidas, ` + @@ -185,7 +185,7 @@ export async function enrichQueries( return result; } catch (error) { - chatLog.error(`[QueryEnricher] Erro ao enriquecer queries:`, error); + chatLog.error(`[QueryEnricher] Erro ao enriquecer queries: ${error instanceof Error ? error.message : String(error)}`); // Fallback: usar apenas query original return createFallbackEnrichment(originalQuery, context); diff --git a/lib/web-search-fallback.ts b/lib/web-search-fallback.ts index 71d07ae..4dd7cda 100644 --- a/lib/web-search-fallback.ts +++ b/lib/web-search-fallback.ts @@ -132,7 +132,7 @@ Query expandida:`; chatLog.info(`Query expanded: "${originalQuery}" → "${expanded}"`); return expanded; } catch (error) { - chatLog.warn('Error expanding query, using original:', error); + chatLog.warn(`Error expanding query, using original: ${error instanceof Error ? error.message : String(error)}`); return originalQuery; } } @@ -352,7 +352,7 @@ export async function executeProgressiveSearch( const results = await searchFn(finalQuery, finalConfig.maxResultsPerRound, round); return { query: finalQuery, results }; } catch (error) { - chatLog.warn(`[Round ${round}] Query "${finalQuery}" failed:`, error); + chatLog.warn(`[Round ${round}] Query "${finalQuery}" failed: ${error instanceof Error ? error.message : String(error)}`); return { query: finalQuery, results: [] }; } }); diff --git a/next.config.ts b/next.config.ts index 56b5743..ce85484 100644 --- a/next.config.ts +++ b/next.config.ts @@ -5,19 +5,17 @@ const nextConfig: NextConfig = { images: { unoptimized: true, }, - webpack: (config, { isServer }) => { - // Adiciona suporte para raw-loader apenas no cliente - if (!isServer) { - config.module.rules.push({ - test: /\.md$/, - use: { - loader: 'raw-loader', - options: { - esModule: false, - }, + webpack: (config) => { + // Adiciona suporte para raw-loader para arquivos .md + config.module.rules.push({ + test: /\.md$/, + use: { + loader: 'raw-loader', + options: { + esModule: false, }, - }); - } + }, + }); return config; }, // Configuração Turbopack: objeto vazio silencia o erro diff --git a/package.json b/package.json index 2f30dc0..62dd276 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "private": true, "scripts": { "dev": "next dev --webpack", - "build": "next build", + "build": "next build --webpack", "start": "next start", "lint": "eslint", "generate-changelog": "node scripts/generate-changelog.js",