Reimplement assistant/tool response rendering akin to the original Shakespeare

This commit is contained in:
Chad Curtis committed 2025-07-21 02:27:25 +00:00
1 parent 53adc58592
commit 39620a7339
14 files changed
+3736 -92

No files matched your search

+1887 -4
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -64,9 +64,12 @@
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.0",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^3.0.3",
"react-router-dom": "^6.26.2",
"react-syntax-highlighter": "^15.6.1",
"recharts": "^2.12.7",
"remark-gfm": "^4.0.1",
"sonner": "^1.5.0",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
@@ -83,6 +86,7 @@
"@types/node": "^22.5.5",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@types/react-syntax-highlighter": "^15.5.13",
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.20",
"eslint": "^9.9.0",
+40 -87
View File
@@ -3,10 +3,7 @@ import { useState, useRef, useEffect } from 'react';
import { CoreMessage, generateText, CoreUserMessage, CoreAssistantMessage, CoreToolMessage, generateId } from 'ai';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Card } from '@/components/ui/card';
import { Send, Bot, User, Settings, Play, CloudUpload } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Send, Settings, Play, CloudUpload } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { FsToolSet } from '@/lib/FsToolSet';
import { useFS } from '@/hooks/useFS';
@@ -14,6 +11,7 @@ import { useJSRuntime } from '@/hooks/useJSRuntime';
import { copyDirectory } from '@/lib/copyFiles';
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
import { bytesToHex } from 'nostr-tools/utils';
import { MessageItem } from '@/components/ai/MessageItem';
interface ChatPaneProps {
projectId: string;
@@ -129,10 +127,18 @@ BASE_DOMAIN=nostrdeploy.com`);
}, [projectName, projectId]);
useEffect(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
if (scrollAreaRef.current && messages) {
// Check if user was already at or near the bottom (within 100px threshold)
const threshold = 100;
const container = scrollAreaRef.current;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
// Only auto-scroll if user was already near the bottom
if (isNearBottom) {
container.scrollTop = container.scrollHeight;
}
}
}, [messages]);
}, [messages, isLoading]);
const createAIChat = async (projectId: string, messages: CoreMessage[]) => {
if (!isConfigured) {
@@ -288,21 +294,7 @@ When creating new components or pages, follow the existing patterns in the codeb
);
}
const renderPart = (part: (CoreUserMessage | CoreAssistantMessage | CoreToolMessage)['content'][0]) => {
if (typeof part === 'string') {
return <div className="whitespace-pre-wrap text-sm">{part}</div>;
}
switch (part.type) {
case 'text':
return <div className="whitespace-pre-wrap text-sm">{part.text}</div>;
case 'tool-call':
return <div className="text-sm text-blue-500">{part.toolName}</div>;
case 'tool-result':
return <div className="text-sm">{JSON.stringify(part.result)}</div>;
default:
return null;
}
};
return (
<div className="h-full flex flex-col">
@@ -333,93 +325,54 @@ When creating new components or pages, follow the existing patterns in the codeb
</div>
</div>
<ScrollArea className="flex-1 p-3 sm:p-4" ref={scrollAreaRef}>
<div className="space-y-3 sm:space-y-4">
<div className="flex-1 overflow-y-scroll overflow-x-hidden" ref={scrollAreaRef}>
<div className="p-4 space-y-4">
{messages.map((message, index) => (
<div
<MessageItem
key={index}
className={cn(
'flex gap-2 sm:gap-3',
message.role === 'user' ? 'justify-end' : 'justify-start'
)}
>
<div
className={cn(
'flex gap-2 max-w-[85%] sm:max-w-[80%]',
message.role === 'user' ? 'flex-row-reverse' : 'flex-row'
)}
>
<div
className={cn(
'w-7 h-7 sm:w-8 sm:h-8 rounded-full flex items-center justify-center flex-shrink-0',
message.role === 'user'
? 'bg-primary text-primary-foreground'
: 'bg-muted'
)}
>
{message.role === 'user' ? (
<User className="h-3 w-3 sm:h-4 sm:w-4" />
) : (
<Bot className="h-3 w-3 sm:h-4 sm:w-4" />
)}
</div>
<Card
className={cn(
'px-3 py-2 sm:px-4',
message.role === 'user'
? 'bg-primary text-primary-foreground'
: 'bg-muted'
)}
>
{typeof message.content === 'string' ? (
<div className="whitespace-pre-wrap text-sm">
{message.content}
</div>
) : (
<div className="whitespace-pre-wrap text-sm">
{[...message.content].map((part, i) => (
<span key={i} className="block">
{renderPart(part)}
</span>
))}
</div>
)}
</Card>
</div>
</div>
message={message}
userDisplayName="You"
allMessages={messages}
/>
))}
{isLoading && (
<div className="flex gap-2">
<div className="w-7 h-7 sm:w-8 sm:h-8 rounded-full bg-muted flex items-center justify-center flex-shrink-0">
<Bot className="h-3 w-3 sm:h-4 sm:w-4" />
</div>
<Card className="px-3 py-2 sm:px-4 bg-muted">
<div className="flex gap-3">
<div className="w-8 h-8 rounded-full bg-muted flex items-center justify-center flex-shrink-0">
<div className="flex space-x-1">
<div className="h-2 w-2 bg-current rounded-full animate-bounce [animation-delay:-0.3s]"></div>
<div className="h-2 w-2 bg-current rounded-full animate-bounce [animation-delay:-0.15s]"></div>
<div className="h-2 w-2 bg-current rounded-full animate-bounce"></div>
<div className="h-1 w-1 bg-current rounded-full animate-bounce [animation-delay:-0.3s]"></div>
<div className="h-1 w-1 bg-current rounded-full animate-bounce [animation-delay:-0.15s]"></div>
<div className="h-1 w-1 bg-current rounded-full animate-bounce"></div>
</div>
</Card>
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium text-sm">Assistant</span>
<span className="text-xs text-muted-foreground">AI</span>
</div>
<div className="text-sm text-muted-foreground">
Thinking...
</div>
</div>
</div>
)}
</div>
</ScrollArea>
</div>
<div className="border-t p-3 sm:p-4">
<div className="border-t p-4">
<div className="flex gap-2">
<Textarea
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Ask me to add features, edit files, or build your project..."
className="min-h-[60px] resize-none touch-action-manipulation overscroll-contain focus-ring"
className="min-h-[60px] resize-none"
disabled={isLoading}
/>
<Button
onClick={handleSend}
disabled={!input.trim() || isLoading}
className="self-end focus-ring"
className="self-end"
size="icon"
>
<Send className="h-4 w-4" />
+341
View File
@@ -0,0 +1,341 @@
import { memo } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Code } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { DiffRenderer } from '@/components/ai/DiffRenderer';
import { ScriptRunner } from '@/components/ai/ScriptRunner';
import { FileViewer } from '@/components/ai/FileViewer';
import { FileWriter } from '@/components/ai/FileWriter';
import { ShellCommand } from '@/components/ai/ShellCommand';
import { PackageManager } from '@/components/ai/PackageManager';
import type { CoreAssistantMessage, CoreToolMessage } from 'ai';
interface AssistantContentProps {
content: CoreAssistantMessage['content'];
allMessages?: unknown[];
}
export const AssistantContent = memo(({ content, allMessages = [] }: AssistantContentProps) => {
// Helper function to find tool result for a given tool call
const findToolResult = (toolCallId: string) => {
// Look through all tool messages to find the one with our toolCallId
for (const msg of allMessages) {
if ((msg as { role: string }).role === 'tool') {
const toolMessage = msg as CoreToolMessage;
if (Array.isArray(toolMessage.content)) {
const toolResultPart = toolMessage.content.find(
part => part.type === 'tool-result' && part.toolCallId === toolCallId
);
if (toolResultPart) {
return toolResultPart;
}
}
}
}
return undefined;
};
// Handle string content (simple text messages)
if (typeof content === 'string') {
return (
<div className="prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
// Customize code blocks to match the existing tool styling
pre: ({ children }) => (
<pre className="bg-muted/50 rounded p-3 overflow-x-auto text-sm">
{children}
</pre>
),
code: ({ children, className }) => {
const isInline = !className;
if (isInline) {
return (
<code className="bg-muted px-1.5 py-0.5 rounded text-sm font-mono">
{children}
</code>
);
}
return <code className={className}>{children}</code>;
},
// Style links
a: ({ href, children }) => (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline"
>
{children}
</a>
),
// Style blockquotes
blockquote: ({ children }) => (
<blockquote className="border-l-4 border-muted-foreground/20 pl-4 italic text-muted-foreground">
{children}
</blockquote>
),
}}
>
{content}
</ReactMarkdown>
</div>
);
}
return (
<>
{content.map((item, index) => {
if (item.type === 'text') {
return (
<div key={index} className="prose prose-sm max-w-none dark:prose-invert">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
// Customize code blocks to match the existing tool styling
pre: ({ children }) => (
<pre className="bg-muted/50 rounded p-3 overflow-x-auto text-sm">
{children}
</pre>
),
code: ({ children, className }) => {
const isInline = !className;
if (isInline) {
return (
<code className="bg-muted px-1.5 py-0.5 rounded text-sm font-mono">
{children}
</code>
);
}
return <code className={className}>{children}</code>;
},
// Style links
a: ({ href, children }) => (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline"
>
{children}
</a>
),
// Style blockquotes
blockquote: ({ children }) => (
<blockquote className="border-l-4 border-muted-foreground/20 pl-4 italic text-muted-foreground">
{children}
</blockquote>
),
}}
>
{item.text}
</ReactMarkdown>
</div>
);
} else if (item.type === 'tool-call') {
// Special rendering for js-dev__text_editor_str_replace tool
if (item.toolName === 'js-dev__text_editor_str_replace' && item.args) {
const { path, old_str, new_str } = item.args as { path: string; old_str: string; new_str: string };
return (
<DiffRenderer
key={index}
path={path}
oldStr={old_str}
newStr={new_str}
/>
);
}
// Special rendering for js-dev__run_script tool
if (item.toolName === 'js-dev__run_script' && item.args) {
const { script } = item.args as { script: string };
return (
<ScriptRunner
key={index}
script={script}
/>
);
}
// Special rendering for readFile tool
if (item.toolName === 'readFile' && item.args) {
const { filePath } = item.args as { filePath: string };
const toolResultPart = findToolResult(item.toolCallId);
let result: string | undefined;
const isError = toolResultPart?.isError || false;
if (toolResultPart && toolResultPart.result) {
if (typeof toolResultPart.result === 'string') {
result = toolResultPart.result;
} else if (toolResultPart.result && typeof toolResultPart.result === 'object') {
// Handle FsToolSet readFile result format: { content, success }
const resultObj = toolResultPart.result as Record<string, unknown>;
if (resultObj.content && typeof resultObj.content === 'string') {
result = resultObj.content;
} else {
result = JSON.stringify(toolResultPart.result);
}
}
}
return (
<FileViewer
key={index}
path={filePath}
result={result}
isError={isError}
/>
);
}
// Special rendering for writeFile tool
if (item.toolName === 'writeFile' && item.args) {
const { filePath, content } = item.args as { filePath: string; content: string };
const toolResultPart = findToolResult(item.toolCallId);
let result: string | undefined;
const isError = toolResultPart?.isError || false;
if (toolResultPart && toolResultPart.result) {
if (typeof toolResultPart.result === 'string') {
result = toolResultPart.result;
} else if (toolResultPart.result && typeof toolResultPart.result === 'object') {
// Handle FsToolSet writeFile result format: { success, message }
const resultObj = toolResultPart.result as Record<string, unknown>;
if (resultObj.message && typeof resultObj.message === 'string') {
result = resultObj.message;
} else {
result = JSON.stringify(toolResultPart.result);
}
}
}
return (
<FileWriter
key={index}
path={filePath}
fileText={content}
result={result}
isError={isError}
/>
);
}
// Special rendering for js-dev__text_editor_view tool
if (item.toolName === 'js-dev__text_editor_view' && item.args) {
const { path } = item.args as { path: string };
return (
<FileViewer
key={index}
path={path}
/>
);
}
// Special rendering for js-dev__text_editor_write tool
if (item.toolName === 'js-dev__text_editor_write' && item.args) {
const { path, file_text } = item.args as { path: string; file_text: string };
return (
<FileWriter
key={index}
path={path}
fileText={file_text}
/>
);
}
// Special rendering for js-dev__shell tool
if (item.toolName === 'js-dev__shell' && item.args) {
const { command } = item.args as { command: string };
return (
<ShellCommand
key={index}
command={command}
/>
);
}
// Special rendering for js-dev__npm_add_package tool
if (item.toolName === 'js-dev__npm_add_package' && item.args) {
const { name, version, dev } = item.args as { name: string; version?: string; dev?: boolean };
return (
<PackageManager
key={index}
action="add"
registry="npm"
packageName={name}
version={version}
dev={dev}
/>
);
}
// Special rendering for js-dev__npm_remove_package tool
if (item.toolName === 'js-dev__npm_remove_package' && item.args) {
const { name } = item.args as { name: string };
return (
<PackageManager
key={index}
action="remove"
registry="npm"
packageName={name}
/>
);
}
// Special rendering for js-dev__jsr_add_package tool
if (item.toolName === 'js-dev__jsr_add_package' && item.args) {
const { name, version, dev } = item.args as { name: string; version?: string; dev?: boolean };
return (
<PackageManager
key={index}
action="add"
registry="jsr"
packageName={name}
version={version}
dev={dev}
/>
);
}
// Special rendering for js-dev__jsr_remove_package tool
if (item.toolName === 'js-dev__jsr_remove_package' && item.args) {
const { name } = item.args as { name: string };
return (
<PackageManager
key={index}
action="remove"
registry="jsr"
packageName={name}
/>
);
}
// Default tool rendering for other tools
return (
<Card key={index} className="mt-2 bg-muted/50">
<CardContent className="p-3">
<div className="flex items-center gap-2 mb-2">
<Code className="h-4 w-4 flex-shrink-0" />
<span className="font-mono text-sm break-all">{String(item.toolName)}</span>
</div>
{item.args && typeof item.args === 'object' && item.args !== null && Object.keys(item.args).length > 0 ? (
<div className="text-xs text-muted-foreground mb-2">
<pre className="overflow-hidden text-ellipsis">
{JSON.stringify(item.args, null, 2)}
</pre>
</div>
) : null}
</CardContent>
</Card>
);
}
return null;
})}
</>
);
});
AssistantContent.displayName = 'AssistantContent';
+151
View File
@@ -0,0 +1,151 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { FileText, CheckCircle, XCircle } from 'lucide-react';
import { cn } from '@/lib/utils';
interface DiffRendererProps {
path: string;
oldStr: string;
newStr: string;
isError?: boolean;
className?: string;
}
export function DiffRenderer({ path, oldStr, newStr, isError = false, className }: DiffRendererProps) {
// Split strings into lines for diff rendering
const oldLines = oldStr.split('\n');
const newLines = newStr.split('\n');
// Simple diff algorithm - find common prefix and suffix
const findCommonPrefix = (a: string[], b: string[]) => {
let i = 0;
while (i < Math.min(a.length, b.length) && a[i] === b[i]) {
i++;
}
return i;
};
const findCommonSuffix = (a: string[], b: string[], prefixLength: number) => {
let i = 0;
const maxLength = Math.min(a.length - prefixLength, b.length - prefixLength);
while (i < maxLength && a[a.length - 1 - i] === b[b.length - 1 - i]) {
i++;
}
return i;
};
const prefixLength = findCommonPrefix(oldLines, newLines);
const suffixLength = findCommonSuffix(oldLines, newLines, prefixLength);
const commonPrefix = oldLines.slice(0, prefixLength);
const commonSuffix = oldLines.slice(oldLines.length - suffixLength);
const removedLines = oldLines.slice(prefixLength, oldLines.length - suffixLength);
const addedLines = newLines.slice(prefixLength, newLines.length - suffixLength);
return (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<FileText className="h-4 w-4 text-muted-foreground" />
<span className="font-mono text-sm font-medium">{path}</span>
</div>
<div className="flex items-center gap-2">
{isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Failed
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
<CheckCircle className="h-3 w-3 mr-1" />
Success
</Badge>
)}
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="bg-muted/30 rounded-md overflow-x-auto overflow-y-hidden">
<div className="font-mono text-xs min-w-max">
{/* Context before changes */}
{commonPrefix.length > 0 && (
<div className="border-b border-muted/50">
{commonPrefix.slice(-3).map((line, index) => (
<div key={`prefix-${index}`} className="px-3 py-1 text-muted-foreground">
<span className="inline-block w-8 text-right mr-3 select-none">
{prefixLength - 3 + index + 1}
</span>
<span className="whitespace-pre whitespace-nowrap">{line || ' '}</span>
</div>
))}
</div>
)}
{/* Removed lines */}
{removedLines.map((line, index) => (
<div key={`removed-${index}`} className="px-3 py-1 bg-red-50 text-red-800 dark:bg-red-900/20 dark:text-red-300">
<span className="inline-block w-8 text-right mr-3 select-none text-red-600 dark:text-red-400">
-{prefixLength + index + 1}
</span>
<span className="whitespace-pre whitespace-nowrap">
<span className="bg-red-200 dark:bg-red-800/50">-</span>
{line || ' '}
</span>
</div>
))}
{/* Added lines */}
{addedLines.map((line, index) => (
<div key={`added-${index}`} className="px-3 py-1 bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-300">
<span className="inline-block w-8 text-right mr-3 select-none text-green-600 dark:text-green-400">
+{prefixLength + index + 1}
</span>
<span className="whitespace-pre whitespace-nowrap">
<span className="bg-green-200 dark:bg-green-800/50">+</span>
{line || ' '}
</span>
</div>
))}
{/* Context after changes */}
{commonSuffix.length > 0 && (
<div className="border-t border-muted/50">
{commonSuffix.slice(0, 3).map((line, index) => (
<div key={`suffix-${index}`} className="px-3 py-1 text-muted-foreground">
<span className="inline-block w-8 text-right mr-3 select-none">
{prefixLength + Math.max(removedLines.length, addedLines.length) + index + 1}
</span>
<span className="whitespace-pre whitespace-nowrap">{line || ' '}</span>
</div>
))}
</div>
)}
{/* Handle case where there are no changes */}
{removedLines.length === 0 && addedLines.length === 0 && (
<div className="px-3 py-4 text-center text-muted-foreground">
No changes detected
</div>
)}
</div>
</div>
{/* Summary */}
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
{removedLines.length > 0 && (
<span className="text-red-600 dark:text-red-400">
-{removedLines.length} line{removedLines.length !== 1 ? 's' : ''}
</span>
)}
{addedLines.length > 0 && (
<span className="text-green-600 dark:text-green-400">
+{addedLines.length} line{addedLines.length !== 1 ? 's' : ''}
</span>
)}
</div>
</CardContent>
</Card>
);
}
+171
View File
@@ -0,0 +1,171 @@
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneDark, oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { useTheme } from '@/hooks/useTheme';
import { cn } from '@/lib/utils';
interface FileContentsProps {
content: string;
filePath: string;
className?: string;
showLineNumbers?: boolean;
maxHeight?: string;
showHeader?: boolean;
headerContent?: React.ReactNode;
}
export function FileContents({
content,
filePath,
className,
showLineNumbers,
maxHeight = 'max-h-80',
showHeader = true,
headerContent
}: FileContentsProps) {
const { theme } = useTheme();
// Get file extension for syntax highlighting hints
const getFileExtension = (path: string) => {
const parts = path.split('.');
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
};
// Map file extensions to syntax highlighter languages
const getLanguageFromExtension = (ext: string): string => {
const languageMap: Record<string, string> = {
'ts': 'typescript',
'tsx': 'tsx',
'js': 'javascript',
'jsx': 'jsx',
'json': 'json',
'md': 'markdown',
'css': 'css',
'scss': 'scss',
'sass': 'sass',
'less': 'less',
'html': 'html',
'xml': 'xml',
'svg': 'xml',
'yml': 'yaml',
'yaml': 'yaml',
'toml': 'toml',
'py': 'python',
'rb': 'ruby',
'php': 'php',
'java': 'java',
'c': 'c',
'cpp': 'cpp',
'cs': 'csharp',
'go': 'go',
'rs': 'rust',
'sh': 'bash',
'bash': 'bash',
'zsh': 'bash',
'fish': 'bash',
'sql': 'sql',
'dockerfile': 'dockerfile',
'gitignore': 'gitignore',
'env': 'bash',
'ini': 'ini',
'conf': 'nginx',
'nginx': 'nginx',
'apache': 'apache',
'htaccess': 'apache',
'vim': 'vim',
'lua': 'lua',
'r': 'r',
'matlab': 'matlab',
'swift': 'swift',
'kotlin': 'kotlin',
'dart': 'dart',
'elm': 'elm',
'haskell': 'haskell',
'clojure': 'clojure',
'scala': 'scala',
'perl': 'perl',
'powershell': 'powershell',
'makefile': 'makefile',
'cmake': 'cmake',
'gradle': 'gradle',
'properties': 'properties',
'diff': 'diff',
'patch': 'diff',
'log': 'log'
};
return languageMap[ext] || 'text';
};
// Check if content should be syntax highlighted
const shouldHighlight = (ext: string, text: string): boolean => {
// Don't highlight very large files (over 50KB) for performance
if (text.length > 50000) return false;
// Don't highlight binary-looking content (check for null bytes and other binary indicators)
if (text.includes('\0') || text.includes('\uFFFD')) return false;
// Always highlight known code file extensions
const codeExtensions = ['ts', 'tsx', 'js', 'jsx', 'json', 'css', 'scss', 'html', 'xml', 'py', 'rb', 'php', 'java', 'c', 'cpp', 'cs', 'go', 'rs', 'sh', 'bash', 'sql', 'yml', 'yaml', 'toml', 'md'];
return codeExtensions.includes(ext);
};
const fileExtension = getFileExtension(filePath);
const shouldUseHighlighting = shouldHighlight(fileExtension, content);
// Determine if we should show line numbers
const shouldShowLineNumbers = showLineNumbers ?? (content.split('\n').length > 10);
return (
<div className={cn("bg-muted/30 rounded-md overflow-hidden", className)}>
{showHeader && (
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50 flex items-center justify-between">
<span>File Contents</span>
{headerContent || (fileExtension && (
<span className="text-xs bg-muted px-2 py-1 rounded">
{fileExtension.toUpperCase()}
</span>
))}
</div>
)}
<div className={cn("p-0 overflow-auto", maxHeight)}>
{shouldUseHighlighting ? (
<SyntaxHighlighter
language={getLanguageFromExtension(fileExtension)}
style={theme === 'dark' ? oneDark : oneLight}
customStyle={{
margin: 0,
padding: '12px',
fontSize: '12px',
lineHeight: '1.4',
background: 'transparent',
border: 'none',
borderRadius: 0,
}}
codeTagProps={{
style: {
fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace',
}
}}
showLineNumbers={shouldShowLineNumbers}
lineNumberStyle={{
minWidth: '2.5em',
paddingRight: '1em',
color: theme === 'dark' ? '#6b7280' : '#9ca3af',
fontSize: '11px',
}}
wrapLines={false}
wrapLongLines={false}
>
{content}
</SyntaxHighlighter>
) : (
<div className="p-3">
<pre className="text-xs font-mono whitespace-pre text-foreground">
{content}
</pre>
</div>
)}
</div>
</div>
);
}
+175
View File
@@ -0,0 +1,175 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { CheckCircle, XCircle, Eye } from 'lucide-react';
import { cn } from '@/lib/utils';
import { FileContents } from '@/components/ai/FileContents';
interface FileViewerProps {
path: string;
result?: string;
isError?: boolean;
className?: string;
}
export function FileViewer({ path, result, isError = false, className }: FileViewerProps) {
// Determine if it's a directory or file based on the result
const isDirectory = result?.includes('├──') || result?.includes('└──') || result?.includes('│');
// Get file extension for syntax highlighting hints
const getFileExtension = (filePath: string) => {
const parts = filePath.split('.');
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
};
const getFileIcon = (filePath: string, isDir: boolean) => {
if (isDir) return '📁';
const ext = getFileExtension(filePath);
switch (ext) {
case 'ts':
case 'tsx': return '🔷';
case 'js':
case 'jsx': return '🟨';
case 'json': return '📋';
case 'md': return '📝';
case 'css': return '🎨';
case 'html': return '🌐';
case 'svg': return '🖼️';
case 'png':
case 'jpg':
case 'jpeg':
case 'gif': return '🖼️';
case 'yml':
case 'yaml': return '⚙️';
case 'toml': return '⚙️';
case 'lock': return '🔒';
default: return '📄';
}
};
const fileIcon = getFileIcon(path, isDirectory || false);
const fileExtension = getFileExtension(path);
// Parse directory structure for better display
const parseDirectoryStructure = (content: string) => {
if (!isDirectory) return content;
const lines = content.split('\n').filter(line => line.trim());
return lines.map((line) => {
// Extract the file/folder name from tree structure
const match = line.match(/[├└]──\s*(.+)$/);
if (match) {
const name = match[1];
const isFolder = !name.includes('.');
const icon = isFolder ? '📁' : getFileIcon(name, false);
return { line, name, icon, isFolder };
}
return { line, name: line.trim(), icon: '📄', isFolder: false };
});
};
const directoryItems = isDirectory ? parseDirectoryStructure(result || '') : [];
const directoryItemsArray = Array.isArray(directoryItems) ? directoryItems : [];
return (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<Eye className="h-4 w-4 text-muted-foreground" />
<span className="text-lg">{fileIcon}</span>
</div>
<div>
<div className="font-mono text-sm font-medium">{path}</div>
<div className="text-xs text-muted-foreground">
{isDirectory ? 'Directory listing' : `${fileExtension ? fileExtension.toUpperCase() + ' file' : 'File'} contents`}
</div>
</div>
</div>
<div className="flex items-center gap-2">
{result ? (
isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Error
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
<CheckCircle className="h-3 w-3 mr-1" />
Viewed
</Badge>
)
) : (
<Badge variant="secondary" className="text-xs bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-400">
<Eye className="h-3 w-3 mr-1" />
Loading
</Badge>
)}
</div>
</div>
</CardHeader>
{result && (
<CardContent className="pt-0">
{isError ? (
<div className="bg-destructive/10 text-destructive border border-destructive/20 rounded-md p-3 text-sm">
{result}
</div>
) : isDirectory ? (
<div className="bg-muted/30 rounded-md overflow-hidden">
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50">
Directory Structure
</div>
<div className="p-3 max-h-80 overflow-y-auto">
<div className="space-y-1">
{directoryItemsArray.map((item, index) => (
<div key={index} className="flex items-center gap-2 text-sm font-mono">
<span className="text-muted-foreground">{item.line.replace(/[├└]──\s*(.+)$/, '')}</span>
<span className="text-xs">{item.icon}</span>
<span className={cn(
item.isFolder ? "text-blue-600 dark:text-blue-400 font-medium" : "text-foreground"
)}>
{item.name}
</span>
</div>
))}
</div>
</div>
</div>
) : (
<FileContents
content={result}
filePath={path}
headerContent={fileExtension && (
<span className="text-xs bg-muted px-2 py-1 rounded">
{fileExtension.toUpperCase()}
</span>
)}
/>
)}
{/* File stats */}
{!isError && result && (
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
{isDirectory ? (
<span>
{directoryItemsArray.length} item{directoryItemsArray.length !== 1 ? 's' : ''}
</span>
) : (
<>
<span>
{result.split('\n').length} line{result.split('\n').length !== 1 ? 's' : ''}
</span>
<span>
{result.length} character{result.length !== 1 ? 's' : ''}
</span>
</>
)}
</div>
)}
</CardContent>
)}
</Card>
);
}
+152
View File
@@ -0,0 +1,152 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { CheckCircle, XCircle, Edit3 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { FileContents } from '@/components/ai/FileContents';
interface FileWriterProps {
path: string;
fileText: string;
result?: string;
isError?: boolean;
className?: string;
}
export function FileWriter({ path, fileText, result, isError = false, className }: FileWriterProps) {
// Get file extension for syntax highlighting hints
const getFileExtension = (filePath: string) => {
const parts = filePath.split('.');
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
};
const getFileIcon = (filePath: string) => {
const ext = getFileExtension(filePath);
switch (ext) {
case 'ts':
case 'tsx': return '🔷';
case 'js':
case 'jsx': return '🟨';
case 'json': return '📋';
case 'md': return '📝';
case 'css': return '🎨';
case 'html': return '🌐';
case 'svg': return '🖼️';
case 'png':
case 'jpg':
case 'jpeg':
case 'gif': return '🖼️';
case 'yml':
case 'yaml': return '⚙️';
case 'toml': return '⚙️';
case 'lock': return '🔒';
default: return '📄';
}
};
const fileIcon = getFileIcon(path);
const fileExtension = getFileExtension(path);
const isNewFile = path.includes('new') || result?.includes('created') || result?.includes('Created');
// Calculate file stats
const lineCount = fileText.split('\n').length;
const charCount = fileText.length;
const wordCount = fileText.split(/\s+/).filter(word => word.length > 0).length;
// Preview first few lines for collapsed view
const previewLines = fileText.split('\n').slice(0, 5);
const hasMoreLines = lineCount > 5;
const previewContent = previewLines.join('\n') + (hasMoreLines ? `\n... (${lineCount - 5} more lines)` : '');
return (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<Edit3 className="h-4 w-4 text-muted-foreground" />
<span className="text-lg">{fileIcon}</span>
</div>
<div>
<div className="font-mono text-sm font-medium">{path}</div>
<div className="text-xs text-muted-foreground">
{isNewFile ? 'Created new file' : 'Updated file contents'}
</div>
</div>
</div>
<div className="flex items-center gap-2">
{result !== undefined ? (
isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Failed
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
<CheckCircle className="h-3 w-3 mr-1" />
{isNewFile ? 'Created' : 'Updated'}
</Badge>
)
) : (
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
<Edit3 className="h-3 w-3 mr-1" />
Writing
</Badge>
)}
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
{/* Error display */}
{isError && result && (
<div className="mb-3 bg-destructive/10 text-destructive border border-destructive/20 rounded-md p-3 text-sm">
{result}
</div>
)}
{/* File stats */}
<div className="mb-3 flex items-center gap-4 text-xs">
<span className="text-muted-foreground">
{lineCount} line{lineCount !== 1 ? 's' : ''}
</span>
<span className="text-muted-foreground">
{wordCount} word{wordCount !== 1 ? 's' : ''}
</span>
<span className="text-muted-foreground">
{charCount} character{charCount !== 1 ? 's' : ''}
</span>
{fileExtension && (
<Badge variant="outline" className="text-xs">
{fileExtension.toUpperCase()}
</Badge>
)}
</div>
{/* File preview */}
<details className="group">
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
<span className="group-open:rotate-90 transition-transform">▶</span>
Preview file contents
</summary>
<FileContents
content={hasMoreLines ? previewContent : fileText}
filePath={path}
showLineNumbers={false}
headerContent={fileExtension && (
<span className="text-xs bg-muted px-2 py-1 rounded">
{fileExtension.toUpperCase()}
</span>
)}
/>
</details>
{/* Success message */}
{!isError && result && (
<div className="mt-3 text-xs text-green-600 dark:text-green-400">
✓ File {isNewFile ? 'created' : 'updated'} successfully
</div>
)}
</CardContent>
</Card>
);
}
+74
View File
@@ -0,0 +1,74 @@
import { memo } from 'react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { AssistantContent } from '@/components/ai/AssistantContent';
import { Bot, User } from 'lucide-react';
import type { CoreUserMessage, CoreAssistantMessage, CoreToolMessage } from 'ai';
interface MessageItemProps {
message: (CoreUserMessage | CoreAssistantMessage | CoreToolMessage) & { id: string };
userDisplayName?: string;
userProfileImage?: string;
allMessages?: ((CoreUserMessage | CoreAssistantMessage | CoreToolMessage) & { id: string })[];
}
export const MessageItem = memo(({
message,
userDisplayName = 'You',
userProfileImage,
allMessages = []
}: MessageItemProps) => {
// Don't render tool messages as separate items - they're integrated into assistant messages
if (message.role === 'tool') {
return null;
}
return (
<div className="flex gap-3">
<Avatar className="h-8 w-8 flex-shrink-0">
{message.role === 'user' ? (
<>
<AvatarImage src={userProfileImage} alt={userDisplayName} />
<AvatarFallback>
<User className="h-4 w-4" />
</AvatarFallback>
</>
) : (
<>
<AvatarFallback>
<Bot className="h-4 w-4" />
</AvatarFallback>
</>
)}
</Avatar>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium text-sm">
{message.role === 'user' ? userDisplayName : 'Assistant'}
</span>
<span className="text-xs text-muted-foreground">
{message.role === 'user' ? 'User' : 'AI'}
</span>
</div>
<div className="text-sm">
{message.role === 'user' ? (
<div className="whitespace-pre-wrap break-words">
{typeof message.content === 'string' ? message.content :
message.content.map((part, _i) => {
if (part.type === 'text') return part.text;
return null;
}).join('')
}
</div>
) : message.role === 'assistant' ? (
<AssistantContent
content={(message as CoreAssistantMessage).content}
allMessages={allMessages}
/>
) : null}
</div>
</div>
</div>
);
});
MessageItem.displayName = 'MessageItem';
+243
View File
@@ -0,0 +1,243 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Package, Plus, Minus, CheckCircle, XCircle } from 'lucide-react';
import { cn } from '@/lib/utils';
interface PackageManagerProps {
action: 'add' | 'remove';
registry: 'npm' | 'jsr';
packageName: string;
version?: string;
dev?: boolean;
result?: string;
isError?: boolean;
className?: string;
}
export function PackageManager({
action,
registry,
packageName,
version,
dev,
result,
isError = false,
className
}: PackageManagerProps) {
// Get package info
const getPackageInfo = (name: string) => {
// Common package icons
if (name.includes('react')) return '⚛️';
if (name.includes('vue')) return '💚';
if (name.includes('angular')) return '🅰️';
if (name.includes('typescript') || name.includes('@types/')) return '🔷';
if (name.includes('eslint')) return '🔍';
if (name.includes('prettier')) return '✨';
if (name.includes('vite')) return '⚡';
if (name.includes('webpack')) return '📦';
if (name.includes('babel')) return '🐠';
if (name.includes('jest') || name.includes('vitest')) return '🧪';
if (name.includes('tailwind')) return '🎨';
if (name.includes('sass') || name.includes('scss')) return '🎨';
if (name.includes('lodash')) return '🔧';
if (name.includes('axios')) return '🌐';
if (name.includes('express')) return '🚀';
if (name.includes('next')) return '▲';
if (name.includes('nuxt')) return '💚';
if (name.includes('svelte')) return '🧡';
if (name.includes('prisma')) return '🔺';
if (name.includes('graphql')) return '🔗';
if (name.includes('socket')) return '🔌';
if (name.includes('redis')) return '🔴';
if (name.includes('mongo')) return '🍃';
if (name.includes('postgres')) return '🐘';
if (name.includes('mysql')) return '🐬';
if (name.includes('docker')) return '🐳';
if (name.includes('kubernetes')) return '☸️';
if (name.includes('aws')) return '☁️';
if (name.includes('firebase')) return '🔥';
if (name.includes('stripe')) return '💳';
if (name.includes('auth')) return '🔐';
if (name.includes('crypto')) return '🔒';
if (name.includes('date') || name.includes('moment')) return '📅';
if (name.includes('uuid')) return '🆔';
if (name.includes('validator')) return '✅';
if (name.includes('helmet')) return '⛑️';
if (name.includes('cors')) return '🌐';
if (name.includes('dotenv')) return '🔧';
if (name.includes('nodemon')) return '👀';
if (name.includes('concurrently')) return '🔄';
if (name.includes('husky')) return '🐶';
if (name.includes('lint-staged')) return '🎭';
if (name.includes('commitizen')) return '📝';
if (name.includes('semantic-release')) return '🚀';
if (name.includes('storybook')) return '📚';
if (name.includes('cypress')) return '🌲';
if (name.includes('playwright')) return '🎭';
if (name.includes('puppeteer')) return '🎪';
return '📦';
};
const packageIcon = getPackageInfo(packageName);
const registryIcon = registry === 'jsr' ? '🦕' : '📦';
// Parse output for useful information
const parseOutput = (output: string) => {
if (!output) return { summary: '', details: output };
if (action === 'add') {
if (output.includes('added') || output.includes('installed')) {
return {
summary: `Successfully added ${packageName}${version ? `@${version}` : ''}`,
details: output
};
}
if (output.includes('already exists') || output.includes('up to date')) {
return {
summary: `${packageName} is already installed`,
details: output
};
}
}
if (action === 'remove') {
if (output.includes('removed') || output.includes('uninstalled')) {
return {
summary: `Successfully removed ${packageName}`,
details: output
};
}
if (output.includes('not found') || output.includes('not installed')) {
return {
summary: `${packageName} was not installed`,
details: output
};
}
}
return {
summary: `Package ${action} completed`,
details: output
};
};
const { summary, details } = parseOutput(result || '');
return (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<Package className="h-4 w-4 text-muted-foreground" />
<span className="text-lg">{packageIcon}</span>
<span className="text-sm">{registryIcon}</span>
</div>
<div>
<div className="font-mono text-sm font-medium">
{action === 'add' ? (
<span className="flex items-center gap-1">
<Plus className="h-3 w-3 text-green-600" />
{packageName}{version && `@${version}`}
</span>
) : (
<span className="flex items-center gap-1">
<Minus className="h-3 w-3 text-red-600" />
{packageName}
</span>
)}
</div>
<div className="text-xs text-muted-foreground">
{action === 'add' ? 'Install' : 'Remove'} {registry.toUpperCase()} package
{dev && ' (dev dependency)'}
</div>
</div>
</div>
<div className="flex items-center gap-2">
{result !== undefined ? (
isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Failed
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
<CheckCircle className="h-3 w-3 mr-1" />
Success
</Badge>
)
) : (
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
<Package className="h-3 w-3 mr-1" />
{action === 'add' ? 'Installing' : 'Removing'}
</Badge>
)}
</div>
</div>
</CardHeader>
{result && (
<CardContent className="pt-0">
{/* Summary */}
{summary && (
<div className={cn(
"mb-3 p-3 rounded-md text-sm font-medium",
isError
? "bg-destructive/10 text-destructive border border-destructive/20"
: "bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-400 border border-green-200 dark:border-green-800/30"
)}>
{summary}
</div>
)}
{/* Full output */}
{details && details.trim() && (
<details className="group">
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
<span className="group-open:rotate-90 transition-transform">▶</span>
View package manager output
</summary>
<div className="bg-muted/30 rounded-md overflow-hidden">
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50">
Package Manager Output
</div>
<div className="p-3 max-h-80 overflow-auto">
<pre className="text-xs font-mono whitespace-pre text-muted-foreground">
{details}
</pre>
</div>
</div>
</details>
)}
{/* Package info */}
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
<span className="flex items-center gap-1">
{registryIcon} {registry.toUpperCase()} registry
</span>
{version && (
<span>
Version: {version}
</span>
)}
{dev && (
<span className="text-orange-600 dark:text-orange-400">
Development dependency
</span>
)}
{action === 'add' && (
<span className="text-green-600 dark:text-green-400">
Added to project
</span>
)}
{action === 'remove' && (
<span className="text-red-600 dark:text-red-400">
Removed from project
</span>
)}
</div>
</CardContent>
)}
</Card>
);
}
+208
View File
@@ -0,0 +1,208 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Play, CheckCircle, XCircle } from 'lucide-react';
import { cn } from '@/lib/utils';
interface ScriptRunnerProps {
script: string;
result?: string;
isError?: boolean;
className?: string;
}
export function ScriptRunner({ script, result, isError = false, className }: ScriptRunnerProps) {
// Get script info
const getScriptInfo = (scriptName: string) => {
switch (scriptName) {
case 'build': return { icon: '🔨', description: 'Build the project for production' };
case 'test': return { icon: '🧪', description: 'Run tests and linting' };
case 'dev': return { icon: '🚀', description: 'Start development server' };
case 'start': return { icon: '▶️', description: 'Start the application' };
case 'lint': return { icon: '🔍', description: 'Check code quality' };
case 'format': return { icon: '✨', description: 'Format code' };
case 'preview': return { icon: '👀', description: 'Preview production build' };
case 'deploy': return { icon: '🚀', description: 'Deploy to production' };
default: return { icon: '⚡', description: 'Run script' };
}
};
const scriptInfo = getScriptInfo(script);
// Parse output for useful information
const parseOutput = (output: string) => {
if (!output) return { summary: '', details: output };
const lines = output.split('\n').filter(line => line.trim());
// Look for common patterns
if (script === 'build') {
if (output.includes('built in') || output.includes('Build completed')) {
return {
summary: 'Build completed successfully',
details: output
};
}
if (output.includes('error') || output.includes('Error')) {
return {
summary: 'Build failed with errors',
details: output
};
}
}
if (script === 'test') {
const passMatch = output.match(/(\d+) passing/);
const failMatch = output.match(/(\d+) failing/);
if (passMatch || failMatch) {
const passing = passMatch ? passMatch[1] : '0';
const failing = failMatch ? failMatch[1] : '0';
return {
summary: `Tests completed: ${passing} passing, ${failing} failing`,
details: output
};
}
if (output.includes('All tests passed') || output.includes('✓')) {
return {
summary: 'All tests passed',
details: output
};
}
}
if (script === 'lint') {
if (output.includes('No linting errors found') || output.includes('✓')) {
return {
summary: 'No linting errors found',
details: output
};
}
const errorMatch = output.match(/(\d+) error/);
const warningMatch = output.match(/(\d+) warning/);
if (errorMatch || warningMatch) {
const errors = errorMatch ? errorMatch[1] : '0';
const warnings = warningMatch ? warningMatch[1] : '0';
return {
summary: `Linting completed: ${errors} errors, ${warnings} warnings`,
details: output
};
}
}
// Default: use last meaningful line
const meaningfulLines = lines.filter(line =>
!line.startsWith('#') &&
!line.startsWith('//') &&
line.length > 0
);
return {
summary: meaningfulLines[meaningfulLines.length - 1] || 'Script executed',
details: output
};
};
const { summary, details } = parseOutput(result || '');
return (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<Play className="h-4 w-4 text-muted-foreground" />
<span className="text-lg">{scriptInfo.icon}</span>
</div>
<div>
<div className="font-mono text-sm font-medium">npm run {script}</div>
<div className="text-xs text-muted-foreground">{scriptInfo.description}</div>
</div>
</div>
<div className="flex items-center gap-2">
{result !== undefined ? (
isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Failed
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
<CheckCircle className="h-3 w-3 mr-1" />
Success
</Badge>
)
) : (
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
<Play className="h-3 w-3 mr-1" />
Running
</Badge>
)}
</div>
</div>
</CardHeader>
{result && (
<CardContent className="pt-0">
{/* Summary */}
{summary && (
<div className={cn(
"mb-3 p-3 rounded-md text-sm font-medium",
isError
? "bg-destructive/10 text-destructive border border-destructive/20"
: "bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-400 border border-green-200 dark:border-green-800/30"
)}>
{summary}
</div>
)}
{/* Full output */}
{details && details.trim() && (
<details className="group">
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
<span className="group-open:rotate-90 transition-transform">▶</span>
View script output
</summary>
<div className="bg-muted/30 rounded-md overflow-hidden">
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50">
Script Output
</div>
<div className="p-3 max-h-80 overflow-auto">
<pre className="text-xs font-mono whitespace-pre text-muted-foreground">
{details}
</pre>
</div>
</div>
</details>
)}
{/* Script stats */}
{!isError && details && (
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
<span>
{details.split('\n').length} line{details.split('\n').length !== 1 ? 's' : ''} output
</span>
{script === 'build' && details.includes('built in') && (
<span>
Build time: {details.match(/built in (\d+\.?\d*[a-z]+)/)?.[1] || 'unknown'}
</span>
)}
{script === 'test' && (
<>
{details.match(/(\d+) passing/) && (
<span className="text-green-600 dark:text-green-400">
{details.match(/(\d+) passing/)?.[1]} passing
</span>
)}
{details.match(/(\d+) failing/) && (
<span className="text-red-600 dark:text-red-400">
{details.match(/(\d+) failing/)?.[1]} failing
</span>
)}
</>
)}
</div>
)}
</CardContent>
)}
</Card>
);
}
+217
View File
@@ -0,0 +1,217 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Terminal, CheckCircle, XCircle, Play } from 'lucide-react';
import { cn } from '@/lib/utils';
interface ShellCommandProps {
command: string;
result?: string;
isError?: boolean;
className?: string;
}
export function ShellCommand({ command, result, isError = false, className }: ShellCommandProps) {
// Parse command to get useful information
const parseCommand = (cmd: string) => {
const parts = cmd.trim().split(' ');
const baseCommand = parts[0];
// Get command info
const getCommandInfo = (baseCmd: string) => {
switch (baseCmd) {
case 'ls':
case 'dir': return { icon: '📁', description: 'List directory contents' };
case 'cd': return { icon: '📂', description: 'Change directory' };
case 'mkdir': return { icon: '📁', description: 'Create directory' };
case 'rm':
case 'rmdir':
case 'del': return { icon: '🗑️', description: 'Remove files/directories' };
case 'cp':
case 'copy': return { icon: '📋', description: 'Copy files' };
case 'mv':
case 'move': return { icon: '📦', description: 'Move/rename files' };
case 'cat':
case 'type': return { icon: '📄', description: 'Display file contents' };
case 'grep':
case 'findstr': return { icon: '🔍', description: 'Search text patterns' };
case 'find': return { icon: '🔍', description: 'Find files and directories' };
case 'chmod': return { icon: '🔐', description: 'Change file permissions' };
case 'git': return { icon: '🌿', description: 'Git version control' };
case 'npm':
case 'yarn':
case 'pnpm': return { icon: '📦', description: 'Package manager' };
case 'node': return { icon: '🟢', description: 'Run Node.js' };
case 'python':
case 'python3': return { icon: '🐍', description: 'Run Python' };
case 'curl':
case 'wget': return { icon: '🌐', description: 'Download from web' };
case 'ps': return { icon: '⚙️', description: 'List running processes' };
case 'kill': return { icon: '⚡', description: 'Terminate processes' };
case 'echo': return { icon: '💬', description: 'Display text' };
case 'pwd': return { icon: '📍', description: 'Show current directory' };
case 'whoami': return { icon: '👤', description: 'Show current user' };
case 'which':
case 'where': return { icon: '🔍', description: 'Locate command' };
default: return { icon: '⚡', description: 'Execute command' };
}
};
return {
baseCommand,
fullCommand: cmd,
...getCommandInfo(baseCommand)
};
};
const commandInfo = parseCommand(command);
// Parse output for useful information
const parseOutput = (output: string) => {
if (!output) return { summary: '', details: output };
const lines = output.split('\n').filter(line => line.trim());
// Look for common patterns
if (commandInfo.baseCommand === 'ls' || commandInfo.baseCommand === 'dir') {
const fileCount = lines.length;
return {
summary: `Found ${fileCount} item${fileCount !== 1 ? 's' : ''}`,
details: output
};
}
if (commandInfo.baseCommand === 'git') {
const gitSubcommand = command.split(' ')[1];
if (gitSubcommand === 'status') {
return {
summary: lines.find(line => line.includes('nothing to commit') || line.includes('Changes') || line.includes('Untracked')) || 'Git status checked',
details: output
};
}
if (gitSubcommand === 'log') {
const commitCount = (output.match(/commit /g) || []).length;
return {
summary: `Showing ${commitCount} commit${commitCount !== 1 ? 's' : ''}`,
details: output
};
}
}
if (commandInfo.baseCommand === 'npm' || commandInfo.baseCommand === 'yarn') {
if (output.includes('added') || output.includes('installed')) {
return {
summary: 'Package installation completed',
details: output
};
}
}
// Default: use first meaningful line or last line
const meaningfulLines = lines.filter(line =>
!line.startsWith('#') &&
!line.startsWith('//') &&
line.length > 0
);
return {
summary: meaningfulLines[meaningfulLines.length - 1] || 'Command executed',
details: output
};
};
const { summary, details } = parseOutput(result || '');
return (
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<Terminal className="h-4 w-4 text-muted-foreground" />
<span className="text-lg">{commandInfo.icon}</span>
</div>
<div>
<div className="font-mono text-sm font-medium">$ {commandInfo.fullCommand}</div>
<div className="text-xs text-muted-foreground">{commandInfo.description}</div>
</div>
</div>
<div className="flex items-center gap-2">
{result !== undefined ? (
isError ? (
<Badge variant="destructive" className="text-xs">
<XCircle className="h-3 w-3 mr-1" />
Failed
</Badge>
) : (
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
<CheckCircle className="h-3 w-3 mr-1" />
Success
</Badge>
)
) : (
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
<Play className="h-3 w-3 mr-1" />
Running
</Badge>
)}
</div>
</div>
</CardHeader>
{result && (
<CardContent className="pt-0">
{/* Summary */}
{summary && (
<div className={cn(
"mb-3 p-3 rounded-md text-sm font-medium",
isError
? "bg-destructive/10 text-destructive border border-destructive/20"
: "bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-400 border border-green-200 dark:border-green-800/30"
)}>
{summary}
</div>
)}
{/* Full output */}
{details && details.trim() && (
<details className="group">
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
<span className="group-open:rotate-90 transition-transform">▶</span>
View command output
</summary>
<div className="bg-muted/30 rounded-md overflow-hidden">
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50">
Terminal Output
</div>
<div className="p-3 max-h-80 overflow-auto">
<pre className="text-xs font-mono whitespace-pre text-muted-foreground">
{details}
</pre>
</div>
</div>
</details>
)}
{/* Command stats */}
{!isError && details && (
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
<span>
{details.split('\n').length} line{details.split('\n').length !== 1 ? 's' : ''} output
</span>
{commandInfo.baseCommand === 'ls' && (
<span>
{details.split('\n').filter(line => line.trim()).length} items listed
</span>
)}
{(commandInfo.baseCommand === 'git' && command.includes('log')) && (
<span>
{(details.match(/commit /g) || []).length} commits shown
</span>
)}
</div>
)}
</CardContent>
)}
</Card>
);
}
+72
View File
@@ -0,0 +1,72 @@
import { memo } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { CheckCircle, XCircle, Wrench } from 'lucide-react';
import type { CoreToolMessage } from 'ai';
interface ToolResultContentProps {
content: CoreToolMessage['content'];
}
export const ToolResultContent = memo(({ content }: ToolResultContentProps) => {
if (typeof content === 'string') {
return (
<Card className="mt-2 bg-muted/50">
<CardContent className="p-3">
<div className="flex items-center gap-2 mb-2">
<Wrench className="h-4 w-4 flex-shrink-0" />
<span className="font-mono text-sm">Tool Result</span>
</div>
<div className="text-xs rounded p-2 border bg-background">
<pre className="whitespace-pre-wrap break-words overflow-x-auto">{content}</pre>
</div>
</CardContent>
</Card>
);
}
return (
<>
{content.map((item, index) => {
if (item.type === 'tool-result') {
const isError = item.isError || false;
const result = typeof item.result === 'string' ? item.result : JSON.stringify(item.result);
return (
<Card key={index} className="mt-2 bg-muted/50">
<CardContent className="p-3">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
<Wrench className="h-4 w-4 flex-shrink-0" />
<span className="font-mono text-sm">{item.toolName}</span>
</div>
<Badge variant={isError ? "destructive" : "secondary"} className="text-xs">
{isError ? (
<>
<XCircle className="h-3 w-3 mr-1" />
Error
</>
) : (
<>
<CheckCircle className="h-3 w-3 mr-1" />
Success
</>
)}
</Badge>
</div>
<div className={`text-xs rounded p-2 border max-h-40 overflow-scroll ${
isError ? 'bg-destructive/10 border-destructive/20' : 'bg-background'
}`}>
<pre className="whitespace-pre-wrap break-words overflow-x-auto">{result}</pre>
</div>
</CardContent>
</Card>
);
}
return null;
})}
</>
);
});
ToolResultContent.displayName = 'ToolResultContent';
+1 -1
View File
@@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom';
import { type Project } from '@/lib/ProjectsManager';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { ProjectSidebar } from '@/components/ProjectSidebar';
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';