From 39adaef4c4c6394d54e3182fc396ee4f3094819b Mon Sep 17 00:00:00 2001 From: sam Date: Wed, 1 Oct 2025 18:50:34 +0700 Subject: [PATCH 01/13] while any project session is 'busy', keep the favicon spinning --- src/App.tsx | 16 ++-- src/components/DynamicFavicon.tsx | 151 ++++++++++++++++++++++++++++++ src/hooks/useAnyProjectBusy.ts | 35 +++++++ 3 files changed, 195 insertions(+), 7 deletions(-) create mode 100644 src/components/DynamicFavicon.tsx create mode 100644 src/hooks/useAnyProjectBusy.ts diff --git a/src/App.tsx b/src/App.tsx index 45b189bf..bd3cd3eb 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -19,6 +19,7 @@ import { FSProvider } from '@/components/FSProvider'; import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider'; import { LightningFSAdapter } from '@/lib/LightningFSAdapter'; import { cleanupTmpDirectory } from '@/lib/tmpCleanup'; +import { DynamicFavicon } from '@/components/DynamicFavicon'; import AppRouter from './AppRouter'; @@ -80,13 +81,14 @@ export function App() { - - - - - - - + + + + + + + + diff --git a/src/components/DynamicFavicon.tsx b/src/components/DynamicFavicon.tsx new file mode 100644 index 00000000..8a2af7eb --- /dev/null +++ b/src/components/DynamicFavicon.tsx @@ -0,0 +1,151 @@ +import { useEffect, useRef } from 'react'; +import { useAnyProjectBusy } from '@/hooks/useAnyProjectBusy'; + +/** + * Component that dynamically updates the favicon when any project is busy with AI + * Rotates the favicon counter-clockwise when busy + */ +export function DynamicFavicon() { + const isBusy = useAnyProjectBusy(); + const canvasRef = useRef(null); + const animationRef = useRef(null); + const rotationRef = useRef(0); + const originalFaviconRef = useRef(null); + const originalImageRef = useRef(null); + + // Initialize canvas and save original favicon + useEffect(() => { + // Create canvas element for drawing the favicon + if (!canvasRef.current) { + canvasRef.current = document.createElement('canvas'); + canvasRef.current.width = 32; + canvasRef.current.height = 32; + } + + // Store the original favicon URL + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement && !originalFaviconRef.current) { + originalFaviconRef.current = faviconElement.getAttribute('href'); + } + + // Preload the favicon image + if (!originalImageRef.current) { + const img = new Image(); + img.crossOrigin = 'anonymous'; + img.src = originalFaviconRef.current || '/shakespeare.png'; + img.onload = () => { + originalImageRef.current = img; + }; + } + + return () => { + // Restore original favicon on unmount + if (originalFaviconRef.current) { + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', originalFaviconRef.current); + } + } + + // Cancel any ongoing animation + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + } + }; + }, []); + + // Handle busy state changes + useEffect(() => { + if (!canvasRef.current) return; + + // If busy, start rotation animation + if (isBusy) { + const startRotationAnimation = () => { + if (!canvasRef.current || !originalImageRef.current) { + // If image isn't loaded yet, try again in a moment + setTimeout(startRotationAnimation, 100); + return; + } + + const canvas = canvasRef.current; + const ctx = canvas.getContext('2d'); + if (!ctx) return; + + const img = originalImageRef.current; + + const animate = () => { + if (!ctx || !canvas) return; + + // Clear canvas + ctx.clearRect(0, 0, canvas.width, canvas.height); + + // Save context state + ctx.save(); + + // Translate to center for rotation + ctx.translate(canvas.width / 2, canvas.height / 2); + + // Rotate counter-clockwise + ctx.rotate(-rotationRef.current); + + // Draw the image centered + ctx.drawImage( + img, + -canvas.width / 2, + -canvas.height / 2, + canvas.width, + canvas.height + ); + + // Restore context state + ctx.restore(); + + // Update rotation for next frame (slower rotation) + rotationRef.current += 0.05; + + // Update favicon + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', canvas.toDataURL('image/png')); + } + + // Continue animation + animationRef.current = requestAnimationFrame(animate); + }; + + // Start animation loop + animate(); + }; + + startRotationAnimation(); + } else { + // If not busy, restore original favicon and stop animation + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + animationRef.current = null; + } + + // Reset rotation + rotationRef.current = 0; + + // Restore original favicon + if (originalFaviconRef.current) { + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', originalFaviconRef.current); + } + } + } + + return () => { + // Cancel animation on effect cleanup + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + animationRef.current = null; + } + }; + }, [isBusy]); + + // This component doesn't render anything visible + return null; +} diff --git a/src/hooks/useAnyProjectBusy.ts b/src/hooks/useAnyProjectBusy.ts new file mode 100644 index 00000000..24b3aae6 --- /dev/null +++ b/src/hooks/useAnyProjectBusy.ts @@ -0,0 +1,35 @@ +import { useState, useEffect } from 'react'; +import { useSessionManager } from './useSessionManager'; + +/** + * Hook to check if any project has running AI sessions + * @returns {boolean} True if any project has a running AI session + */ +export function useAnyProjectBusy(): boolean { + const sessionManager = useSessionManager(); + const [anyProjectBusy, setAnyProjectBusy] = useState(false); + + useEffect(() => { + const updateStatus = () => { + const sessions = sessionManager.getAllSessions(); + const hasBusyProject = sessions.some(session => session.isLoading); + setAnyProjectBusy(hasBusyProject); + }; + + // Initial update + updateStatus(); + + // Subscribe to session changes + sessionManager.on('sessionCreated', updateStatus); + sessionManager.on('sessionDeleted', updateStatus); + sessionManager.on('loadingChanged', updateStatus); + + return () => { + sessionManager.off('sessionCreated', updateStatus); + sessionManager.off('sessionDeleted', updateStatus); + sessionManager.off('loadingChanged', updateStatus); + }; + }, [sessionManager]); + + return anyProjectBusy; +} From 7abb0ace5a9662aca79432ca93bd8789ed9ce2ba Mon Sep 17 00:00:00 2001 From: sam Date: Fri, 3 Oct 2025 12:42:13 +0700 Subject: [PATCH 02/13] define lint spec for spaces > tabs and complete vscode/cursor setup for auto linting lint drop over zealous rule --- .vscode/settings.json | 8 +- src/components/DynamicFavicon.tsx | 234 +++++++++++++++--------------- 2 files changed, 123 insertions(+), 119 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 0a770118..0bd0fcd9 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,7 @@ { - "editor.tabSize": 2 -} \ No newline at end of file + "editor.tabSize": 2, + "editor.insertSpaces": true, + "editor.codeActionsOnSave": { + "source.fixAll.eslint": true + } +} diff --git a/src/components/DynamicFavicon.tsx b/src/components/DynamicFavicon.tsx index 8a2af7eb..9e02c0f5 100644 --- a/src/components/DynamicFavicon.tsx +++ b/src/components/DynamicFavicon.tsx @@ -6,146 +6,146 @@ import { useAnyProjectBusy } from '@/hooks/useAnyProjectBusy'; * Rotates the favicon counter-clockwise when busy */ export function DynamicFavicon() { - const isBusy = useAnyProjectBusy(); - const canvasRef = useRef(null); - const animationRef = useRef(null); - const rotationRef = useRef(0); - const originalFaviconRef = useRef(null); - const originalImageRef = useRef(null); + const isBusy = useAnyProjectBusy(); + const canvasRef = useRef(null); + const animationRef = useRef(null); + const rotationRef = useRef(0); + const originalFaviconRef = useRef(null); + const originalImageRef = useRef(null); - // Initialize canvas and save original favicon - useEffect(() => { - // Create canvas element for drawing the favicon - if (!canvasRef.current) { - canvasRef.current = document.createElement('canvas'); - canvasRef.current.width = 32; - canvasRef.current.height = 32; - } + // Initialize canvas and save original favicon + useEffect(() => { + // Create canvas element for drawing the favicon + if (!canvasRef.current) { + canvasRef.current = document.createElement('canvas'); + canvasRef.current.width = 32; + canvasRef.current.height = 32; + } - // Store the original favicon URL - const faviconElement = document.querySelector('link[rel="icon"]'); - if (faviconElement && !originalFaviconRef.current) { - originalFaviconRef.current = faviconElement.getAttribute('href'); - } + // Store the original favicon URL + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement && !originalFaviconRef.current) { + originalFaviconRef.current = faviconElement.getAttribute('href'); + } - // Preload the favicon image - if (!originalImageRef.current) { - const img = new Image(); - img.crossOrigin = 'anonymous'; - img.src = originalFaviconRef.current || '/shakespeare.png'; - img.onload = () => { - originalImageRef.current = img; - }; - } + // Preload the favicon image + if (!originalImageRef.current) { + const img = new Image(); + img.crossOrigin = 'anonymous'; + img.src = originalFaviconRef.current || '/shakespeare.png'; + img.onload = () => { + originalImageRef.current = img; + }; + } - return () => { - // Restore original favicon on unmount - if (originalFaviconRef.current) { - const faviconElement = document.querySelector('link[rel="icon"]'); - if (faviconElement) { - faviconElement.setAttribute('href', originalFaviconRef.current); - } - } + return () => { + // Restore original favicon on unmount + if (originalFaviconRef.current) { + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', originalFaviconRef.current); + } + } - // Cancel any ongoing animation - if (animationRef.current !== null) { - cancelAnimationFrame(animationRef.current); - } - }; - }, []); + // Cancel any ongoing animation + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + } + }; + }, []); - // Handle busy state changes - useEffect(() => { - if (!canvasRef.current) return; + // Handle busy state changes + useEffect(() => { + if (!canvasRef.current) return; - // If busy, start rotation animation - if (isBusy) { - const startRotationAnimation = () => { - if (!canvasRef.current || !originalImageRef.current) { - // If image isn't loaded yet, try again in a moment - setTimeout(startRotationAnimation, 100); - return; - } + // If busy, start rotation animation + if (isBusy) { + const startRotationAnimation = () => { + if (!canvasRef.current || !originalImageRef.current) { + // If image isn't loaded yet, try again in a moment + setTimeout(startRotationAnimation, 100); + return; + } - const canvas = canvasRef.current; - const ctx = canvas.getContext('2d'); - if (!ctx) return; + const canvas = canvasRef.current; + const ctx = canvas.getContext('2d'); + if (!ctx) return; - const img = originalImageRef.current; + const img = originalImageRef.current; - const animate = () => { - if (!ctx || !canvas) return; + const animate = () => { + if (!ctx || !canvas) return; - // Clear canvas - ctx.clearRect(0, 0, canvas.width, canvas.height); + // Clear canvas + ctx.clearRect(0, 0, canvas.width, canvas.height); - // Save context state - ctx.save(); + // Save context state + ctx.save(); - // Translate to center for rotation - ctx.translate(canvas.width / 2, canvas.height / 2); + // Translate to center for rotation + ctx.translate(canvas.width / 2, canvas.height / 2); - // Rotate counter-clockwise - ctx.rotate(-rotationRef.current); + // Rotate counter-clockwise + ctx.rotate(-rotationRef.current); - // Draw the image centered - ctx.drawImage( - img, - -canvas.width / 2, - -canvas.height / 2, - canvas.width, - canvas.height - ); + // Draw the image centered + ctx.drawImage( + img, + -canvas.width / 2, + -canvas.height / 2, + canvas.width, + canvas.height + ); - // Restore context state - ctx.restore(); + // Restore context state + ctx.restore(); - // Update rotation for next frame (slower rotation) - rotationRef.current += 0.05; + // Update rotation for next frame (slower rotation) + rotationRef.current += 0.05; - // Update favicon - const faviconElement = document.querySelector('link[rel="icon"]'); - if (faviconElement) { - faviconElement.setAttribute('href', canvas.toDataURL('image/png')); - } + // Update favicon + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', canvas.toDataURL('image/png')); + } - // Continue animation - animationRef.current = requestAnimationFrame(animate); - }; + // Continue animation + animationRef.current = requestAnimationFrame(animate); + }; - // Start animation loop - animate(); - }; + // Start animation loop + animate(); + }; - startRotationAnimation(); - } else { - // If not busy, restore original favicon and stop animation - if (animationRef.current !== null) { - cancelAnimationFrame(animationRef.current); - animationRef.current = null; - } + startRotationAnimation(); + } else { + // If not busy, restore original favicon and stop animation + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + animationRef.current = null; + } - // Reset rotation - rotationRef.current = 0; + // Reset rotation + rotationRef.current = 0; - // Restore original favicon - if (originalFaviconRef.current) { - const faviconElement = document.querySelector('link[rel="icon"]'); - if (faviconElement) { - faviconElement.setAttribute('href', originalFaviconRef.current); - } - } - } + // Restore original favicon + if (originalFaviconRef.current) { + const faviconElement = document.querySelector('link[rel="icon"]'); + if (faviconElement) { + faviconElement.setAttribute('href', originalFaviconRef.current); + } + } + } - return () => { - // Cancel animation on effect cleanup - if (animationRef.current !== null) { - cancelAnimationFrame(animationRef.current); - animationRef.current = null; - } - }; - }, [isBusy]); + return () => { + // Cancel animation on effect cleanup + if (animationRef.current !== null) { + cancelAnimationFrame(animationRef.current); + animationRef.current = null; + } + }; + }, [isBusy]); - // This component doesn't render anything visible - return null; + // This component doesn't render anything visible + return null; } From 3f5667d62a8d3045c7ad0b1deae8171d85229c55 Mon Sep 17 00:00:00 2001 From: sam Date: Fri, 3 Oct 2025 15:01:23 +0700 Subject: [PATCH 03/13] warn but don't fail on lint errors --- eslint.config.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/eslint.config.js b/eslint.config.js index 1e1fc7fd..b5b839f5 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -40,6 +40,8 @@ export default tseslint.config( "ignoreRestSiblings": true, }, ], + "indent": ["warn", 2], + "no-tabs": "warn", "custom/no-placeholder-comments": "error", "no-warning-comments": [ "error", From b419f88571c5bc9921288f8a72dfaf7faec19718 Mon Sep 17 00:00:00 2001 From: sam Date: Fri, 3 Oct 2025 15:01:30 +0700 Subject: [PATCH 04/13] lint --- src/hooks/useAnyProjectBusy.ts | 42 +++++++++++++++++----------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/src/hooks/useAnyProjectBusy.ts b/src/hooks/useAnyProjectBusy.ts index 24b3aae6..1ff33004 100644 --- a/src/hooks/useAnyProjectBusy.ts +++ b/src/hooks/useAnyProjectBusy.ts @@ -6,30 +6,30 @@ import { useSessionManager } from './useSessionManager'; * @returns {boolean} True if any project has a running AI session */ export function useAnyProjectBusy(): boolean { - const sessionManager = useSessionManager(); - const [anyProjectBusy, setAnyProjectBusy] = useState(false); + const sessionManager = useSessionManager(); + const [anyProjectBusy, setAnyProjectBusy] = useState(false); - useEffect(() => { - const updateStatus = () => { - const sessions = sessionManager.getAllSessions(); - const hasBusyProject = sessions.some(session => session.isLoading); - setAnyProjectBusy(hasBusyProject); - }; + useEffect(() => { + const updateStatus = () => { + const sessions = sessionManager.getAllSessions(); + const hasBusyProject = sessions.some(session => session.isLoading); + setAnyProjectBusy(hasBusyProject); + }; - // Initial update - updateStatus(); + // Initial update + updateStatus(); - // Subscribe to session changes - sessionManager.on('sessionCreated', updateStatus); - sessionManager.on('sessionDeleted', updateStatus); - sessionManager.on('loadingChanged', updateStatus); + // Subscribe to session changes + sessionManager.on('sessionCreated', updateStatus); + sessionManager.on('sessionDeleted', updateStatus); + sessionManager.on('loadingChanged', updateStatus); - return () => { - sessionManager.off('sessionCreated', updateStatus); - sessionManager.off('sessionDeleted', updateStatus); - sessionManager.off('loadingChanged', updateStatus); - }; - }, [sessionManager]); + return () => { + sessionManager.off('sessionCreated', updateStatus); + sessionManager.off('sessionDeleted', updateStatus); + sessionManager.off('loadingChanged', updateStatus); + }; + }, [sessionManager]); - return anyProjectBusy; + return anyProjectBusy; } From c48288f9e6e17fe437141e34fb7197f9eec8101e Mon Sep 17 00:00:00 2001 From: sam Date: Wed, 1 Oct 2025 16:27:46 +0700 Subject: [PATCH 05/13] 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 06/13] 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 07/13] 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 08/13] 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 09/13] 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 10/13] 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 11/13] 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 12/13] 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', () => ({ From a07241a0cb8875a2a3c60dc2b2cb37fb171b1f7b Mon Sep 17 00:00:00 2001 From: sam Date: Sat, 4 Oct 2025 22:01:51 +0700 Subject: [PATCH 13/13] =?UTF-8?q?=F0=9F=93=9C=20More=20light=20and=20light?= =?UTF-8?q?;=20more=20dark=20and=20dark=20our=20woes.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/lib/commands/ShellCommand.ts | 3 + src/lib/commands/index.ts | 1 + src/lib/commands/shakespeare.ts | 148 +++++++++++++++++++++++++++++++ src/lib/tools/ShellTool.ts | 16 ++-- 4 files changed, 162 insertions(+), 6 deletions(-) create mode 100644 src/lib/commands/shakespeare.ts diff --git a/src/lib/commands/ShellCommand.ts b/src/lib/commands/ShellCommand.ts index 52c34404..b8ec119f 100644 --- a/src/lib/commands/ShellCommand.ts +++ b/src/lib/commands/ShellCommand.ts @@ -11,6 +11,9 @@ export interface ShellCommand { /** Usage syntax for the command */ usage: string; + /** If true, this command is hidden from help and command listings (for easter eggs) */ + isEasterEgg?: boolean; + /** * Execute the command with the given arguments * @param args Array of command arguments (excluding the command name itself) diff --git a/src/lib/commands/index.ts b/src/lib/commands/index.ts index 4396089b..415c5ded 100644 --- a/src/lib/commands/index.ts +++ b/src/lib/commands/index.ts @@ -20,6 +20,7 @@ export { MvCommand } from './mv'; export { PwdCommand } from './pwd'; export { RmCommand } from './rm'; export { SedCommand } from './sed'; +export { ShakespeareCommand } from './shakespeare'; export { SortCommand } from './sort'; export { TailCommand } from './tail'; export { TouchCommand } from './touch'; diff --git a/src/lib/commands/shakespeare.ts b/src/lib/commands/shakespeare.ts new file mode 100644 index 00000000..c677c57d --- /dev/null +++ b/src/lib/commands/shakespeare.ts @@ -0,0 +1,148 @@ +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult } from "./ShellCommand"; + + +const ASCII_QUILLY = ` + + + @@@@@@% + @@ @@@ + @@ @@@ + @@ @@@ + @@%%% %@@@ @@@ + @@@@%@%@% @@@@ %@@@@% + @@@@@ @%% @@ @@@@@@@ + @@@@@ @@ @@@@@@% + @@@@ @%#@@ @@@@@@ + @@%@@@@@@@@ %@@@@@@% + @@% @ @@@ %@% @@ + @@ @@ %@@ @@ + @@ @@@%@@ %@@ + @@@@@%@@%@@@%# @@ + @@@@@@@%@@@@@@@@ @@ + @@ @@ @@ + @@ @@@ @@ @@ + @@ @@@ @@ @@ + @@ @@@ @@ @@ + @@ @@@ @@ @@ + @@ @@@ @@ @@ + @@ @@@ @@ @@ + @@ %@@ @@ @@ + @@ @@@ @@@ @@ + @@ @@@@@@@@% @@ + @@% %@% @@@ + @@ @@ + @@@ @@@ + @@@@@@@@@@@@% + @@% +`; + +/** + * Collection of Shakespeare poems + * Replace these placeholders with actual Shakespeare sonnets/excerpts + */ +const POEMS = [ + `From The Phoenix and the Turtle + +Here the anthem doth commence: +Love and constancy is dead; +Phoenix and the turtle fled +In a mutual flame from hence. + +So they loved, as love in twain +Had the essence but in one; +Two distincts, division none: +Number there in love was slain. + +Hearts remote, yet not asunder; +Distance, and no space was seen +'Twixt the turtle and his queen: +But in them it were a wonder. + +So between them love did shine, +That the turtle saw his right +Flaming in the phoenix' sight; +Either was the other's mine.`, + + `From Romeo and Juliet - Act III, Scene 5; Capulet’s orchard + +Juliet. Yon light is not day-light, I know it, I: +It is some meteor that the sun exhales,2110 +To be to thee this night a torch-bearer, +And light thee on thy way to Mantua: +Therefore stay yet; thou need'st not to be gone. + +Romeo. Let me be ta'en, let me be put to death; +I am content, so thou wilt have it so.2115 +I'll say yon grey is not the morning's eye, +'Tis but the pale reflex of Cynthia's brow; +Nor that is not the lark, whose notes do beat +The vaulty heaven so high above our heads: +I have more care to stay than will to go:2120 +Come, death, and welcome! Juliet wills it so. +How is't, my soul? let's talk; it is not day. + +Juliet. It is, it is: hie hence, be gone, away! +It is the lark that sings so out of tune, +Straining harsh discords and unpleasing sharps.2125 +Some say the lark makes sweet division; +This doth not so, for she divideth us: +Some say the lark and loathed toad change eyes, +O, now I would they had changed voices too! +Since arm from arm that voice doth us affray,2130 +Hunting thee hence with hunt's-up to the day, +O, now be gone; more light and light it grows. + +Romeo. More light and light; more dark and dark our woes!`, + + `From A lover's complaint + +'Now all these hearts that do on mine depend, +Feeling it break, with bleeding groans they pine; +And supplicant their sighs to you extend, +To leave the battery that you make 'gainst mine, +Lending soft audience to my sweet design,280 +And credent soul to that strong-bonded oath +That shall prefer and undertake my troth.' + +'This said, his watery eyes he did dismount, +Whose sights till then were levell'd on my face; +Each cheek a river running from a fount285 +With brinish current downward flow'd apace: +O, how the channel to the stream gave grace! +Who glazed with crystal gate the glowing roses +That flame through water which their hue encloses. + +'O father, what a hell of witchcraft lies290 +In the small orb of one particular tear! +But with the inundation of the eyes +What rocky heart to water will not wear? +What breast so cold that is not warmed here? +O cleft effect! cold modesty, hot wrath,295 +Both fire from hence and chill extincture hath.`, +]; + +/** + * Implementation of the 'shakespeare' command + * Display ASCII art and a random Shakespeare poem - an easter egg! + */ +export class ShakespeareCommand implements ShellCommand { + name = 'shakespeare'; + description = 'Display a quote from the Bard himself'; + usage = 'shakespeare'; + isEasterEgg = true; + + async execute(_args: string[], _cwd: string, _input?: string): Promise { + // Get random poem + const randomPoem = POEMS[Math.floor(Math.random() * POEMS.length)]; + + // Combine ASCII art and poem + const output = `${ASCII_QUILLY} + +${randomPoem} + +`; + + return createSuccessResult(output); + } +} diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index c51a3208..f51e6aca 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -25,6 +25,7 @@ import { PwdCommand, RmCommand, SedCommand, + ShakespeareCommand, SortCommand, TailCommand, TouchCommand, @@ -85,6 +86,7 @@ export class ShellTool implements Tool { this.registerCommand(new PwdCommand()); this.registerCommand(new RmCommand(fs)); this.registerCommand(new SedCommand(fs)); + this.registerCommand(new ShakespeareCommand()); this.registerCommand(new SortCommand(fs)); this.registerCommand(new TailCommand(fs)); this.registerCommand(new TouchCommand(fs)); @@ -493,13 +495,15 @@ export class ShellTool implements Tool { } /** - * Get list of available commands + * Get list of available commands (excludes hidden easter eggs) */ getAvailableCommands(): Array<{ name: string; description: string; usage: string }> { - return Array.from(this.commands.values()).map(cmd => ({ - name: cmd.name, - description: cmd.description, - usage: cmd.usage, - })); + return Array.from(this.commands.values()) + .filter(cmd => !cmd.isEasterEgg) // Hide easter egg commands from help + .map(cmd => ({ + name: cmd.name, + description: cmd.description, + usage: cmd.usage, + })); } } \ No newline at end of file