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/eslint.config.js b/eslint.config.js index 647f40e3..033a86e4 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", diff --git a/src/App.tsx b/src/App.tsx index 1bf73b8b..80dd3067 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..9e02c0f5 --- /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/components/Quilly.test.tsx b/src/components/Quilly.test.tsx new file mode 100644 index 00000000..59d388e1 --- /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/consoleMessages'; + +// 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(); + }); +}); diff --git a/src/components/Quilly.tsx b/src/components/Quilly.tsx index adb087b7..a951d6ef 100644 --- a/src/components/Quilly.tsx +++ b/src/components/Quilly.tsx @@ -9,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; @@ -58,6 +59,16 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq }; } + 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: { + label: 'Change model', + onClick: onOpenModelSelector, + }, + }; + } + // Handle OpenAI API errors with specific error codes if (error instanceof OpenAI.APIError) { switch (error.code) { diff --git a/src/hooks/useAnyProjectBusy.ts b/src/hooks/useAnyProjectBusy.ts new file mode 100644 index 00000000..1ff33004 --- /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; +} 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/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/errors/MalformedToolCallError.ts b/src/lib/errors/MalformedToolCallError.ts new file mode 100644 index 00000000..1bd79d89 --- /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); + } + } +} + 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