Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

feat: additional debug logging

Gabriel Stein87f44d1237dc
diff --git a/preload.js b/preload.js
index 7dfebf11d..4b5d47b57 100644
--- a/preload.js
+++ b/preload.js
@@ -119,6 +119,10 @@ contextBridge.exposeInMainWorld("electronAPI", {
llamaCppInstall: () => ipcRenderer.invoke("llama-cpp-install"),
llamaCppUninstall: () => ipcRenderer.invoke("llama-cpp-uninstall"),
+ // Debug logging for reasoning pipeline
+ logReasoning: (stage, details) =>
+ ipcRenderer.invoke("log-reasoning", stage, details),
+
// Remove all listeners for a channel
removeAllListeners: (channel) => {
ipcRenderer.removeAllListeners(channel);
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index f5c5b0c60..dfb71842c 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -181,13 +181,24 @@ export default function SettingsPage({
}
};
- const saveReasoningSettings = useCallback(() => {
+ const saveReasoningSettings = useCallback(async () => {
// Update reasoning settings
updateReasoningSettings({
useReasoningModel,
reasoningModel
});
+ // Save API keys to backend based on provider
+ if (localReasoningProvider === "openai" && openaiApiKey) {
+ await window.electronAPI?.saveOpenAIKey(openaiApiKey);
+ }
+ if (localReasoningProvider === "anthropic" && anthropicApiKey) {
+ await window.electronAPI?.saveAnthropicKey(anthropicApiKey);
+ }
+ if (localReasoningProvider === "gemini" && geminiApiKey) {
+ await window.electronAPI?.saveGeminiKey(geminiApiKey);
+ }
+
updateApiKeys({
...(localReasoningProvider === "openai" &&
openaiApiKey.trim() && { openaiApiKey }),
@@ -223,15 +234,33 @@ export default function SettingsPage({
const saveApiKey = useCallback(async () => {
try {
- await window.electronAPI?.saveOpenAIKey(openaiApiKey);
- updateApiKeys({ openaiApiKey });
+ // Save all API keys to backend
+ if (openaiApiKey) {
+ await window.electronAPI?.saveOpenAIKey(openaiApiKey);
+ }
+ if (anthropicApiKey) {
+ await window.electronAPI?.saveAnthropicKey(anthropicApiKey);
+ }
+ if (geminiApiKey) {
+ await window.electronAPI?.saveGeminiKey(geminiApiKey);
+ }
+
+ updateApiKeys({ openaiApiKey, anthropicApiKey, geminiApiKey });
updateTranscriptionSettings({ allowLocalFallback, fallbackWhisperModel });
try {
- await window.electronAPI?.createProductionEnvFile(openaiApiKey);
+ if (openaiApiKey) {
+ await window.electronAPI?.createProductionEnvFile(openaiApiKey);
+ }
+
+ const savedKeys: string[] = [];
+ if (openaiApiKey) savedKeys.push("OpenAI");
+ if (anthropicApiKey) savedKeys.push("Anthropic");
+ if (geminiApiKey) savedKeys.push("Gemini");
+
showAlertDialog({
- title: "API Key Saved",
- description: `OpenAI API key saved successfully! Your credentials have been securely recorded for transcription services.${
+ title: "API Keys Saved",
+ description: `${savedKeys.join(", ")} API key${savedKeys.length > 1 ? 's' : ''} saved successfully! Your credentials have been securely recorded.${
allowLocalFallback ? " Local Whisper fallback is enabled." : ""
}`,
});
@@ -254,6 +283,8 @@ export default function SettingsPage({
}
}, [
openaiApiKey,
+ anthropicApiKey,
+ geminiApiKey,
allowLocalFallback,
fallbackWhisperModel,
updateApiKeys,
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index fc9863683..cb91a1ae0 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -1,6 +1,22 @@
import TextCleanup from "../utils/textCleanup";
import ReasoningService from "../services/ReasoningService";
+// Debug logger for renderer process
+const debugLogger = {
+ logReasoning: async (stage, details) => {
+ if (window.electronAPI?.logReasoning) {
+ try {
+ await window.electronAPI.logReasoning(stage, details);
+ } catch (error) {
+ console.error('Failed to log reasoning:', error);
+ }
+ } else {
+ // Fallback to console if IPC not available
+ console.log(`πŸ€– [REASONING ${stage}]`, details);
+ }
+ }
+};
+
class AudioManager {
constructor() {
@@ -356,36 +372,154 @@ class AudioManager {
}
async processWithReasoningModel(text) {
- const model = localStorage.getItem("reasoningModel") || "gpt-4o-mini";
- return await ReasoningService.processText(text, model);
+ const model = (typeof window !== 'undefined' && window.localStorage)
+ ? (localStorage.getItem("reasoningModel") || "gpt-4o-mini")
+ : "gpt-4o-mini";
+ const agentName = (typeof window !== 'undefined' && window.localStorage)
+ ? (localStorage.getItem("agentName") || null)
+ : null;
+
+ debugLogger.logReasoning("CALLING_REASONING_SERVICE", {
+ model,
+ agentName,
+ textLength: text.length
+ });
+
+ const startTime = Date.now();
+
+ try {
+ const result = await ReasoningService.processText(text, model, agentName);
+
+ const processingTime = Date.now() - startTime;
+
+ debugLogger.logReasoning("REASONING_SERVICE_COMPLETE", {
+ model,
+ processingTimeMs: processingTime,
+ resultLength: result.length,
+ success: true
+ });
+
+ return result;
+ } catch (error) {
+ const processingTime = Date.now() - startTime;
+
+ debugLogger.logReasoning("REASONING_SERVICE_ERROR", {
+ model,
+ processingTimeMs: processingTime,
+ error: error.message,
+ stack: error.stack
+ });
+
+ throw error;
+ }
}
async isReasoningAvailable() {
- const useReasoning = localStorage.getItem("useReasoningModel") === "true";
- if (!useReasoning) return false;
-
- try {
- return await ReasoningService.isAvailable();
- } catch {
- return false;
+ // Check if we're in renderer process (has localStorage)
+ if (typeof window !== 'undefined' && window.localStorage) {
+ const storedValue = localStorage.getItem("useReasoningModel");
+
+ // Debug log the actual stored value
+ debugLogger.logReasoning("REASONING_STORAGE_CHECK", {
+ storedValue,
+ typeOfStoredValue: typeof storedValue,
+ isTrue: storedValue === "true",
+ isTruthy: !!storedValue && storedValue !== "false"
+ });
+
+ // Check for both "true" string and truthy values (but not "false")
+ const useReasoning = storedValue === "true" || (!!storedValue && storedValue !== "false");
+
+ if (!useReasoning) return false;
+
+ try {
+ const isAvailable = await ReasoningService.isAvailable();
+
+ debugLogger.logReasoning("REASONING_AVAILABILITY", {
+ isAvailable,
+ reasoningEnabled: useReasoning,
+ finalDecision: useReasoning && isAvailable
+ });
+
+ return isAvailable;
+ } catch (error) {
+ debugLogger.logReasoning("REASONING_AVAILABILITY_ERROR", {
+ error: error.message,
+ stack: error.stack
+ });
+ return false;
+ }
}
+ // If not in renderer, reasoning is not available
+ return false;
}
async processTranscription(text, source) {
+
+ // Log incoming transcription
+ debugLogger.logReasoning("TRANSCRIPTION_RECEIVED", {
+ source,
+ textLength: text.length,
+ textPreview: text.substring(0, 100) + (text.length > 100 ? "..." : ""),
+ timestamp: new Date().toISOString()
+ });
+
// Check if reasoning should handle cleanup
const useReasoning = await this.isReasoningAvailable();
+ // Safe localStorage access
+ const reasoningModel = (typeof window !== 'undefined' && window.localStorage)
+ ? (localStorage.getItem("reasoningModel") || "gpt-4o-mini")
+ : "gpt-4o-mini";
+ const reasoningProvider = (typeof window !== 'undefined' && window.localStorage)
+ ? (localStorage.getItem("reasoningProvider") || "auto")
+ : "auto";
+ const agentName = (typeof window !== 'undefined' && window.localStorage)
+ ? (localStorage.getItem("agentName") || null)
+ : null;
+
+ debugLogger.logReasoning("REASONING_CHECK", {
+ useReasoning,
+ reasoningModel,
+ reasoningProvider,
+ agentName
+ });
+
if (useReasoning) {
try {
// Minimal cleanup for reasoning models
const preparedText = AudioManager.cleanTranscriptionForAPI(text);
- return await this.processWithReasoningModel(preparedText);
+
+ debugLogger.logReasoning("SENDING_TO_REASONING", {
+ preparedTextLength: preparedText.length,
+ model: reasoningModel,
+ provider: reasoningProvider
+ });
+
+ const result = await this.processWithReasoningModel(preparedText);
+
+ debugLogger.logReasoning("REASONING_SUCCESS", {
+ resultLength: result.length,
+ resultPreview: result.substring(0, 100) + (result.length > 100 ? "..." : ""),
+ processingTime: new Date().toISOString()
+ });
+
+ return result;
} catch (error) {
+ debugLogger.logReasoning("REASONING_FAILED", {
+ error: error.message,
+ stack: error.stack,
+ fallbackToCleanup: true
+ });
console.error(`Reasoning failed (${source}):`, error.message);
// Fall back to standard cleanup
}
}
+ debugLogger.logReasoning("USING_STANDARD_CLEANUP", {
+ reason: useReasoning ? "Reasoning failed" : "Reasoning not enabled"
+ });
+
// Standard cleanup when reasoning is unavailable or fails
return AudioManager.cleanTranscription(text);
}
diff --git a/src/helpers/debugLogger.js b/src/helpers/debugLogger.js
index 716cd89f4..bcbfe7de0 100644
--- a/src/helpers/debugLogger.js
+++ b/src/helpers/debugLogger.js
@@ -58,6 +58,23 @@ class DebugLogger {
}
}
+ logReasoning(stage, details) {
+ if (!this.debugMode) return;
+
+ const reasoningInfo = {
+ stage,
+ timestamp: new Date().toISOString(),
+ ...details,
+ };
+
+ // Special formatting for reasoning logs to make them stand out
+ console.log(`\nπŸ€– === REASONING ${stage.toUpperCase()} ===`);
+ console.log(reasoningInfo);
+ console.log(`================================\n`);
+
+ this.log(`πŸ€– Reasoning Pipeline - ${stage}`, reasoningInfo);
+ }
+
error(...args) {
if (!this.debugMode) return;
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index fcf5b1c5e..14ea1b3dc 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -427,6 +427,12 @@ class IPCHandlers {
return { success: false, error: error.message };
}
});
+
+ // Debug logging handler for reasoning pipeline
+ ipcMain.handle("log-reasoning", async (event, stage, details) => {
+ debugLogger.logReasoning(stage, details);
+ return { success: true };
+ });
}
}
diff --git a/src/services/LocalReasoningService.ts b/src/services/LocalReasoningService.ts
index 522cffac5..be5a7568b 100644
--- a/src/services/LocalReasoningService.ts
+++ b/src/services/LocalReasoningService.ts
@@ -3,6 +3,13 @@ import { inferenceConfig } from "../config/InferenceConfig";
import { BaseReasoningService } from "./BaseReasoningService";
import { TOKEN_LIMITS } from "../config/constants";
+// Import debugLogger for comprehensive logging
+const debugLogger = {
+ logReasoning: (stage: string, details: any) => {
+ console.log(`[LOCAL_REASONING ${stage}]`, details);
+ }
+};
+
interface LocalReasoningConfig {
maxTokens?: number;
temperature?: number;
@@ -16,15 +23,28 @@ class LocalReasoningService extends BaseReasoningService {
agentName: string | null = null,
config: LocalReasoningConfig = {}
): Promise<string> {
+ debugLogger.logReasoning("LOCAL_MODEL_START", {
+ modelId,
+ agentName,
+ textLength: text.length,
+ configKeys: Object.keys(config)
+ });
+
if (this.isProcessing) {
throw new Error("Already processing a request");
}
this.isProcessing = true;
+ const startTime = Date.now();
try {
// Get prompt using the base class method
const reasoningPrompt = this.getReasoningPrompt(text, agentName, config);
+
+ debugLogger.logReasoning("LOCAL_MODEL_PROMPT_PREPARED", {
+ promptLength: reasoningPrompt.length,
+ hasAgentName: !!agentName
+ });
// Get optimized config for reasoning use case
const inferenceOptions = inferenceConfig.getConfigForUseCase('reasoning');
@@ -36,6 +56,13 @@ class LocalReasoningService extends BaseReasoningService {
TOKEN_LIMITS.MAX_TOKENS,
TOKEN_LIMITS.TOKEN_MULTIPLIER
);
+
+ debugLogger.logReasoning("LOCAL_MODEL_INFERENCE_CONFIG", {
+ modelId,
+ maxTokens,
+ temperature: config.temperature || inferenceOptions.temperature,
+ contextSize: config.contextSize || TOKEN_LIMITS.REASONING_CONTEXT_SIZE
+ });
// Run inference
const result = await modelManager.runInference(modelId, reasoningPrompt, {
@@ -44,9 +71,27 @@ class LocalReasoningService extends BaseReasoningService {
temperature: config.temperature || inferenceOptions.temperature,
contextSize: config.contextSize || TOKEN_LIMITS.REASONING_CONTEXT_SIZE,
});
+
+ const processingTime = Date.now() - startTime;
+
+ debugLogger.logReasoning("LOCAL_MODEL_SUCCESS", {
+ modelId,
+ processingTimeMs: processingTime,
+ resultLength: result.length,
+ resultPreview: result.substring(0, 100) + (result.length > 100 ? "..." : "")
+ });
return result;
} catch (error) {
+ const processingTime = Date.now() - startTime;
+
+ debugLogger.logReasoning("LOCAL_MODEL_ERROR", {
+ modelId,
+ processingTimeMs: processingTime,
+ error: (error as Error).message,
+ stack: (error as Error).stack
+ });
+
console.error("LocalReasoningService error:", error);
throw error;
} finally {
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index 07ad02a6e..0f32e8956 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -4,6 +4,15 @@ import { SecureCache } from "../utils/SecureCache";
import { withRetry, createApiRetryStrategy } from "../utils/retry";
import { API_ENDPOINTS, API_VERSIONS, TOKEN_LIMITS } from "../config/constants";
+// Import debugLogger for comprehensive logging
+const debugLogger = typeof window !== 'undefined' && window.electronAPI
+ ? { logReasoning: (stage: string, details: any) => {
+ window.electronAPI.logReasoning?.(stage, details).catch(() => {});
+ }}
+ : { logReasoning: (stage: string, details: any) => {
+ console.log(`[REASONING ${stage}]`, details);
+ }};
+
export const DEFAULT_PROMPTS = {
agent: `You are {{agentName}}, a helpful AI assistant. Process and improve the following text, removing any reference to your name from the output:\n\n{{text}}\n\nImproved text:`,
regular: `Process and improve the following text:\n\n{{text}}\n\nImproved text:`
@@ -21,6 +30,13 @@ class ReasoningService extends BaseReasoningService {
private async getApiKey(provider: 'openai' | 'anthropic' | 'gemini'): Promise<string> {
let apiKey = this.apiKeyCache.get(provider);
+
+ debugLogger.logReasoning(`${provider.toUpperCase()}_KEY_RETRIEVAL`, {
+ provider,
+ fromCache: !!apiKey,
+ cacheSize: this.apiKeyCache.size || 0
+ });
+
if (!apiKey) {
try {
const keyGetters = {
@@ -29,16 +45,33 @@ class ReasoningService extends BaseReasoningService {
gemini: () => window.electronAPI.getGeminiKey(),
};
apiKey = await keyGetters[provider]();
+
+ debugLogger.logReasoning(`${provider.toUpperCase()}_KEY_FETCHED`, {
+ provider,
+ hasKey: !!apiKey,
+ keyLength: apiKey?.length || 0,
+ keyPreview: apiKey ? `${apiKey.substring(0, 8)}...` : 'none'
+ });
+
if (apiKey) {
this.apiKeyCache.set(provider, apiKey);
}
} catch (error) {
- // API key retrieval failed
+ debugLogger.logReasoning(`${provider.toUpperCase()}_KEY_FETCH_ERROR`, {
+ provider,
+ error: (error as Error).message,
+ stack: (error as Error).stack
+ });
}
}
if (!apiKey) {
- throw new Error(`${provider.charAt(0).toUpperCase() + provider.slice(1)} API key not configured`);
+ const errorMsg = `${provider.charAt(0).toUpperCase() + provider.slice(1)} API key not configured`;
+ debugLogger.logReasoning(`${provider.toUpperCase()}_KEY_MISSING`, {
+ provider,
+ error: errorMsg
+ });
+ throw new Error(errorMsg);
}
return apiKey;
@@ -52,20 +85,59 @@ class ReasoningService extends BaseReasoningService {
): Promise<string> {
const provider = getModelProvider(model);
+ debugLogger.logReasoning("PROVIDER_SELECTION", {
+ model,
+ provider,
+ agentName,
+ hasConfig: Object.keys(config).length > 0,
+ textLength: text.length,
+ timestamp: new Date().toISOString()
+ });
+
try {
+ let result: string;
+ const startTime = Date.now();
+
+ debugLogger.logReasoning("ROUTING_TO_PROVIDER", {
+ provider,
+ model
+ });
+
switch (provider) {
case "openai":
- return await this.processWithOpenAI(text, model, agentName, config);
+ result = await this.processWithOpenAI(text, model, agentName, config);
+ break;
case "anthropic":
- return await this.processWithAnthropic(text, model, agentName, config);
+ result = await this.processWithAnthropic(text, model, agentName, config);
+ break;
case "local":
- return await this.processWithLocal(text, model, agentName, config);
+ result = await this.processWithLocal(text, model, agentName, config);
+ break;
case "gemini":
- return await this.processWithGemini(text, model, agentName, config);
+ result = await this.processWithGemini(text, model, agentName, config);
+ break;
default:
throw new Error(`Unsupported reasoning provider: ${provider}`);
}
+
+ const processingTime = Date.now() - startTime;
+
+ debugLogger.logReasoning("PROVIDER_SUCCESS", {
+ provider,
+ model,
+ processingTimeMs: processingTime,
+ resultLength: result.length,
+ resultPreview: result.substring(0, 100) + (result.length > 100 ? "..." : "")
+ });
+
+ return result;
} catch (error) {
+ debugLogger.logReasoning("PROVIDER_ERROR", {
+ provider,
+ model,
+ error: (error as Error).message,
+ stack: (error as Error).stack
+ });
// Re-throw error with provider context
throw error;
}
@@ -77,11 +149,22 @@ class ReasoningService extends BaseReasoningService {
agentName: string | null = null,
config: ReasoningConfig = {}
): Promise<string> {
+ debugLogger.logReasoning("OPENAI_START", {
+ model,
+ agentName,
+ hasApiKey: false // Will update after fetching
+ });
+
if (this.isProcessing) {
throw new Error("Already processing a request");
}
const apiKey = await this.getApiKey('openai');
+
+ debugLogger.logReasoning("OPENAI_API_KEY", {
+ hasApiKey: !!apiKey,
+ keyLength: apiKey?.length || 0
+ });
this.isProcessing = true;
@@ -125,7 +208,23 @@ class ReasoningService extends BaseReasoningService {
createApiRetryStrategy("OpenAI")
);
- return response.choices[0].message.content.trim();
+ const responseText = response.choices[0].message.content.trim();
+
+ debugLogger.logReasoning("OPENAI_RESPONSE", {
+ model,
+ responseLength: responseText.length,
+ tokensUsed: response.usage?.total_tokens || 0,
+ success: true
+ });
+
+ return responseText;
+ } catch (error) {
+ debugLogger.logReasoning("OPENAI_ERROR", {
+ model,
+ error: (error as Error).message,
+ errorType: (error as Error).name
+ });
+ throw error;
} finally {
this.isProcessing = false;
}
@@ -137,11 +236,22 @@ class ReasoningService extends BaseReasoningService {
agentName: string | null = null,
config: ReasoningConfig = {}
): Promise<string> {
+ debugLogger.logReasoning("ANTHROPIC_START", {
+ model,
+ agentName,
+ hasApiKey: false // Will update after fetching
+ });
+
if (this.isProcessing) {
throw new Error("Already processing a request");
}
const apiKey = await this.getApiKey('anthropic');
+
+ debugLogger.logReasoning("ANTHROPIC_API_KEY", {
+ hasApiKey: !!apiKey,
+ keyLength: apiKey?.length || 0
+ });
this.isProcessing = true;
@@ -184,7 +294,23 @@ class ReasoningService extends BaseReasoningService {
createApiRetryStrategy("Anthropic")
);
- return response.content[0].text.trim();
+ const responseText = response.content[0].text.trim();
+
+ debugLogger.logReasoning("ANTHROPIC_RESPONSE", {
+ model,
+ responseLength: responseText.length,
+ tokensUsed: response.usage?.total_tokens || 0,
+ success: true
+ });
+
+ return responseText;
+ } catch (error) {
+ debugLogger.logReasoning("ANTHROPIC_ERROR", {
+ model,
+ error: (error as Error).message,
+ errorType: (error as Error).name
+ });
+ throw error;
} finally {
this.isProcessing = false;
}
@@ -196,16 +322,45 @@ class ReasoningService extends BaseReasoningService {
agentName: string | null = null,
config: ReasoningConfig = {}
): Promise<string> {
+ debugLogger.logReasoning("LOCAL_START", {
+ model,
+ agentName,
+ environment: typeof window !== 'undefined' ? 'browser' : 'node'
+ });
+
// Instead of importing directly, we'll use IPC to communicate with main process
// For local models, we need to use IPC to communicate with the main process
if (typeof window !== 'undefined' && window.electronAPI) {
+ const startTime = Date.now();
+
+ debugLogger.logReasoning("LOCAL_IPC_CALL", {
+ model,
+ textLength: text.length
+ });
+
const result = await window.electronAPI.processLocalReasoning(text, model, agentName, config);
+
+ const processingTime = Date.now() - startTime;
+
if (result.success) {
+ debugLogger.logReasoning("LOCAL_SUCCESS", {
+ model,
+ processingTimeMs: processingTime,
+ resultLength: result.text.length
+ });
return result.text;
} else {
+ debugLogger.logReasoning("LOCAL_ERROR", {
+ model,
+ processingTimeMs: processingTime,
+ error: result.error
+ });
throw new Error(result.error);
}
} else {
+ debugLogger.logReasoning("LOCAL_UNAVAILABLE", {
+ reason: 'Not in Electron environment'
+ });
throw new Error('Local reasoning is not available in this environment');
}
}
@@ -216,11 +371,22 @@ class ReasoningService extends BaseReasoningService {
agentName: string | null = null,
config: ReasoningConfig = {}
): Promise<string> {
+ debugLogger.logReasoning("GEMINI_START", {
+ model,
+ agentName,
+ hasApiKey: false // Will update after fetching
+ });
+
if (this.isProcessing) {
throw new Error("Already processing a request");
}
const apiKey = await this.getApiKey('gemini');
+
+ debugLogger.logReasoning("GEMINI_API_KEY", {
+ hasApiKey: !!apiKey,
+ keyLength: apiKey?.length || 0
+ });
this.isProcessing = true;
@@ -259,8 +425,38 @@ class ReasoningService extends BaseReasoningService {
);
if (!res.ok) {
- const errorData = await res.json().catch(() => ({ error: res.statusText }));
- throw new Error(errorData.error?.message || `Gemini API error: ${res.status}`);
+ const errorText = await res.text();
+ let errorData: any = { error: res.statusText };
+
+ try {
+ errorData = JSON.parse(errorText);
+ } catch {
+ errorData = { error: errorText || res.statusText };
+ }
+
+ debugLogger.logReasoning("GEMINI_API_ERROR_DETAIL", {
+ status: res.status,
+ statusText: res.statusText,
+ error: errorData,
+ errorMessage: errorData.error?.message || errorData.message || errorData.error,
+ errorCode: errorData.error?.code,
+ errorStatus: errorData.error?.status,
+ fullResponse: errorText.substring(0, 500),
+ headers: Object.fromEntries(res.headers.entries())
+ });
+
+ // Check for common error patterns
+ const errorMessage = errorData.error?.message || errorData.message || errorData.error || `Gemini API error: ${res.status}`;
+
+ if (res.status === 403 || errorMessage.includes('quota') || errorMessage.includes('billing')) {
+ throw new Error(`Gemini API quota/billing error: ${errorMessage}. Please check your Google Cloud billing account.`);
+ } else if (res.status === 401) {
+ throw new Error(`Gemini API authentication error: Invalid API key`);
+ } else if (res.status === 400) {
+ throw new Error(`Gemini API request error: ${errorMessage}`);
+ } else {
+ throw new Error(`Gemini API error (${res.status}): ${errorMessage}`);
+ }
}
return res.json();
@@ -268,7 +464,26 @@ class ReasoningService extends BaseReasoningService {
createApiRetryStrategy("Gemini")
);
- return response.candidates[0].content.parts[0].text.trim();
+ const responseText = response.candidates[0].content.parts[0].text.trim();
+
+ debugLogger.logReasoning("GEMINI_RESPONSE", {
+ model,
+ responseLength: responseText.length,
+ tokensUsed: response.usageMetadata?.totalTokenCount || 0,
+ success: true
+ });
+
+ return responseText;
+ } catch (error) {
+ debugLogger.logReasoning("GEMINI_ERROR", {
+ model,
+ error: (error as Error).message,
+ errorType: (error as Error).name,
+ stack: (error as Error).stack,
+ apiKey: apiKey ? `${apiKey.substring(0, 8)}...${apiKey.substring(apiKey.length - 4)}` : 'missing',
+ endpoint: `${API_ENDPOINTS.GEMINI}/models/${model}:generateContent`
+ });
+ throw error;
} finally {
this.isProcessing = false;
}
@@ -282,8 +497,24 @@ class ReasoningService extends BaseReasoningService {
const geminiKey = await window.electronAPI?.getGeminiKey?.();
const localAvailable = await window.electronAPI?.checkLocalReasoningAvailable?.();
+ debugLogger.logReasoning("API_KEY_CHECK", {
+ hasOpenAI: !!openaiKey,
+ hasAnthropic: !!anthropicKey,
+ hasGemini: !!geminiKey,
+ hasLocal: !!localAvailable,
+ openAIKeyLength: openaiKey?.length || 0,
+ anthropicKeyLength: anthropicKey?.length || 0,
+ geminiKeyLength: geminiKey?.length || 0,
+ geminiKeyPreview: geminiKey ? `${geminiKey.substring(0, 8)}...` : 'none'
+ });
+
return !!(openaiKey || anthropicKey || geminiKey || localAvailable);
} catch (error) {
+ debugLogger.logReasoning("API_KEY_CHECK_ERROR", {
+ error: (error as Error).message,
+ stack: (error as Error).stack,
+ name: (error as Error).name
+ });
return false;
}
}
diff --git a/src/services/localReasoningBridge.js b/src/services/localReasoningBridge.js
index 6d4896f02..ad0eea501 100644
--- a/src/services/localReasoningBridge.js
+++ b/src/services/localReasoningBridge.js
@@ -1,4 +1,5 @@
const modelManager = require("../helpers/modelManagerBridge").default;
+const debugLogger = require("../helpers/debugLogger");
class LocalReasoningService {
constructor() {
@@ -19,11 +20,19 @@ class LocalReasoningService {
}
async processText(text, modelId, agentName = null, config = {}) {
+ debugLogger.logReasoning("LOCAL_BRIDGE_START", {
+ modelId,
+ agentName,
+ textLength: text.length,
+ hasConfig: Object.keys(config).length > 0
+ });
+
if (this.isProcessing) {
throw new Error("Already processing a request");
}
this.isProcessing = true;
+ const startTime = Date.now();
try {
// Get custom prompts from the request context
@@ -32,8 +41,13 @@ class LocalReasoningService {
// Build the reasoning prompt
const reasoningPrompt = this.getReasoningPrompt(text, agentName, customPrompts);
- // Run inference
- const result = await modelManager.runInference(modelId, reasoningPrompt, {
+ debugLogger.logReasoning("LOCAL_BRIDGE_PROMPT", {
+ promptLength: reasoningPrompt.length,
+ hasAgentName: !!agentName,
+ hasCustomPrompts: !!customPrompts
+ });
+
+ const inferenceConfig = {
maxTokens: config.maxTokens || this.calculateMaxTokens(text.length),
temperature: config.temperature || 0.7,
topK: config.topK || 40,
@@ -42,9 +56,37 @@ class LocalReasoningService {
contextSize: config.contextSize || 4096,
threads: config.threads || 4,
systemPrompt: "You are a helpful AI assistant that processes and improves text."
+ };
+
+ debugLogger.logReasoning("LOCAL_BRIDGE_INFERENCE", {
+ modelId,
+ config: inferenceConfig
+ });
+
+ // Run inference
+ const result = await modelManager.runInference(modelId, reasoningPrompt, inferenceConfig);
+
+ const processingTime = Date.now() - startTime;
+
+ debugLogger.logReasoning("LOCAL_BRIDGE_SUCCESS", {
+ modelId,
+ processingTimeMs: processingTime,
+ resultLength: result.length,
+ resultPreview: result.substring(0, 100) + (result.length > 100 ? "..." : "")
});
return result;
+ } catch (error) {
+ const processingTime = Date.now() - startTime;
+
+ debugLogger.logReasoning("LOCAL_BRIDGE_ERROR", {
+ modelId,
+ processingTimeMs: processingTime,
+ error: error.message,
+ stack: error.stack
+ });
+
+ throw error;
} finally {
this.isProcessing = false;
}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 10c86cc42..5fdff344f 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -237,6 +237,16 @@ declare global {
// Hotkey management
updateHotkey: (key: string) => Promise<void>;
+
+ // Gemini API key management
+ getGeminiKey: () => Promise<string | null>;
+ saveGeminiKey: (key: string) => Promise<void>;
+
+ // Debug logging
+ logReasoning?: (stage: string, details: any) => Promise<void>;
+
+ // FFmpeg availability
+ checkFFmpegAvailability: () => Promise<boolean>;
};
api?: {
diff --git a/src/utils/debugLoggerRenderer.js b/src/utils/debugLoggerRenderer.js
new file mode 100644
index 000000000..c32958f06
--- /dev/null
+++ b/src/utils/debugLoggerRenderer.js
@@ -0,0 +1,40 @@
+// Shared debug logger for renderer process
+const createDebugLogger = (prefix = "REASONING") => {
+ return {
+ isDebugMode: null, // Cache debug mode status
+
+ async checkDebugMode() {
+ if (this.isDebugMode === null && typeof window !== 'undefined' && window.electronAPI?.getDebugMode) {
+ try {
+ this.isDebugMode = await window.electronAPI.getDebugMode();
+ } catch {
+ this.isDebugMode = false;
+ }
+ }
+ return this.isDebugMode || false;
+ },
+
+ async logReasoning(stage, details) {
+ // Only log if debug mode is enabled
+ const debugEnabled = await this.checkDebugMode();
+ if (!debugEnabled) return;
+
+ if (typeof window !== 'undefined' && window.electronAPI?.logReasoning) {
+ try {
+ await window.electronAPI.logReasoning(stage, details);
+ } catch (error) {
+ console.error('Failed to log reasoning:', error);
+ }
+ } else {
+ // Fallback to console if IPC not available
+ console.log(`πŸ€– [${prefix} ${stage}]`, details);
+ }
+ },
+
+ clearCache() {
+ this.isDebugMode = null;
+ }
+ };
+};
+
+export default createDebugLogger;
\ No newline at end of file