From c48288f9e6e17fe437141e34fb7197f9eec8101e Mon Sep 17 00:00:00 2001 From: sam Date: Wed, 1 Oct 2025 16:27:46 +0700 Subject: [PATCH 1/8] adapt console error type to simplify quillys understand --- src/lib/tools/ReadConsoleMessagesTool.ts | 59 ++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/src/lib/tools/ReadConsoleMessagesTool.ts b/src/lib/tools/ReadConsoleMessagesTool.ts index 1f8e5904..c7624be2 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.ts @@ -10,6 +10,65 @@ export interface ReadConsoleMessagesParams { * AI tool for reading console messages from the project preview. * This tool allows AI assistants to access console logs for debugging assistance. */ +export class ProjectPreviewConsoleError extends Error { + public readonly code = 'console_error' as const; + public readonly logs: ConsoleMessage[]; + + constructor(message: string, logs: ConsoleMessage[]) { + super(message); + this.name = 'ProjectPreviewConsoleError'; + this.logs = logs; + } +} + +// Simple global console messages storage +const consoleMessages: ConsoleMessage[] = []; +const errorListeners: Array<(error: ProjectPreviewConsoleError) => void> = []; + +export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { + const consoleMessage: ConsoleMessage = { + level, + message, + }; + + consoleMessages.push(consoleMessage); + + // If this is an error, notify listeners + if (level === 'error') { + const error = new ProjectPreviewConsoleError( + `Console error detected: ${message}`, + consoleMessages.filter(msg => msg.level === 'error') + ); + + errorListeners.forEach(listener => { + try { + listener(error); + } catch (err) { + console.warn('Error listener failed:', err); + } + }); + } +}; + +export const getConsoleMessages = (): ConsoleMessage[] => { + return [...consoleMessages]; +}; + +export const addErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => { + errorListeners.push(listener); +}; + +export const removeErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => { + const index = errorListeners.indexOf(listener); + if (index > -1) { + errorListeners.splice(index, 1); + } +}; + +export const clearConsoleMessages = () => { + consoleMessages.length = 0; +}; + export class ReadConsoleMessagesTool implements Tool { async execute(params: ReadConsoleMessagesParams): Promise { const { filter = 'all', limit } = params; From 8b5cf72356c772bcf8844b36c0ffb6c42e33752c Mon Sep 17 00:00:00 2001 From: sam Date: Wed, 1 Oct 2025 16:29:02 +0700 Subject: [PATCH 2/8] define and surface an error for malformed tool responses --- src/lib/SessionManager.ts | 35 ++++++++++++++++++++++-- src/lib/errors/MalformedToolCallError.ts | 22 +++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) create mode 100644 src/lib/errors/MalformedToolCallError.ts diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 22f416c1..7f9431ee 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -8,6 +8,7 @@ import type { NUser } from '@nostrify/react/login'; import type { AIProvider } from '@/contexts/AISettingsContext'; import { makeSystemPrompt } from './system'; import { NostrMetadata } from '@nostrify/nostrify'; +import { MalformedToolCallError } from './errors/MalformedToolCallError'; export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | { role: 'assistant'; @@ -283,7 +284,7 @@ export class SessionManager { // LiteLLM, Z.ai, etc. use 'reasoning_content' if (delta && 'reasoning_content' in delta && typeof delta.reasoning_content === 'string') { reasoningContent = delta.reasoning_content; - // ollama uses 'reasoning' + // ollama uses 'reasoning' } else if (delta && 'reasoning' in delta && typeof delta.reasoning === 'string') { reasoningContent = delta.reasoning; } @@ -336,10 +337,20 @@ export class SessionManager { } } - // Fix tool calls with empty arguments + // Fix tool calls with empty arguments or names for (const toolCall of accumulatedToolCalls) { if (toolCall.type === 'function') { toolCall.function.arguments = toolCall.function.arguments || '{}'; + + // Log and handle empty tool names (malformed AI response) + if (!toolCall.function.name || toolCall.function.name.trim() === '') { + console.error('Malformed tool call detected: missing function name', { + projectId, + providerModel, + toolCallId: toolCall.id, + toolCall: JSON.stringify(toolCall), + }); + } } } @@ -366,10 +377,28 @@ export class SessionManager { const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall; const toolName = functionToolCall.function.name; + + // Check for missing/empty tool name (malformed AI response) + if (!toolName || toolName.trim() === '') { + // Add detailed technical error to tool message for debugging + await this.addToolMessage( + projectId, + functionToolCall.id, + `Error: Malformed tool call received from AI provider (missing function name). This is likely a provider-specific issue. Tool call ID: ${functionToolCall.id}` + ); + + // Throw custom error to trigger Quilly UI with user-friendly message + throw new MalformedToolCallError( + 'The AI provider sent an incomplete response. This may be due to a network interruption or provider issue.', + functionToolCall.id, + providerModel + ); + } + const tool = session.customTools[toolName]; if (!tool) { - await this.addToolMessage(projectId, functionToolCall.id, `Tool ${toolName} not found`); + await this.addToolMessage(projectId, functionToolCall.id, `Tool "${toolName}" not found`); continue; } diff --git a/src/lib/errors/MalformedToolCallError.ts b/src/lib/errors/MalformedToolCallError.ts new file mode 100644 index 00000000..d2ef93b7 --- /dev/null +++ b/src/lib/errors/MalformedToolCallError.ts @@ -0,0 +1,22 @@ +/** + * Error thrown when an AI provider sends a malformed tool call response + * (e.g., missing function name in the streaming response) + */ +export class MalformedToolCallError extends Error { + public readonly code = 'malformed_tool_call' as const; + public readonly toolCallId: string; + public readonly providerModel: string; + + constructor(message: string, toolCallId: string, providerModel: string) { + super(message); + this.name = 'MalformedToolCallError'; + this.toolCallId = toolCallId; + this.providerModel = providerModel; + + // Maintains proper stack trace for where our error was thrown (only available on V8) + if (Error.captureStackTrace) { + Error.captureStackTrace(this, MalformedToolCallError); + } + } +} + From 1416c5d0179c3be25a5dd8f7bbff1de208d6a24c Mon Sep 17 00:00:00 2001 From: sam Date: Wed, 1 Oct 2025 16:29:35 +0700 Subject: [PATCH 3/8] let quilly opine on tool call errors, and streamline handling errors --- src/components/Quilly.tsx | 166 ++++++++++++++++++++------------------ 1 file changed, 88 insertions(+), 78 deletions(-) diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index adb087b7..c3342b28 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -1,4 +1,3 @@ -import OpenAI from 'openai'; import { useNavigate } from 'react-router-dom'; import { X } from 'lucide-react'; import { Button } from '@/components/ui/button'; @@ -44,95 +43,106 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq const [showCreditsDialog, setShowCreditsDialog] = useState(false); const renderBody = (error: Error): ErrorBody => { - // Handle Project Preview Console Errors - if (error instanceof ProjectPreviewConsoleError) { + // Handle errors with a code property (custom errors and API errors) + const errorCode = (error as Error & { code?: string }).code; + + if (!errorCode) { + // Generic error fallback for errors without a code property return { - message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?', - action: { - label: 'Help fix errors', - onClick: () => { - onRequestConsoleErrorHelp?.(error); - onDismiss(); - }, - }, + message: error.message + ? `AI service error: ${error.message}` + : 'Sorry, I encountered an unexpected error. Please try again.', }; } - // Handle OpenAI API errors with specific error codes - if (error instanceof OpenAI.APIError) { - switch (error.code) { - case 'invalid_api_key': - case 'invalid_request_error': + switch (errorCode) { + // Application-specific error codes + case 'console_error': + return { + message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?', + action: { + label: 'Help fix errors', + onClick: () => { + onRequestConsoleErrorHelp?.(error as ProjectPreviewConsoleError); + onDismiss(); + }, + }, + }; + + case 'malformed_tool_call': + return { + message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.', + action: { + label: 'Change model', + onClick: onOpenModelSelector, + }, + }; + + // OpenAI API error codes + case 'invalid_api_key': + case 'invalid_request_error': + return { + message: 'Authentication error: Please check your API key in AI settings.', + action: { + label: 'Check API key', + onClick: () => navigate('/settings/ai'), + } + }; + + case 'insufficient_quota': { + if (credits.data) { return { - message: 'Authentication error: Please check your API key in AI settings.', + message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`, action: { - label: 'Check API key', + label: 'Add credits', + onClick: () => setShowCreditsDialog(true), + } + }; + } else { + return { + message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.', + action: { + label: 'Check AI settings', onClick: () => navigate('/settings/ai'), } }; - - case 'insufficient_quota': { - if (credits.data) { - return { - message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`, - action: { - label: 'Add credits', - onClick: () => setShowCreditsDialog(true), - } - }; - } else { - return { - message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.', - action: { - label: 'Check AI settings', - onClick: () => navigate('/settings/ai'), - } - }; - } } - - case 'rate_limit_exceeded': - return { - message: 'Rate limit exceeded. Please wait a moment before trying again.', - }; - - case 'model_not_found': - return { - message: 'The selected AI model is not available. Please choose a different model.', - action: { - label: 'Choose model', - onClick: onOpenModelSelector, - }, - }; - - case 'context_length_exceeded': - return { - message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.', - action: { - label: 'New chat', - onClick: onNewChat, - }, - }; - - case 'server_error': - case 'service_unavailable': - return { - message: 'The AI service is temporarily unavailable. Please try again in a moment.', - }; - - default: - return { - message: `AI service error: ${error.message}`, - }; } - } - // Default fallback - return { - message: error.message - ? `AI service error: ${error.message}` - : 'Sorry, I encountered an unexpected error. Please try again.', - }; + case 'rate_limit_exceeded': + return { + message: 'Rate limit exceeded. Please wait a moment before trying again.', + }; + + case 'model_not_found': + return { + message: 'The selected AI model is not available. Please choose a different model.', + action: { + label: 'Choose model', + onClick: onOpenModelSelector, + }, + }; + + case 'context_length_exceeded': + return { + message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.', + action: { + label: 'New chat', + onClick: onNewChat, + }, + }; + + case 'server_error': + case 'service_unavailable': + return { + message: 'The AI service is temporarily unavailable. Please try again in a moment.', + }; + + default: + return { + message: `AI service error: ${error.message}`, + }; + } }; const { message, action } = renderBody(error); From d2971fcdb9333e51ebf785c694e67c73a4c1f42e Mon Sep 17 00:00:00 2001 From: sam Date: Wed, 1 Oct 2025 16:55:32 +0700 Subject: [PATCH 4/8] test quilly renders the error --- src/components/Quilly.test.tsx | 80 ++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 src/components/Quilly.test.tsx diff --git a/src/components/Quilly.test.tsx b/src/components/Quilly.test.tsx new file mode 100644 index 00000000..2df8be2a --- /dev/null +++ b/src/components/Quilly.test.tsx @@ -0,0 +1,80 @@ +import { render, screen } from '@testing-library/react'; +import { describe, it, expect, vi } from 'vitest'; +import { Quilly } from './Quilly'; +import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError'; +import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; + +// Mock all required hooks and components +vi.mock('@/hooks/useAISettings', () => ({ + useAISettings: () => ({ + settings: { + providers: [] + } + }) +})); + +vi.mock('@/hooks/useAICredits', () => ({ + useAICredits: () => ({ + data: null + }) +})); + +vi.mock('react-router-dom', () => ({ + useNavigate: () => vi.fn() +})); + +// Mock CreditsDialog to avoid NostrProvider dependency +vi.mock('./CreditsDialog', () => ({ + CreditsDialog: () => null +})); + +describe('Quilly', () => { + const defaultProps = { + error: new Error('Generic error'), + onDismiss: vi.fn(), + onNewChat: vi.fn(), + onOpenModelSelector: vi.fn(), + providerModel: 'test/model' + }; + + it('renders generic error message', () => { + render(); + + expect(screen.getByText(/AI service error: Generic error/)).toBeInTheDocument(); + }); + + it('renders correctly for malformed tool call errors', () => { + const error = new MalformedToolCallError( + 'The AI provider sent an incomplete response.', + 'call_abc123', + 'test/model' + ); + + render( + + ); + + expect(screen.getByText(/The AI sent an incomplete response/)).toBeInTheDocument(); + expect(screen.getByText(/Change model/)).toBeInTheDocument(); + }); + + it('renders correctly for console errors', () => { + const error = new ProjectPreviewConsoleError( + 'Console error', + [] + ); + + render( + + ); + + expect(screen.getByText(/I noticed some console errors/)).toBeInTheDocument(); + expect(screen.getByText(/Help fix errors/)).toBeInTheDocument(); + }); +}); From 4ebca7f077de5f53424972dfd1acdc6e4e465554 Mon Sep 17 00:00:00 2001 From: sam Date: Fri, 3 Oct 2025 15:37:50 +0700 Subject: [PATCH 5/8] lint --- src/components/Quilly.test.tsx | 100 ++++++++-------- src/components/Quilly.tsx | 142 +++++++++++------------ src/lib/errors/MalformedToolCallError.ts | 26 ++--- 3 files changed, 134 insertions(+), 134 deletions(-) diff --git a/src/components/Quilly.test.tsx b/src/components/Quilly.test.tsx index 2df8be2a..dfad2479 100644 --- a/src/components/Quilly.test.tsx +++ b/src/components/Quilly.test.tsx @@ -6,75 +6,75 @@ import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool' // Mock all required hooks and components vi.mock('@/hooks/useAISettings', () => ({ - useAISettings: () => ({ - settings: { - providers: [] - } - }) + useAISettings: () => ({ + settings: { + providers: [] + } + }) })); vi.mock('@/hooks/useAICredits', () => ({ - useAICredits: () => ({ - data: null - }) + useAICredits: () => ({ + data: null + }) })); vi.mock('react-router-dom', () => ({ - useNavigate: () => vi.fn() + useNavigate: () => vi.fn() })); // Mock CreditsDialog to avoid NostrProvider dependency vi.mock('./CreditsDialog', () => ({ - CreditsDialog: () => null + CreditsDialog: () => null })); describe('Quilly', () => { - const defaultProps = { - error: new Error('Generic error'), - onDismiss: vi.fn(), - onNewChat: vi.fn(), - onOpenModelSelector: vi.fn(), - providerModel: 'test/model' - }; + const defaultProps = { + error: new Error('Generic error'), + onDismiss: vi.fn(), + onNewChat: vi.fn(), + onOpenModelSelector: vi.fn(), + providerModel: 'test/model' + }; - it('renders generic error message', () => { - render(); + it('renders generic error message', () => { + render(); - expect(screen.getByText(/AI service error: Generic error/)).toBeInTheDocument(); - }); + expect(screen.getByText(/AI service error: Generic error/)).toBeInTheDocument(); + }); - it('renders correctly for malformed tool call errors', () => { - const error = new MalformedToolCallError( - 'The AI provider sent an incomplete response.', - 'call_abc123', - 'test/model' - ); + it('renders correctly for malformed tool call errors', () => { + const error = new MalformedToolCallError( + 'The AI provider sent an incomplete response.', + 'call_abc123', + 'test/model' + ); - render( - - ); + render( + + ); - expect(screen.getByText(/The AI sent an incomplete response/)).toBeInTheDocument(); - expect(screen.getByText(/Change model/)).toBeInTheDocument(); - }); + expect(screen.getByText(/The AI sent an incomplete response/)).toBeInTheDocument(); + expect(screen.getByText(/Change model/)).toBeInTheDocument(); + }); - it('renders correctly for console errors', () => { - const error = new ProjectPreviewConsoleError( - 'Console error', - [] - ); + it('renders correctly for console errors', () => { + const error = new ProjectPreviewConsoleError( + 'Console error', + [] + ); - render( - - ); + render( + + ); - expect(screen.getByText(/I noticed some console errors/)).toBeInTheDocument(); - expect(screen.getByText(/Help fix errors/)).toBeInTheDocument(); - }); + expect(screen.getByText(/I noticed some console errors/)).toBeInTheDocument(); + expect(screen.getByText(/Help fix errors/)).toBeInTheDocument(); + }); }); diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index c3342b28..248274b0 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -56,92 +56,92 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq } switch (errorCode) { - // Application-specific error codes - case 'console_error': - return { - message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?', - action: { - label: 'Help fix errors', - onClick: () => { - onRequestConsoleErrorHelp?.(error as ProjectPreviewConsoleError); - onDismiss(); - }, + // Application-specific error codes + case 'console_error': + return { + message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?', + action: { + label: 'Help fix errors', + onClick: () => { + onRequestConsoleErrorHelp?.(error as ProjectPreviewConsoleError); + onDismiss(); }, - }; + }, + }; - case 'malformed_tool_call': - return { - message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.', - action: { - label: 'Change model', - onClick: onOpenModelSelector, - }, - }; + case 'malformed_tool_call': + return { + message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.', + action: { + label: 'Change model', + onClick: onOpenModelSelector, + }, + }; // OpenAI API error codes - case 'invalid_api_key': - case 'invalid_request_error': + case 'invalid_api_key': + case 'invalid_request_error': + return { + message: 'Authentication error: Please check your API key in AI settings.', + action: { + label: 'Check API key', + onClick: () => navigate('/settings/ai'), + } + }; + + case 'insufficient_quota': { + if (credits.data) { return { - message: 'Authentication error: Please check your API key in AI settings.', + message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`, action: { - label: 'Check API key', + label: 'Add credits', + onClick: () => setShowCreditsDialog(true), + } + }; + } else { + return { + message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.', + action: { + label: 'Check AI settings', onClick: () => navigate('/settings/ai'), } }; - - case 'insufficient_quota': { - if (credits.data) { - return { - message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`, - action: { - label: 'Add credits', - onClick: () => setShowCreditsDialog(true), - } - }; - } else { - return { - message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.', - action: { - label: 'Check AI settings', - onClick: () => navigate('/settings/ai'), - } - }; - } } + } - case 'rate_limit_exceeded': - return { - message: 'Rate limit exceeded. Please wait a moment before trying again.', - }; + case 'rate_limit_exceeded': + return { + message: 'Rate limit exceeded. Please wait a moment before trying again.', + }; - case 'model_not_found': - return { - message: 'The selected AI model is not available. Please choose a different model.', - action: { - label: 'Choose model', - onClick: onOpenModelSelector, - }, - }; + case 'model_not_found': + return { + message: 'The selected AI model is not available. Please choose a different model.', + action: { + label: 'Choose model', + onClick: onOpenModelSelector, + }, + }; - case 'context_length_exceeded': - return { - message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.', - action: { - label: 'New chat', - onClick: onNewChat, - }, - }; + case 'context_length_exceeded': + return { + message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.', + action: { + label: 'New chat', + onClick: onNewChat, + }, + }; - case 'server_error': - case 'service_unavailable': - return { - message: 'The AI service is temporarily unavailable. Please try again in a moment.', - }; + case 'server_error': + case 'service_unavailable': + return { + message: 'The AI service is temporarily unavailable. Please try again in a moment.', + }; - default: - return { - message: `AI service error: ${error.message}`, - }; + default: + return { + message: `AI service error: ${error.message}`, + }; } }; diff --git a/src/lib/errors/MalformedToolCallError.ts b/src/lib/errors/MalformedToolCallError.ts index d2ef93b7..1bd79d89 100644 --- a/src/lib/errors/MalformedToolCallError.ts +++ b/src/lib/errors/MalformedToolCallError.ts @@ -3,20 +3,20 @@ * (e.g., missing function name in the streaming response) */ export class MalformedToolCallError extends Error { - public readonly code = 'malformed_tool_call' as const; - public readonly toolCallId: string; - public readonly providerModel: string; + public readonly code = 'malformed_tool_call' as const; + public readonly toolCallId: string; + public readonly providerModel: string; - constructor(message: string, toolCallId: string, providerModel: string) { - super(message); - this.name = 'MalformedToolCallError'; - this.toolCallId = toolCallId; - this.providerModel = providerModel; + constructor(message: string, toolCallId: string, providerModel: string) { + super(message); + this.name = 'MalformedToolCallError'; + this.toolCallId = toolCallId; + this.providerModel = providerModel; - // Maintains proper stack trace for where our error was thrown (only available on V8) - if (Error.captureStackTrace) { - Error.captureStackTrace(this, MalformedToolCallError); - } - } + // Maintains proper stack trace for where our error was thrown (only available on V8) + if (Error.captureStackTrace) { + Error.captureStackTrace(this, MalformedToolCallError); + } + } } From 76979c615098e1c0af1566c252f4fb27289d67d6 Mon Sep 17 00:00:00 2001 From: sam Date: Fri, 3 Oct 2025 16:03:09 +0700 Subject: [PATCH 6/8] revert to handle individual error types explicitly ++ ++ ++ --- src/components/Quilly.tsx | 155 +++++++++++++++++++------------------- 1 file changed, 78 insertions(+), 77 deletions(-) diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index 248274b0..a951d6ef 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -1,3 +1,4 @@ +import OpenAI from 'openai'; import { useNavigate } from 'react-router-dom'; import { X } from 'lucide-react'; import { Button } from '@/components/ui/button'; @@ -8,6 +9,7 @@ import { useAICredits } from '@/hooks/useAICredits'; import { CreditsDialog } from './CreditsDialog'; import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; import { useState } from 'react'; +import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError'; export interface QuillyProps { error: Error; @@ -43,33 +45,21 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq const [showCreditsDialog, setShowCreditsDialog] = useState(false); const renderBody = (error: Error): ErrorBody => { - // Handle errors with a code property (custom errors and API errors) - const errorCode = (error as Error & { code?: string }).code; - - if (!errorCode) { - // Generic error fallback for errors without a code property - return { - message: error.message - ? `AI service error: ${error.message}` - : 'Sorry, I encountered an unexpected error. Please try again.', - }; - } - - switch (errorCode) { - // Application-specific error codes - case 'console_error': + // Handle Project Preview Console Errors + if (error instanceof ProjectPreviewConsoleError) { return { message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?', action: { label: 'Help fix errors', onClick: () => { - onRequestConsoleErrorHelp?.(error as ProjectPreviewConsoleError); + onRequestConsoleErrorHelp?.(error); onDismiss(); }, }, }; + } - case 'malformed_tool_call': + if (error instanceof MalformedToolCallError) { return { message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.', action: { @@ -77,72 +67,83 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq onClick: onOpenModelSelector, }, }; + } - // OpenAI API error codes - case 'invalid_api_key': - case 'invalid_request_error': - return { - message: 'Authentication error: Please check your API key in AI settings.', - action: { - label: 'Check API key', - onClick: () => navigate('/settings/ai'), + // Handle OpenAI API errors with specific error codes + if (error instanceof OpenAI.APIError) { + switch (error.code) { + case 'invalid_api_key': + case 'invalid_request_error': + return { + message: 'Authentication error: Please check your API key in AI settings.', + action: { + label: 'Check API key', + onClick: () => navigate('/settings/ai'), + } + }; + + case 'insufficient_quota': { + if (credits.data) { + return { + message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`, + action: { + label: 'Add credits', + onClick: () => setShowCreditsDialog(true), + } + }; + } else { + return { + message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.', + action: { + label: 'Check AI settings', + onClick: () => navigate('/settings/ai'), + } + }; + } } - }; - case 'insufficient_quota': { - if (credits.data) { - return { - message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`, - action: { - label: 'Add credits', - onClick: () => setShowCreditsDialog(true), - } - }; - } else { - return { - message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.', - action: { - label: 'Check AI settings', - onClick: () => navigate('/settings/ai'), - } - }; + case 'rate_limit_exceeded': + return { + message: 'Rate limit exceeded. Please wait a moment before trying again.', + }; + + case 'model_not_found': + return { + message: 'The selected AI model is not available. Please choose a different model.', + action: { + label: 'Choose model', + onClick: onOpenModelSelector, + }, + }; + + case 'context_length_exceeded': + return { + message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.', + action: { + label: 'New chat', + onClick: onNewChat, + }, + }; + + case 'server_error': + case 'service_unavailable': + return { + message: 'The AI service is temporarily unavailable. Please try again in a moment.', + }; + + default: + return { + message: `AI service error: ${error.message}`, + }; } } - case 'rate_limit_exceeded': - return { - message: 'Rate limit exceeded. Please wait a moment before trying again.', - }; - - case 'model_not_found': - return { - message: 'The selected AI model is not available. Please choose a different model.', - action: { - label: 'Choose model', - onClick: onOpenModelSelector, - }, - }; - - case 'context_length_exceeded': - return { - message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.', - action: { - label: 'New chat', - onClick: onNewChat, - }, - }; - - case 'server_error': - case 'service_unavailable': - return { - message: 'The AI service is temporarily unavailable. Please try again in a moment.', - }; - - default: - return { - message: `AI service error: ${error.message}`, - }; - } + // Default fallback + return { + message: error.message + ? `AI service error: ${error.message}` + : 'Sorry, I encountered an unexpected error. Please try again.', + }; }; const { message, action } = renderBody(error); From 1eebef173f41357216dbb6a86ffc41aaa936d61e Mon Sep 17 00:00:00 2001 From: sam Date: Fri, 3 Oct 2025 16:21:43 +0700 Subject: [PATCH 7/8] merge --- src/lib/tools/ReadConsoleMessagesTool.ts | 59 ------------------------ 1 file changed, 59 deletions(-) diff --git a/src/lib/tools/ReadConsoleMessagesTool.ts b/src/lib/tools/ReadConsoleMessagesTool.ts index c7624be2..1f8e5904 100644 --- a/src/lib/tools/ReadConsoleMessagesTool.ts +++ b/src/lib/tools/ReadConsoleMessagesTool.ts @@ -10,65 +10,6 @@ export interface ReadConsoleMessagesParams { * AI tool for reading console messages from the project preview. * This tool allows AI assistants to access console logs for debugging assistance. */ -export class ProjectPreviewConsoleError extends Error { - public readonly code = 'console_error' as const; - public readonly logs: ConsoleMessage[]; - - constructor(message: string, logs: ConsoleMessage[]) { - super(message); - this.name = 'ProjectPreviewConsoleError'; - this.logs = logs; - } -} - -// Simple global console messages storage -const consoleMessages: ConsoleMessage[] = []; -const errorListeners: Array<(error: ProjectPreviewConsoleError) => void> = []; - -export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { - const consoleMessage: ConsoleMessage = { - level, - message, - }; - - consoleMessages.push(consoleMessage); - - // If this is an error, notify listeners - if (level === 'error') { - const error = new ProjectPreviewConsoleError( - `Console error detected: ${message}`, - consoleMessages.filter(msg => msg.level === 'error') - ); - - errorListeners.forEach(listener => { - try { - listener(error); - } catch (err) { - console.warn('Error listener failed:', err); - } - }); - } -}; - -export const getConsoleMessages = (): ConsoleMessage[] => { - return [...consoleMessages]; -}; - -export const addErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => { - errorListeners.push(listener); -}; - -export const removeErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => { - const index = errorListeners.indexOf(listener); - if (index > -1) { - errorListeners.splice(index, 1); - } -}; - -export const clearConsoleMessages = () => { - consoleMessages.length = 0; -}; - export class ReadConsoleMessagesTool implements Tool { async execute(params: ReadConsoleMessagesParams): Promise { const { filter = 'all', limit } = params; From 2d8d5aa7289efe789e2721c206c4499bf054cf30 Mon Sep 17 00:00:00 2001 From: sam Date: Fri, 3 Oct 2025 17:41:32 +0700 Subject: [PATCH 8/8] fix tests --- src/components/Quilly.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/Quilly.test.tsx b/src/components/Quilly.test.tsx index dfad2479..59d388e1 100644 --- a/src/components/Quilly.test.tsx +++ b/src/components/Quilly.test.tsx @@ -2,7 +2,7 @@ import { render, screen } from '@testing-library/react'; import { describe, it, expect, vi } from 'vitest'; import { Quilly } from './Quilly'; import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError'; -import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; +import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; // Mock all required hooks and components vi.mock('@/hooks/useAISettings', () => ({