diff --git a/src/components/AIMessageItem.tsx b/src/components/AIMessageItem.tsx index 1869261e..4517ce86 100644 --- a/src/components/AIMessageItem.tsx +++ b/src/components/AIMessageItem.tsx @@ -1,47 +1,15 @@ import { memo, useState } from 'react'; import { Streamdown } from 'streamdown'; -import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, Lightbulb, Loader2, Logs, Send, Puzzle, Image, AlertCircle } from 'lucide-react'; +import { Lightbulb, Loader2 } from 'lucide-react'; import type { AIMessage } from '@/lib/SessionManager'; import { cn } from '@/lib/utils'; import { UserMessage } from '@/components/UserMessage'; -import { VFSImage } from '@/components/VFSImage'; -import { Alert, AlertDescription } from '@/components/ui/alert'; -import { ImageModelDialog } from '@/components/ImageModelDialog'; import { ImageLightbox } from '@/components/ImageLightbox'; +import { ToolCallDisplay } from '@/components/ToolCallDisplay'; import OpenAI from 'openai'; import { useTheme } from '@/hooks/useTheme'; import { isEmptyMessage } from '@/lib/isEmptyMessage'; -// Component to show image generation errors inline -function ImageGenerationError() { - const [showImageModelDialog, setShowImageModelDialog] = useState(false); - - return ( - <> -
- - - - - Image generation failed. This could be due to an issue with the selected image model or the AI provider.{' '} - - - - -
- - - ); -} - // Type guard to check if message has reasoning content function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } { return message.role === 'assistant' && 'reasoning_content' in message && typeof (message as { reasoning_content?: unknown }).reasoning_content === 'string'; @@ -58,8 +26,6 @@ export const AIMessageItem = memo(({ isCurrentlyLoading = false, toolCall, }: AIMessageItemProps) => { - // All tools start collapsed by default - const [isToolExpanded, setIsToolExpanded] = useState(false); const [isReasoningExpanded, setIsReasoningExpanded] = useState(false); const [expandedImageUrl, setExpandedImageUrl] = useState(null); const { displayTheme } = useTheme(); @@ -83,162 +49,11 @@ export const AIMessageItem = memo(({ return ''; }; - // Get tool info including icon and title - const getToolInfo = () => { - if (message.role === 'tool' && toolCall) { - if (toolCall.type === 'function') { - const toolName = toolCall.function.name; - let args; - - try { - args = JSON.parse(toolCall.function.arguments); - } catch { - args = {}; - } - - // Generate icons and titles based on tool name and arguments - switch (toolName) { - case 'shell': - return { - icon: Terminal, - title: args.command ? args.command : 'Shell Command' - }; - case 'text_editor_view': { - const title = args.path - ? (args.start_line || args.end_line - ? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})` - : `Viewed ${args.path}`) - : 'Viewed File'; - return { icon: Eye, title }; - } - case 'text_editor_write': - return { - icon: FileText, - title: args.path ? `Wrote ${args.path}` : 'Wrote File' - }; - case 'text_editor_str_replace': - return { - icon: Edit, - title: args.path ? `Edited ${args.path}` : 'Edited File' - }; - case 'npm_add_package': { - const installTitle = args.name - ? (args.dev ? `Installed ${args.name} (dev)` : `Installed ${args.name}`) - : 'Installed Package'; - return { icon: Package, title: installTitle }; - } - case 'npm_remove_package': - return { - icon: PackageMinus, - title: args.name ? `Removed ${args.name}` : 'Removed Package' - }; - case 'git_commit': - return { - icon: GitCommit, - title: args.message ? `Committed: ${args.message}` : 'Committed Changes' - }; - case 'build_project': - return { - icon: Package, - title: 'Built Project' - }; - case 'nostr_read_nip': - return { - icon: BookOpen, - title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP' - }; - case 'nostr_fetch_event': - return { - icon: Download, - title: args.identifier ? `Fetched ${args.identifier.slice(0, 16)}...` : 'Fetched Event' - }; - case 'nostr_read_kind': - return { - icon: Hash, - title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind' - }; - case 'nostr_read_tag': - return { - icon: Tag, - title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag' - }; - case 'nostr_read_protocol': - return { - icon: Network, - title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol' - }; - case 'nostr_read_nips_index': - return { - icon: List, - title: 'Read NIPs Index' - }; - case 'nostr_generate_kind': - return { - icon: Plus, - title: args.range ? `Generated ${args.range} kind` : 'Generated Kind' - }; - case 'nostr_publish_events': { - const eventCount = args.events?.length || 0; - return { - icon: Send, - title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event' - }; - } - case 'deploy_project': - return { - icon: Globe, - title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project' - }; - case 'read_console_messages': - return { - icon: Logs, - title: 'Read Console' - }; - case 'skill': - return { - icon: Puzzle, - title: args.name ? `Skill: ${args.name}` : 'Skill' - }; - case 'generate_image': - return { - icon: Image, - title: args.prompt ? args.prompt : 'Generated Image' - }; - default: - return { - icon: Wrench, - title: toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()) - }; - } - } - } - - // Fallback to extracting from content - if (message.role === 'tool') { - const content = getContent(); - const lines = content.split('\n'); - const firstLine = lines[0]; - - if (firstLine && firstLine.length < 100) { - return { - icon: Wrench, - title: firstLine.replace(/^(Error |Tool |Executing |Result: )/i, '').trim() - }; - } - - return { icon: Wrench, title: 'Tool Result' }; - } - - return { icon: Wrench, title: 'Tool' }; - }; - // Special rendering for tool messages if (message.role === 'tool') { const content = getContent(); - const toolInfo = getToolInfo(); - const IconComponent = toolInfo.icon; - // Get tool call arguments for special rendering + // Get tool call arguments let toolArgs: Record = {}; let toolName = ''; if (toolCall?.type === 'function') { @@ -250,131 +65,13 @@ export const AIMessageItem = memo(({ } } - // Special rendering for tools - const renderSpecialContent = () => { - if (toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string') { - return ( -
-
- {toolArgs.file_text} -
-
- ); - } - - if (toolName === 'text_editor_str_replace' && typeof toolArgs.old_str === 'string' && typeof toolArgs.new_str === 'string') { - const oldLines = toolArgs.old_str.split('\n'); - const newLines = toolArgs.new_str.split('\n'); - - return ( -
-
- {/* Old content (removed) */} -
- {oldLines.map((line, index) => ( -
- - - - {line} - -
- ))} -
- - {/* New content (added) */} -
- {newLines.map((line, index) => ( -
- + - - {line} - -
- ))} -
-
-
- ); - } - - if (toolName === 'generate_image') { - // For generate_image, when expanded show the full prompt - return ( -
-
{typeof toolArgs.prompt === 'string' ? toolArgs.prompt : 'No prompt provided'}
-
- ); - } - - // Default rendering for other tools - return ( -
-
- {content} -
-
- ); - }; - - // Special rendering for generate_image - always show image below the tool - const renderImageBelowTool = () => { - if (toolName !== 'generate_image') return null; - - // Parse "Generated image: /tmp/filename.png" from content - const match = content.match(/Generated image:\s*(\/tmp\/[^\s\n]+)/); - if (match) { - const imagePath = match[1]; - const filename = imagePath.split('/').pop() || imagePath; - - return ( -
-
setExpandedImageUrl(imagePath)} - > - -
-
- ); - } else { - // Image generation failed - show error in place - return ; - } - }; - - // Regular tool message rendering return ( - <> -
{/* -mt-2 to make it snug with the previous assistant message */} - - - {isToolExpanded && renderSpecialContent()} - - {/* Always render image below for generate_image tool */} - {renderImageBelowTool()} -
- - {/* Image expansion lightbox */} - setExpandedImageUrl(null)} - /> - + ); } diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 341bb73e..72d2b588 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -16,6 +16,7 @@ import { useProviderModels } from '@/hooks/useProviderModels'; import { useSessionManager } from '@/hooks/useSessionManager'; import { useMCPTools } from '@/hooks/useMCPTools'; import { AIMessageItem } from '@/components/AIMessageItem'; +import { ToolCallDisplay } from '@/components/ToolCallDisplay'; import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool'; import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool'; import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool'; @@ -612,16 +613,20 @@ export const ChatPane = forwardRef(({ isCurrentlyLoading={isLoading} /> )} - {/* "Running ..." if streaming tool call is in progress */} + {/* Show tool call in "calling" state if streaming tool call is in progress */} {(streamingToolCall?.type === 'function') ? ( -
-
- - - {t('runningTool', { tool: streamingToolCall.function.name })} - -
-
+ { + try { + return JSON.parse(streamingToolCall.function.arguments); + } catch { + return {}; + } + })()} + state="calling" + /> ) : ( <> {/* Show loading skeleton if AI appears stuck generating tools */} @@ -643,30 +648,21 @@ export const ChatPane = forwardRef(({ const lastMessage = messages[messages.length - 1] as AIMessage | undefined; const lastToolCall = lastMessage?.role === 'assistant' ? lastMessage?.tool_calls?.[0] : undefined; - // "Waiting for ..." if last tool call is still executing + // Show tool call in "waiting" state if last tool call is still executing if (lastToolCall?.type === 'function') { - const isGenerateImageTool = lastToolCall.function.name === 'generate_image'; - return ( -
-
- - - {t('waitingForTool', { tool: lastToolCall.function.name })} - -
- {/* Special placeholder for generate_image tool */} - {isGenerateImageTool && ( -
-
- -
- -
-
-
- )} -
+ { + try { + return JSON.parse(lastToolCall.function.arguments); + } catch { + return {}; + } + })()} + state="waiting" + /> ); } diff --git a/src/components/ToolCallDisplay.tsx b/src/components/ToolCallDisplay.tsx new file mode 100644 index 00000000..d07fc956 --- /dev/null +++ b/src/components/ToolCallDisplay.tsx @@ -0,0 +1,404 @@ +import { useState } from 'react'; +import { + Wrench, + Eye, + FileText, + Edit, + Package, + PackageMinus, + GitCommit, + BookOpen, + Download, + Hash, + Tag, + Network, + List, + Plus, + Terminal, + Globe, + Loader2, + Logs, + Send, + Puzzle, + Image, + AlertCircle, + LucideIcon, +} from 'lucide-react'; +import { cn } from '@/lib/utils'; +import { VFSImage } from '@/components/VFSImage'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { ImageModelDialog } from '@/components/ImageModelDialog'; +import { ImageLightbox } from '@/components/ImageLightbox'; + +interface ToolInfo { + icon: LucideIcon; + title: string; + callingTitle?: string; // Title to show while calling (e.g., "Editing {path}") +} + +interface ToolCallDisplayProps { + toolName: string; + toolArgs: Record; + state: 'calling' | 'waiting' | 'completed'; + result?: string; // The tool result content (only for completed state) +} + +// Component to show image generation errors inline +function ImageGenerationError() { + const [showImageModelDialog, setShowImageModelDialog] = useState(false); + + return ( + <> +
+ + + + + Image generation failed. This could be due to an issue with the selected image model or the AI provider.{' '} + + + + +
+ + + ); +} + +/** + * Get tool information including icon, title, and calling title + */ +function getToolInfo(toolName: string, args: Record): ToolInfo { + switch (toolName) { + case 'shell': + return { + icon: Terminal, + title: args.command ? String(args.command) : 'Shell Command', + callingTitle: args.command ? String(args.command) : 'Running Shell Command', + }; + + case 'text_editor_view': { + const path = args.path ? String(args.path) : 'File'; + const hasLineRange = args.start_line || args.end_line; + const lineInfo = hasLineRange + ? ` (lines ${args.start_line || 1}-${args.end_line || 'end'})` + : ''; + return { + icon: Eye, + title: `Viewed ${path}${lineInfo}`, + callingTitle: `Viewing ${path}${lineInfo}`, + }; + } + + case 'text_editor_write': + return { + icon: FileText, + title: args.path ? `Wrote ${args.path}` : 'Wrote File', + callingTitle: args.path ? `Writing ${args.path}` : 'Writing File', + }; + + case 'text_editor_str_replace': + return { + icon: Edit, + title: args.path ? `Edited ${args.path}` : 'Edited File', + callingTitle: args.path ? `Editing ${args.path}` : 'Editing File', + }; + + case 'npm_add_package': { + const name = args.name ? String(args.name) : 'Package'; + const devSuffix = args.dev ? ' (dev)' : ''; + return { + icon: Package, + title: `Installed ${name}${devSuffix}`, + callingTitle: `Installing ${name}${devSuffix}`, + }; + } + + case 'npm_remove_package': + return { + icon: PackageMinus, + title: args.name ? `Removed ${args.name}` : 'Removed Package', + callingTitle: args.name ? `Removing ${args.name}` : 'Removing Package', + }; + + case 'git_commit': + return { + icon: GitCommit, + title: args.message ? `Committed: ${args.message}` : 'Committed Changes', + callingTitle: args.message ? `Committing: ${args.message}` : 'Committing Changes', + }; + + case 'build_project': + return { + icon: Package, + title: 'Built Project', + callingTitle: 'Building Project', + }; + + case 'nostr_read_nip': + return { + icon: BookOpen, + title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP', + callingTitle: args.nip ? `Reading NIP-${args.nip}` : 'Reading NIP', + }; + + case 'nostr_fetch_event': + return { + icon: Download, + title: args.identifier ? `Fetched ${String(args.identifier).slice(0, 16)}...` : 'Fetched Event', + callingTitle: args.identifier ? `Fetching ${String(args.identifier).slice(0, 16)}...` : 'Fetching Event', + }; + + case 'nostr_read_kind': + return { + icon: Hash, + title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind', + callingTitle: args.kind !== undefined ? `Reading Kind ${args.kind}` : 'Reading Kind', + }; + + case 'nostr_read_tag': + return { + icon: Tag, + title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag', + callingTitle: args.tag ? `Reading Tag "${args.tag}"` : 'Reading Tag', + }; + + case 'nostr_read_protocol': + return { + icon: Network, + title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol', + callingTitle: args.doc ? `Reading Protocol: ${args.doc}` : 'Reading Protocol', + }; + + case 'nostr_read_nips_index': + return { + icon: List, + title: 'Read NIPs Index', + callingTitle: 'Reading NIPs Index', + }; + + case 'nostr_generate_kind': + return { + icon: Plus, + title: args.range ? `Generated ${args.range} kind` : 'Generated Kind', + callingTitle: args.range ? `Generating ${args.range} kind` : 'Generating Kind', + }; + + case 'nostr_publish_events': { + const eventCount = Array.isArray(args.events) ? args.events.length : 0; + return { + icon: Send, + title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event', + callingTitle: eventCount > 1 ? `Publishing ${eventCount} Nostr events` : 'Publishing Nostr event', + }; + } + + case 'deploy_project': + return { + icon: Globe, + title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project', + callingTitle: args.deployServer ? `Deploying to ${args.deployServer}` : 'Deploying Project', + }; + + case 'read_console_messages': + return { + icon: Logs, + title: 'Read Console', + callingTitle: 'Reading Console', + }; + + case 'skill': + return { + icon: Puzzle, + title: args.name ? `Skill: ${args.name}` : 'Skill', + callingTitle: args.name ? `Running Skill: ${args.name}` : 'Running Skill', + }; + + case 'generate_image': + return { + icon: Image, + title: args.prompt ? String(args.prompt) : 'Generated Image', + callingTitle: args.prompt ? String(args.prompt) : 'Generating Image', + }; + + default: { + const formattedName = toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()); + return { + icon: Wrench, + title: formattedName, + callingTitle: formattedName, + }; + } + } +} + +/** + * Unified component for displaying tool calls in all states + */ +export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallDisplayProps) { + const [isExpanded, setIsExpanded] = useState(false); + const [expandedImageUrl, setExpandedImageUrl] = useState(null); + + const toolInfo = getToolInfo(toolName, toolArgs); + const IconComponent = toolInfo.icon; + + // Determine which title to show based on state + const displayTitle = state === 'completed' + ? toolInfo.title + : (toolInfo.callingTitle || toolInfo.title); + + // Only allow clicking when completed + const isClickable = state === 'completed'; + + // Render special content for specific tools when expanded + const renderExpandedContent = () => { + if (!result || !isExpanded) return null; + + if (toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string') { + return ( +
+
+ {toolArgs.file_text} +
+
+ ); + } + + if (toolName === 'text_editor_str_replace' && typeof toolArgs.old_str === 'string' && typeof toolArgs.new_str === 'string') { + const oldLines = String(toolArgs.old_str).split('\n'); + const newLines = String(toolArgs.new_str).split('\n'); + + return ( +
+
+ {/* Old content (removed) */} +
+ {oldLines.map((line, index) => ( +
+ - + + {line} + +
+ ))} +
+ + {/* New content (added) */} +
+ {newLines.map((line, index) => ( +
+ + + + {line} + +
+ ))} +
+
+
+ ); + } + + if (toolName === 'generate_image') { + // For generate_image, when expanded show the full prompt + return ( +
+
{typeof toolArgs.prompt === 'string' ? toolArgs.prompt : 'No prompt provided'}
+
+ ); + } + + // Default rendering for other tools + return ( +
+
+ {result} +
+
+ ); + }; + + // Special rendering for generate_image - always show image below the tool + const renderImageBelowTool = () => { + if (toolName !== 'generate_image' || !result) return null; + + // Parse "Generated image: /tmp/filename.png" from result + const match = result.match(/Generated image:\s*(\/tmp\/[^\s\n]+)/); + if (match) { + const imagePath = match[1]; + const filename = imagePath.split('/').pop() || imagePath; + + return ( +
+
setExpandedImageUrl(imagePath)} + > + +
+
+ ); + } else if (state === 'completed') { + // Image generation failed - show error in place + return ; + } else if (state === 'calling' || state === 'waiting') { + // Show placeholder while generating + return ( +
+
+
+
+ +
+
+
+ ); + } + }; + + return ( + <> +
+ + + {renderExpandedContent()} + {renderImageBelowTool()} +
+ + {/* Image expansion lightbox */} + setExpandedImageUrl(null)} + /> + + ); +}