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, CheckCircle, Lightbulb, Loader2, Logs, Send, Puzzle } from 'lucide-react'; import type { AIMessage } from '@/lib/SessionManager'; import { cn } from '@/lib/utils'; import { UserMessage } from '@/components/UserMessage'; import OpenAI from 'openai'; import { useTheme } from '@/hooks/useTheme'; import { isEmptyMessage } from '@/lib/isEmptyMessage'; // 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'; } interface AIMessageItemProps { message: AIMessage; isCurrentlyLoading?: boolean; toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message } export const AIMessageItem = memo(({ message, isCurrentlyLoading = false, toolCall, }: AIMessageItemProps) => { const [isToolExpanded, setIsToolExpanded] = useState(false); const [isReasoningExpanded, setIsReasoningExpanded] = useState(false); const { displayTheme } = useTheme(); // Get content to display const getContent = () => { if (typeof message.content === 'string') { return message.content; } if (Array.isArray(message.content)) { // Handle array content (like images, text blocks) return message.content .map(item => { if (typeof item === 'string') return item; if (item.type === 'text') return item.text; if (item.type === 'image_url') return `[Image: ${item.image_url.url}]`; return '[Unknown content]'; }) .join('\n'); } 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 'typecheck': return { icon: CheckCircle, title: 'TypeScript' }; case 'read_console_messages': return { icon: Logs, title: 'Read Console' }; case 'skill': return { icon: Puzzle, title: args.name ? `Skill: ${args.name}` : 'Skill' }; 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 let toolArgs: Record = {}; let toolName = ''; if (toolCall?.type === 'function') { toolName = toolCall.function.name; try { toolArgs = JSON.parse(toolCall.function.arguments); } catch { toolArgs = {}; } } // Special rendering for tools const renderSpecialContent = () => { if (toolName === 'text_editor_write' && toolArgs.file_text) { return (
{toolArgs.file_text as string}
); } if (toolName === 'text_editor_str_replace' && toolArgs.old_str && toolArgs.new_str) { const oldLines = (toolArgs.old_str as string).split('\n'); const newLines = (toolArgs.new_str as string).split('\n'); return (
{/* Old content (removed) */}
{oldLines.map((line, index) => (
- {line}
))}
{/* New content (added) */}
{newLines.map((line, index) => (
+ {line}
))}
); } // Default rendering for other tools return (
{content}
); }; // Regular tool message rendering return (
{/* -mt-2 to make it snug with the previous assistant message */} {isToolExpanded && renderSpecialContent()}
); } // Regular rendering for non-tool messages if (message.role === 'user') { // User messages: right-aligned bubble without avatar/name const userContent = typeof message.content === 'string' ? message.content : Array.isArray(message.content) ? message.content.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[] : ''; return (
); } if (message.role !== 'assistant') { return null; // Only render assistant and user messages } // If the message is empty (no content or reasoning), render nothing if (isEmptyMessage({ ...message, tool_calls: [] })) { return null; } // Assistant messages: left-aligned without avatar/name return (
{/* Reasoning content display */} {hasReasoningContent(message) && message.reasoning_content.trim() && (
{isReasoningExpanded && (
{message.reasoning_content}
)}
)} {/* Main content display */} {getContent().trim() && (
{getContent()}
)} {/* Tool calls are now hidden from assistant messages */}
); }); AIMessageItem.displayName = 'AIMessageItem';