mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Rip out the streaming chat code
This commit is contained in:
19 files changed
+212
-2551
No files matched your search
Generated
+46
-10
@@ -48,7 +48,7 @@
|
||||
"@unhead/addons": "^2.0.10",
|
||||
"@unhead/react": "^2.0.10",
|
||||
"@webcontainer/api": "^1.6.1",
|
||||
"ai": "^5.0.19",
|
||||
"ai": "^5.0.22",
|
||||
"buffer": "^6.0.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
@@ -118,13 +118,31 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@ai-sdk/gateway": {
|
||||
"version": "1.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-1.0.9.tgz",
|
||||
"integrity": "sha512-kIfwunyUUwyBLg2KQcaRtjRQ1bDuJYPNIs4CNWaWPpMZ4SV5cRL1hLGMuX4bhfCJYDXHMGvJGLtUK6+iAJH2ZQ==",
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-1.0.11.tgz",
|
||||
"integrity": "sha512-ErwWS3sPOuWy42eE3AVxlKkTa1XjjKBEtNCOylVKMO5KNyz5qie8QVlLYbULOG56dtxX4zTKX3rQNJudplhcmQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@ai-sdk/provider": "2.0.0",
|
||||
"@ai-sdk/provider-utils": "3.0.4"
|
||||
"@ai-sdk/provider-utils": "3.0.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"zod": "^3.25.76 || ^4"
|
||||
}
|
||||
},
|
||||
"node_modules/@ai-sdk/gateway/node_modules/@ai-sdk/provider-utils": {
|
||||
"version": "3.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-3.0.5.tgz",
|
||||
"integrity": "sha512-HliwB/yzufw3iwczbFVE2Fiwf1XqROB/I6ng8EKUsPM5+2wnIa8f4VbljZcDx+grhFrPV+PnRZH7zBqi8WZM7Q==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@ai-sdk/provider": "2.0.0",
|
||||
"@standard-schema/spec": "^1.0.0",
|
||||
"eventsource-parser": "^3.0.3",
|
||||
"zod-to-json-schema": "^3.24.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
@@ -4356,14 +4374,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/ai": {
|
||||
"version": "5.0.19",
|
||||
"resolved": "https://registry.npmjs.org/ai/-/ai-5.0.19.tgz",
|
||||
"integrity": "sha512-I0yQO68Z1DdvjMc9be5scMYdsuBvpNneQDh6TUuUVlFXdCxAIm7yATnOaomfYTE2KaRDsrO+OSRPjJm4FSKioA==",
|
||||
"version": "5.0.22",
|
||||
"resolved": "https://registry.npmjs.org/ai/-/ai-5.0.22.tgz",
|
||||
"integrity": "sha512-RZiYhj7Ux7hrLtXkHPcxzdiSZt4NOiC69O5AkNfMCsz3twwz/KRkl9ASptosoOsg833s5yRcTSdIu5z53Sl6Pw==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@ai-sdk/gateway": "1.0.9",
|
||||
"@ai-sdk/gateway": "1.0.11",
|
||||
"@ai-sdk/provider": "2.0.0",
|
||||
"@ai-sdk/provider-utils": "3.0.4",
|
||||
"@ai-sdk/provider-utils": "3.0.5",
|
||||
"@opentelemetry/api": "1.9.0"
|
||||
},
|
||||
"engines": {
|
||||
@@ -4373,6 +4391,24 @@
|
||||
"zod": "^3.25.76 || ^4"
|
||||
}
|
||||
},
|
||||
"node_modules/ai/node_modules/@ai-sdk/provider-utils": {
|
||||
"version": "3.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-3.0.5.tgz",
|
||||
"integrity": "sha512-HliwB/yzufw3iwczbFVE2Fiwf1XqROB/I6ng8EKUsPM5+2wnIa8f4VbljZcDx+grhFrPV+PnRZH7zBqi8WZM7Q==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@ai-sdk/provider": "2.0.0",
|
||||
"@standard-schema/spec": "^1.0.0",
|
||||
"eventsource-parser": "^3.0.3",
|
||||
"zod-to-json-schema": "^3.24.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"zod": "^3.25.76 || ^4"
|
||||
}
|
||||
},
|
||||
"node_modules/ajv": {
|
||||
"version": "6.12.6",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@
|
||||
"@unhead/addons": "^2.0.10",
|
||||
"@unhead/react": "^2.0.10",
|
||||
"@webcontainer/api": "^1.6.1",
|
||||
"ai": "^5.0.19",
|
||||
"ai": "^5.0.22",
|
||||
"buffer": "^6.0.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
|
||||
@@ -2,29 +2,23 @@ import { memo } from 'react';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Bot, User, Square } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ChatMessage } from '@/hooks/useStreamingChat';
|
||||
import { AssistantContent } from '@/components/ai/AssistantContent';
|
||||
import { AIMessage } from '@/hooks/useAIChat';
|
||||
|
||||
interface StreamingMessageItemProps {
|
||||
message: ChatMessage;
|
||||
interface AIMessageItemProps {
|
||||
message: AIMessage;
|
||||
userDisplayName?: string;
|
||||
userProfileImage?: string;
|
||||
isCurrentlyStreaming?: boolean;
|
||||
onStopStreaming?: () => void;
|
||||
isCurrentlyLoading?: boolean;
|
||||
onStopGeneration?: () => void;
|
||||
}
|
||||
|
||||
export const StreamingMessageItem = memo(({
|
||||
export const AIMessageItem = memo(({
|
||||
message,
|
||||
userDisplayName = 'You',
|
||||
userProfileImage,
|
||||
isCurrentlyStreaming = false,
|
||||
onStopStreaming
|
||||
}: StreamingMessageItemProps) => {
|
||||
// Don't render tool messages as separate items - they're integrated into assistant messages
|
||||
if (message.role === 'tool') {
|
||||
return null;
|
||||
}
|
||||
|
||||
isCurrentlyLoading = false,
|
||||
onStopGeneration
|
||||
}: AIMessageItemProps) => {
|
||||
return (
|
||||
<div className="flex gap-3">
|
||||
<Avatar className="h-8 w-8 flex-shrink-0">
|
||||
@@ -51,11 +45,11 @@ export const StreamingMessageItem = memo(({
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{message.role === 'user' ? 'User' : message.role === 'assistant' ? 'AI' : 'System'}
|
||||
</span>
|
||||
{isCurrentlyStreaming && onStopStreaming && (
|
||||
{isCurrentlyLoading && onStopGeneration && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onStopStreaming}
|
||||
onClick={onStopGeneration}
|
||||
className="ml-auto gap-1 h-6 px-2 text-xs"
|
||||
>
|
||||
<Square className="h-3 w-3" />
|
||||
@@ -64,24 +58,13 @@ export const StreamingMessageItem = memo(({
|
||||
)}
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
{message.role === 'user' ? (
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
{typeof message.content === 'string' ? message.content :
|
||||
Array.isArray(message.content) ?
|
||||
message.content.map(part => part.type === 'text' ? part.text : '').join('') :
|
||||
''}
|
||||
</div>
|
||||
) : message.role === 'assistant' ? (
|
||||
<AssistantContent content={message.content} />
|
||||
) : message.role === 'system' ? (
|
||||
<div className="whitespace-pre-wrap break-words text-muted-foreground">
|
||||
{typeof message.content === 'string' ? message.content : ''}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
{message.content}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
StreamingMessageItem.displayName = 'StreamingMessageItem';
|
||||
AIMessageItem.displayName = 'AIMessageItem';
|
||||
@@ -6,11 +6,11 @@ import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useJSRuntime } from '@/hooks/useJSRuntime';
|
||||
import { useKeepAlive } from '@/hooks/useKeepAlive';
|
||||
import { useStreamingChat } from '@/hooks/useStreamingChat';
|
||||
import { useAIChat } from '@/hooks/useAIChat';
|
||||
import { copyDirectory } from '@/lib/copyFiles';
|
||||
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
|
||||
import { bytesToHex } from 'nostr-tools/utils';
|
||||
import { StreamingMessageItem } from '@/components/ai/StreamingMessageItem';
|
||||
import { AIMessageItem } from '@/components/AIMessageItem';
|
||||
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
|
||||
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
|
||||
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
|
||||
@@ -34,7 +34,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
|
||||
const { fs: browserFS } = useFS();
|
||||
const { runtime } = useJSRuntime();
|
||||
|
||||
// Initialize streaming chat with tools
|
||||
// Initialize AI chat with tools
|
||||
const cwd = `/projects/${projectId}`;
|
||||
const tools = {
|
||||
git_commit: new GitCommitTool(browserFS, cwd),
|
||||
@@ -77,11 +77,10 @@ When creating new components or pages, follow the existing patterns in the codeb
|
||||
|
||||
const {
|
||||
messages,
|
||||
isStreaming,
|
||||
currentStreamingMessageId,
|
||||
isLoading,
|
||||
sendMessage,
|
||||
stopStreaming,
|
||||
} = useStreamingChat({
|
||||
stopGeneration,
|
||||
} = useAIChat({
|
||||
projectId,
|
||||
projectName,
|
||||
tools,
|
||||
@@ -93,7 +92,7 @@ When creating new components or pages, follow the existing patterns in the codeb
|
||||
|
||||
// Keep-alive functionality to prevent tab throttling during AI processing
|
||||
const { updateMetadata } = useKeepAlive({
|
||||
enabled: isStreaming || isBuildLoading || isDeployLoading,
|
||||
enabled: isLoading || isBuildLoading || isDeployLoading,
|
||||
title: 'Shakespeare',
|
||||
artist: `Working on ${projectName}...`,
|
||||
artwork: [
|
||||
@@ -190,8 +189,6 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
}
|
||||
};
|
||||
|
||||
// Note: Message clearing and history loading is now handled in useStreamingChat hook
|
||||
|
||||
useEffect(() => {
|
||||
if (scrollAreaRef.current && messages) {
|
||||
// Check if user was already at or near the bottom (within 100px threshold)
|
||||
@@ -204,10 +201,10 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}
|
||||
}
|
||||
}, [messages, isStreaming]);
|
||||
}, [messages, isLoading]);
|
||||
|
||||
const handleSend = async () => {
|
||||
if (!input.trim() || isStreaming) return;
|
||||
if (!input.trim() || isLoading) return;
|
||||
|
||||
const messageContent = input;
|
||||
setInput('');
|
||||
@@ -216,7 +213,7 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
await sendMessage(messageContent);
|
||||
} catch (error) {
|
||||
console.error('AI chat error:', error);
|
||||
// Error handling is done in the useStreamingChat hook
|
||||
// Error handling is done in the useAIChat hook
|
||||
}
|
||||
};
|
||||
|
||||
@@ -300,7 +297,7 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
className="gap-1 sm:gap-2 hover:bg-primary/10 hover:border-primary/20"
|
||||
onClick={runBuild}
|
||||
onMouseDown={handleFirstInteraction}
|
||||
disabled={isBuildLoading || isDeployLoading || isStreaming}
|
||||
disabled={isBuildLoading || isDeployLoading || isLoading}
|
||||
>
|
||||
{isBuildLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
@@ -317,7 +314,7 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
className="gap-1 sm:gap-2 hover:bg-accent/10 hover:border-accent/20"
|
||||
onClick={runDeploy}
|
||||
onMouseDown={handleFirstInteraction}
|
||||
disabled={isDeployLoading || isBuildLoading || isStreaming}
|
||||
disabled={isDeployLoading || isBuildLoading || isLoading}
|
||||
>
|
||||
{isDeployLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
@@ -334,12 +331,12 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
<div className="flex-1 overflow-y-scroll overflow-x-hidden" ref={scrollAreaRef}>
|
||||
<div className="p-4 space-y-4">
|
||||
{messages.map((message) => (
|
||||
<StreamingMessageItem
|
||||
<AIMessageItem
|
||||
key={message.id}
|
||||
message={message}
|
||||
userDisplayName="You"
|
||||
isCurrentlyStreaming={isStreaming && message.id === currentStreamingMessageId}
|
||||
onStopStreaming={stopStreaming}
|
||||
isCurrentlyLoading={isLoading && message.role === 'assistant'}
|
||||
onStopGeneration={stopGeneration}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -354,12 +351,12 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
onFocus={handleFirstInteraction}
|
||||
placeholder="Ask me to add features, edit files, or build your project..."
|
||||
className="min-h-[60px] resize-none"
|
||||
disabled={isStreaming}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
onMouseDown={handleFirstInteraction}
|
||||
disabled={!input.trim() || isStreaming}
|
||||
disabled={!input.trim() || isLoading}
|
||||
className="self-end"
|
||||
size="icon"
|
||||
>
|
||||
|
||||
@@ -1,258 +0,0 @@
|
||||
import { memo } from 'react';
|
||||
import { Code } from 'lucide-react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Response } from '@/components/ai-elements/response';
|
||||
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 { GitCommit } from '@/components/ai/GitCommit';
|
||||
import type { AssistantModelMessage } from 'ai';
|
||||
|
||||
interface AssistantContentProps {
|
||||
content: AssistantModelMessage['content'];
|
||||
}
|
||||
|
||||
export const AssistantContent = memo(({ content }: AssistantContentProps) => {
|
||||
// Helper function to find tool result by call ID
|
||||
const findToolResult = (toolCallId: string) => {
|
||||
if (Array.isArray(content)) {
|
||||
for (const part of content) {
|
||||
if (part.type === 'tool-result' && part.toolCallId === toolCallId) {
|
||||
return part;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// Helper function to extract result text and error status
|
||||
const extractToolResult = (toolCallId: string): { result?: string; isError: boolean } => {
|
||||
const toolResult = findToolResult(toolCallId);
|
||||
|
||||
if (!toolResult) {
|
||||
return { isError: false };
|
||||
}
|
||||
|
||||
// Handle direct string results
|
||||
if (toolResult.output.type === 'text') {
|
||||
return {
|
||||
result: toolResult.output.value,
|
||||
isError: false
|
||||
};
|
||||
}
|
||||
|
||||
return { isError: true };
|
||||
};
|
||||
// Handle string content (simple text messages)
|
||||
if (typeof content === 'string') {
|
||||
return (
|
||||
<div className="prose prose-sm max-w-none dark:prose-invert">
|
||||
<Response>{content}</Response>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{content.map((item, index) => {
|
||||
if (item.type === 'text') {
|
||||
return (
|
||||
<div key={index} className="prose prose-sm max-w-none dark:prose-invert">
|
||||
<Response>{item.text}</Response>
|
||||
</div>
|
||||
);
|
||||
} else if (item.type === 'tool-call') {
|
||||
// Special rendering for text_editor_str_replace tool
|
||||
if (item.toolName === 'text_editor_str_replace' && item.input) {
|
||||
const { path, old_str, new_str } = item.input as { path: string; old_str: string; new_str: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<DiffRenderer
|
||||
key={index}
|
||||
path={path}
|
||||
oldStr={old_str}
|
||||
newStr={new_str}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for run_script tool
|
||||
if (item.toolName === 'run_script' && item.input) {
|
||||
const { script } = item.input as { script: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<ScriptRunner
|
||||
key={index}
|
||||
script={script}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for text_editor_view tool
|
||||
if (item.toolName === 'text_editor_view' && item.input) {
|
||||
const { path } = item.input as { path: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<FileViewer
|
||||
key={index}
|
||||
path={path}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for text_editor_write tool
|
||||
if (item.toolName === 'text_editor_write' && item.input) {
|
||||
const { path, file_text } = item.input as { path: string; file_text: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<FileWriter
|
||||
key={index}
|
||||
path={path}
|
||||
fileText={file_text}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for shell tool
|
||||
if (item.toolName === 'shell' && item.input) {
|
||||
const { command } = item.input as { command: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<ShellCommand
|
||||
key={index}
|
||||
command={command}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for npm_add_package tool
|
||||
if (item.toolName === 'npm_add_package' && item.input) {
|
||||
const { name, version, dev } = item.input as { name: string; version?: string; dev?: boolean };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<PackageManager
|
||||
key={index}
|
||||
action="add"
|
||||
registry="npm"
|
||||
packageName={name}
|
||||
version={version}
|
||||
dev={dev}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for npm_remove_package tool
|
||||
if (item.toolName === 'npm_remove_package' && item.input) {
|
||||
const { name } = item.input as { name: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<PackageManager
|
||||
key={index}
|
||||
action="remove"
|
||||
registry="npm"
|
||||
packageName={name}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for jsr_add_package tool
|
||||
if (item.toolName === 'jsr_add_package' && item.input) {
|
||||
const { name, version, dev } = item.input as { name: string; version?: string; dev?: boolean };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<PackageManager
|
||||
key={index}
|
||||
action="add"
|
||||
registry="jsr"
|
||||
packageName={name}
|
||||
version={version}
|
||||
dev={dev}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for jsr_remove_package tool
|
||||
if (item.toolName === 'jsr_remove_package' && item.input) {
|
||||
const { name } = item.input as { name: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<PackageManager
|
||||
key={index}
|
||||
action="remove"
|
||||
registry="jsr"
|
||||
packageName={name}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for git_commit tool
|
||||
if (item.toolName === 'git_commit' && item.input) {
|
||||
const { message } = item.input as { message: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<GitCommit
|
||||
key={index}
|
||||
message={message}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// 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.input && typeof item.input === 'object' && item.input !== null && Object.keys(item.input).length > 0 ? (
|
||||
<div className="text-xs text-muted-foreground mb-2">
|
||||
<pre className="overflow-hidden text-ellipsis">
|
||||
{JSON.stringify(item.input, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
AssistantContent.displayName = 'AssistantContent';
|
||||
@@ -1,164 +0,0 @@
|
||||
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;
|
||||
result?: string;
|
||||
isError?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function DiffRenderer({ path, oldStr, newStr, result, 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>
|
||||
|
||||
{/* Tool Result */}
|
||||
{result && (
|
||||
<div className={cn(
|
||||
"mt-3 p-3 rounded-md text-sm",
|
||||
isError
|
||||
? "bg-destructive/10 text-destructive border border-destructive/20"
|
||||
: "bg-muted/30 text-muted-foreground"
|
||||
)}>
|
||||
<pre className="whitespace-pre-wrap break-words">{result}</pre>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,208 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
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.output.type === 'error-text' || item.output.type === 'error-json';
|
||||
const result = item.output.type === 'content'
|
||||
? item.output.value
|
||||
.map((part) => part.type === 'text' ? part.text : undefined)
|
||||
.filter(Boolean)
|
||||
.join('\n')
|
||||
: JSON.stringify(item.output);
|
||||
|
||||
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';
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useState, useCallback, useRef } from 'react';
|
||||
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
|
||||
import { generateText, Tool } from 'ai';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
|
||||
export interface AIMessage {
|
||||
id: string;
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
interface UseAIChatOptions {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
tools?: Record<string, Tool>;
|
||||
systemPrompt?: string;
|
||||
onUpdateMetadata?: (title: string, description: string) => void;
|
||||
}
|
||||
|
||||
export function useAIChat({
|
||||
projectId: _projectId,
|
||||
projectName,
|
||||
tools = {},
|
||||
systemPrompt,
|
||||
onUpdateMetadata
|
||||
}: UseAIChatOptions) {
|
||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const abortControllerRef = useRef<AbortController | null>(null);
|
||||
const { settings, isConfigured } = useAISettings();
|
||||
|
||||
const addMessage = useCallback((message: AIMessage) => {
|
||||
setMessages(prev => [...prev, message]);
|
||||
}, []);
|
||||
|
||||
const sendMessage = useCallback(async (content: string) => {
|
||||
if (!isConfigured || isLoading) return;
|
||||
|
||||
// Add user message
|
||||
const userMessage: AIMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
role: 'user',
|
||||
content,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
|
||||
addMessage(userMessage);
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Create abort controller for this request
|
||||
abortControllerRef.current = new AbortController();
|
||||
|
||||
// Get all messages including the new user message
|
||||
const allMessages = [...messages, userMessage];
|
||||
const modelMessages = allMessages.map(msg => ({
|
||||
role: msg.role,
|
||||
content: msg.content
|
||||
}));
|
||||
|
||||
// Initialize OpenAI provider
|
||||
const openai = createOpenAICompatible({
|
||||
name: 'custom',
|
||||
baseURL: settings.baseUrl,
|
||||
apiKey: settings.apiKey,
|
||||
});
|
||||
|
||||
const provider = openai(settings.model);
|
||||
|
||||
// Update metadata
|
||||
if (onUpdateMetadata) {
|
||||
onUpdateMetadata('Shakespeare', `Working on ${projectName}...`);
|
||||
}
|
||||
|
||||
// Generate response
|
||||
const result = await generateText({
|
||||
model: provider,
|
||||
messages: modelMessages,
|
||||
tools,
|
||||
system: systemPrompt,
|
||||
abortSignal: abortControllerRef.current.signal,
|
||||
});
|
||||
|
||||
// Add assistant message
|
||||
const assistantMessage: AIMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
role: 'assistant',
|
||||
content: result.text,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
|
||||
addMessage(assistantMessage);
|
||||
|
||||
} catch (error) {
|
||||
console.error('AI chat error:', error);
|
||||
|
||||
// Add error message
|
||||
const errorMessage: AIMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
role: 'assistant',
|
||||
content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.',
|
||||
timestamp: Date.now()
|
||||
};
|
||||
|
||||
addMessage(errorMessage);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
abortControllerRef.current = null;
|
||||
}
|
||||
}, [isConfigured, isLoading, addMessage, messages, settings.baseUrl, settings.apiKey, settings.model, tools, systemPrompt, onUpdateMetadata, projectName]);
|
||||
|
||||
const stopGeneration = useCallback(() => {
|
||||
if (abortControllerRef.current) {
|
||||
abortControllerRef.current.abort();
|
||||
}
|
||||
}, []);
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
setMessages([]);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
messages,
|
||||
isLoading,
|
||||
sendMessage,
|
||||
stopGeneration,
|
||||
clearMessages,
|
||||
addMessage,
|
||||
isConfigured
|
||||
};
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
// Test the streaming message history saving behavior
|
||||
describe('useStreamingChat history saving fix', () => {
|
||||
it('should only save completed messages to history', () => {
|
||||
// Test the logic for when messages should be saved to history
|
||||
const testCases = [
|
||||
{
|
||||
message: {
|
||||
role: 'user' as const,
|
||||
content: 'Hello AI',
|
||||
isStreaming: false,
|
||||
},
|
||||
shouldSave: true,
|
||||
description: 'completed user message'
|
||||
},
|
||||
{
|
||||
message: {
|
||||
role: 'assistant' as const,
|
||||
content: 'Hello user',
|
||||
isStreaming: false,
|
||||
},
|
||||
shouldSave: true,
|
||||
description: 'completed assistant message'
|
||||
},
|
||||
{
|
||||
message: {
|
||||
role: 'assistant' as const,
|
||||
content: '',
|
||||
isStreaming: true,
|
||||
},
|
||||
shouldSave: false,
|
||||
description: 'streaming assistant message (empty)'
|
||||
},
|
||||
{
|
||||
message: {
|
||||
role: 'assistant' as const,
|
||||
content: 'Partial response...',
|
||||
isStreaming: true,
|
||||
},
|
||||
shouldSave: false,
|
||||
description: 'streaming assistant message (with content)'
|
||||
},
|
||||
];
|
||||
|
||||
testCases.forEach(({ message, shouldSave }) => {
|
||||
// This is the logic from the addMessage function
|
||||
const willSave = !message.isStreaming;
|
||||
expect(willSave).toBe(shouldSave);
|
||||
});
|
||||
});
|
||||
|
||||
it('should save messages when streaming stops', () => {
|
||||
// Test the logic for when streaming messages get saved
|
||||
const testCases = [
|
||||
{
|
||||
previousMessage: {
|
||||
role: 'assistant' as const,
|
||||
content: 'Hello world',
|
||||
isStreaming: true,
|
||||
},
|
||||
update: {
|
||||
isStreaming: false,
|
||||
},
|
||||
shouldSave: true,
|
||||
description: 'streaming stops'
|
||||
},
|
||||
{
|
||||
previousMessage: {
|
||||
role: 'assistant' as const,
|
||||
content: 'Hello',
|
||||
isStreaming: true,
|
||||
},
|
||||
update: {
|
||||
content: 'Hello world',
|
||||
isStreaming: true,
|
||||
},
|
||||
shouldSave: false,
|
||||
description: 'content update but still streaming'
|
||||
},
|
||||
{
|
||||
previousMessage: {
|
||||
role: 'assistant' as const,
|
||||
content: 'Hello',
|
||||
isStreaming: false,
|
||||
},
|
||||
update: {
|
||||
content: 'Hello world',
|
||||
},
|
||||
shouldSave: false,
|
||||
description: 'update to already completed message'
|
||||
},
|
||||
];
|
||||
|
||||
testCases.forEach(({ previousMessage, update, shouldSave }) => {
|
||||
// This is the logic from the updateMessage function
|
||||
const willSave = update.isStreaming === false && previousMessage.isStreaming === true;
|
||||
expect(willSave).toBe(shouldSave);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,403 +0,0 @@
|
||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
|
||||
import { streamText, ModelMessage, generateId, Tool, stepCountIs } from 'ai';
|
||||
import type { TextPart, ToolCallPart, ToolResultPart } from 'ai';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { AIMessage, DotAI } from '@/lib/DotAI';
|
||||
|
||||
// Extend ModelMessage with additional UI state
|
||||
export type ChatMessage = ModelMessage & {
|
||||
id: string;
|
||||
isStreaming?: boolean;
|
||||
timestamp?: number;
|
||||
}
|
||||
|
||||
interface UseStreamingChatOptions {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
tools?: Record<string, Tool>;
|
||||
systemPrompt?: string;
|
||||
onStepFinish?: (stepResult: unknown) => void;
|
||||
onUpdateMetadata?: (title: string, description: string) => void;
|
||||
}
|
||||
|
||||
export function useStreamingChat({
|
||||
projectId,
|
||||
projectName,
|
||||
tools = {},
|
||||
systemPrompt,
|
||||
onStepFinish,
|
||||
onUpdateMetadata
|
||||
}: UseStreamingChatOptions) {
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [isStreaming, setIsStreaming] = useState(false);
|
||||
const [currentStreamingMessageId, setCurrentStreamingMessageId] = useState<string | null>(null);
|
||||
const [sessionName, setSessionName] = useState<string>(DotAI.generateSessionName());
|
||||
const [loadedProjectId, setLoadedProjectId] = useState<string | null>(null);
|
||||
const abortControllerRef = useRef<AbortController | null>(null);
|
||||
const { settings, isConfigured } = useAISettings();
|
||||
const { fs } = useFS();
|
||||
const dotAIRef = useRef<DotAI | null>(null);
|
||||
|
||||
// Initialize DotAI for this project
|
||||
useEffect(() => {
|
||||
const initializeDotAI = async () => {
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `/projects/${projectId}`);
|
||||
dotAIRef.current = dotAI;
|
||||
|
||||
// Generate session name if not already set
|
||||
if (!sessionName) {
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to initialize DotAI:', error);
|
||||
}
|
||||
};
|
||||
|
||||
initializeDotAI();
|
||||
}, [fs, projectId, sessionName]);
|
||||
|
||||
// Load message history when project changes
|
||||
useEffect(() => {
|
||||
const loadMessageHistory = async () => {
|
||||
// Only load if we haven't loaded this project yet or if the project has changed
|
||||
if (!dotAIRef.current || loadedProjectId === projectId) return;
|
||||
|
||||
// Clear messages when switching to a new project
|
||||
setMessages([]);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
|
||||
try {
|
||||
const historyDir = `/projects/${projectId}/.ai/history`;
|
||||
|
||||
// Check if history directory exists
|
||||
try {
|
||||
await fs.stat(historyDir);
|
||||
} catch {
|
||||
// History directory doesn't exist, no history to load
|
||||
setLoadedProjectId(projectId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get all session files
|
||||
const files = await fs.readdir(historyDir);
|
||||
const sessionFiles = files.filter(file => file.endsWith('.jsonl'));
|
||||
|
||||
if (sessionFiles.length === 0) {
|
||||
setLoadedProjectId(projectId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Sort by filename (which includes timestamp) to get the latest session
|
||||
sessionFiles.sort();
|
||||
const latestSessionFile = sessionFiles[sessionFiles.length - 1];
|
||||
const latestSessionName = latestSessionFile.replace('.jsonl', '');
|
||||
|
||||
// Load messages from the latest session
|
||||
const sessionPath = `${historyDir}/${latestSessionFile}`;
|
||||
const sessionContent = await fs.readFile(sessionPath, 'utf8');
|
||||
|
||||
const loadedMessages: ChatMessage[] = [];
|
||||
const lines = sessionContent.split('\n').filter(line => line.trim());
|
||||
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const messageData = JSON.parse(line);
|
||||
// Convert to ChatMessage format
|
||||
const chatMessage: ChatMessage = {
|
||||
id: generateId(),
|
||||
role: messageData.role,
|
||||
content: messageData.content,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
loadedMessages.push(chatMessage);
|
||||
} catch (error) {
|
||||
console.warn('Failed to parse message from history:', error);
|
||||
}
|
||||
}
|
||||
|
||||
if (loadedMessages.length > 0) {
|
||||
setMessages(loadedMessages);
|
||||
setSessionName(latestSessionName);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load message history:', error);
|
||||
} finally {
|
||||
setLoadedProjectId(projectId);
|
||||
}
|
||||
};
|
||||
|
||||
loadMessageHistory();
|
||||
}, [fs, projectId, loadedProjectId]);
|
||||
|
||||
// Save message to history
|
||||
const saveMessageToHistory = useCallback(async (message: AIMessage) => {
|
||||
if (!dotAIRef.current || !sessionName) {
|
||||
console.error("Unable to save message to history:", {
|
||||
dotAIRef,
|
||||
sessionName,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Convert ChatMessage to DotAI format
|
||||
const aiMessage = {
|
||||
role: message.role,
|
||||
content: message.content
|
||||
};
|
||||
|
||||
await dotAIRef.current.addToHistory(sessionName, aiMessage);
|
||||
} catch (error) {
|
||||
console.warn('Failed to save message to history:', error);
|
||||
}
|
||||
}, [sessionName]);
|
||||
|
||||
// Convert ChatMessage to ModelMessage for AI SDK
|
||||
const convertToModelMessages = useCallback((chatMessages: ChatMessage[]): ModelMessage[] => {
|
||||
return chatMessages.map(({ id, isStreaming, timestamp, ...modelMessage }) => modelMessage as ModelMessage);
|
||||
}, []);
|
||||
|
||||
const addMessage = useCallback((message: ChatMessage) => {
|
||||
setMessages(prev => {
|
||||
const messageMap = new Map(prev.map(m => [m.id, m]));
|
||||
messageMap.set(message.id, message);
|
||||
return Array.from(messageMap.values());
|
||||
});
|
||||
}, []);
|
||||
|
||||
const updateMessage = useCallback((id: string, updates: Partial<ChatMessage> | ((prev: ChatMessage) => Partial<ChatMessage>)) => {
|
||||
setMessages(prev => prev.map(msg => {
|
||||
if (msg.id === id) {
|
||||
const updatesObj = typeof updates === 'function' ? updates(msg) : updates;
|
||||
const updatedMessage = { ...msg, ...updatesObj } as ChatMessage;
|
||||
return updatedMessage;
|
||||
}
|
||||
return msg;
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const sendMessage = useCallback(async (content: string) => {
|
||||
if (!isConfigured || isStreaming) return;
|
||||
|
||||
// Add user message
|
||||
const userMessage: ChatMessage = {
|
||||
id: generateId(),
|
||||
role: 'user',
|
||||
content,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
|
||||
addMessage(userMessage);
|
||||
await saveMessageToHistory(userMessage);
|
||||
setIsStreaming(true);
|
||||
|
||||
// Track current assistant message for this step
|
||||
let currentAssistantMessageId: string | null = null;
|
||||
|
||||
try {
|
||||
// Create abort controller for this request
|
||||
abortControllerRef.current = new AbortController();
|
||||
|
||||
// Get all messages including the new user message
|
||||
const allMessages = [...messages, userMessage];
|
||||
const modelMessages = convertToModelMessages(allMessages);
|
||||
|
||||
// Initialize OpenAI provider
|
||||
const openai = createOpenAICompatible({
|
||||
name: 'custom',
|
||||
baseURL: settings.baseUrl,
|
||||
apiKey: settings.apiKey,
|
||||
});
|
||||
|
||||
const provider = openai(settings.model);
|
||||
|
||||
// Start streaming
|
||||
const result = streamText({
|
||||
model: provider,
|
||||
messages: modelMessages,
|
||||
tools,
|
||||
system: systemPrompt,
|
||||
abortSignal: abortControllerRef.current.signal,
|
||||
stopWhen: stepCountIs(50),
|
||||
onStepFinish: async (stepResult) => {
|
||||
console.log('Step finished:', stepResult);
|
||||
|
||||
// Update metadata if callback provided
|
||||
if (onUpdateMetadata && stepResult.toolCalls && stepResult.toolCalls.length > 0) {
|
||||
const toolName = stepResult.toolCalls[0].toolName;
|
||||
onUpdateMetadata('Shakespeare', `Working on ${projectName} - ${toolName}`);
|
||||
}
|
||||
|
||||
// Save messages to history after step is finished
|
||||
if (stepResult.finishReason === 'stop') {
|
||||
for (const message of stepResult.response.messages) {
|
||||
await saveMessageToHistory(message);
|
||||
}
|
||||
}
|
||||
|
||||
// Call custom step finish handler
|
||||
if (onStepFinish) {
|
||||
onStepFinish(stepResult);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Stream the content step by step using fullStream
|
||||
for await (const chunk of result.fullStream) {
|
||||
if (abortControllerRef.current?.signal.aborted) {
|
||||
break;
|
||||
}
|
||||
|
||||
switch (chunk.type) {
|
||||
case 'text-delta': {
|
||||
// Create new assistant message if we don't have one for this step
|
||||
if (!currentAssistantMessageId) {
|
||||
currentAssistantMessageId = generateId();
|
||||
const assistantMessage: ChatMessage = {
|
||||
id: currentAssistantMessageId,
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
isStreaming: true,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
addMessage(assistantMessage);
|
||||
setCurrentStreamingMessageId(currentAssistantMessageId);
|
||||
}
|
||||
|
||||
// Update the current message with new text
|
||||
updateMessage(currentAssistantMessageId, (prev) => {
|
||||
const currentContent = prev.content;
|
||||
if (typeof currentContent === 'string') {
|
||||
return {
|
||||
content: currentContent + chunk.text,
|
||||
isStreaming: true
|
||||
};
|
||||
} else {
|
||||
// If content is an array, find the last text part or add a new one
|
||||
const content = Array.isArray(currentContent) ?
|
||||
currentContent.filter((part): part is TextPart | ToolCallPart | ToolResultPart =>
|
||||
part.type === 'text' || part.type === 'tool-call' || part.type === 'tool-result'
|
||||
) : [];
|
||||
const lastPart = content[content.length - 1];
|
||||
if (lastPart && lastPart.type === 'text') {
|
||||
lastPart.text += chunk.text;
|
||||
} else {
|
||||
content.push({ type: 'text' as const, text: chunk.text });
|
||||
}
|
||||
return {
|
||||
content,
|
||||
isStreaming: true
|
||||
};
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'tool-call': {
|
||||
// Create new assistant message if we don't have one for this step
|
||||
if (!currentAssistantMessageId) {
|
||||
currentAssistantMessageId = generateId();
|
||||
const assistantMessage: ChatMessage = {
|
||||
id: currentAssistantMessageId,
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
isStreaming: true,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
addMessage(assistantMessage);
|
||||
setCurrentStreamingMessageId(currentAssistantMessageId);
|
||||
}
|
||||
|
||||
// Add tool call to current message
|
||||
updateMessage(currentAssistantMessageId, (prev) => {
|
||||
const currentContent = prev.content;
|
||||
const content: Array<TextPart | ToolCallPart | ToolResultPart> = Array.isArray(currentContent) ?
|
||||
currentContent.filter((part): part is TextPart | ToolCallPart | ToolResultPart =>
|
||||
part.type === 'text' || part.type === 'tool-call' || part.type === 'tool-result'
|
||||
) :
|
||||
typeof currentContent === 'string' && currentContent ? [{ type: 'text' as const, text: currentContent }] : [];
|
||||
|
||||
content.push({
|
||||
type: 'tool-call' as const,
|
||||
toolCallId: chunk.toolCallId,
|
||||
toolName: chunk.toolName,
|
||||
input: chunk.input
|
||||
});
|
||||
|
||||
return { content };
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'finish-step': {
|
||||
// Finalize the last assistant message
|
||||
if (currentAssistantMessageId) {
|
||||
updateMessage(currentAssistantMessageId, {
|
||||
isStreaming: false
|
||||
});
|
||||
}
|
||||
|
||||
// Reset current assistant message ID for next step
|
||||
currentAssistantMessageId = null;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Streaming error:', error);
|
||||
|
||||
// Handle error - create or update assistant message with error content
|
||||
if (currentAssistantMessageId) {
|
||||
updateMessage(currentAssistantMessageId, {
|
||||
content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.',
|
||||
isStreaming: false
|
||||
});
|
||||
} else {
|
||||
// Create error message if no assistant message exists
|
||||
const errorMessageId = generateId();
|
||||
addMessage({
|
||||
id: errorMessageId,
|
||||
role: 'assistant',
|
||||
content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.',
|
||||
isStreaming: false,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
setIsStreaming(false);
|
||||
setCurrentStreamingMessageId(null);
|
||||
abortControllerRef.current = null;
|
||||
}
|
||||
}, [isConfigured, isStreaming, addMessage, saveMessageToHistory, messages, convertToModelMessages, settings.baseUrl, settings.apiKey, settings.model, tools, systemPrompt, onUpdateMetadata, onStepFinish, projectName, updateMessage]);
|
||||
|
||||
const stopStreaming = useCallback(() => {
|
||||
if (abortControllerRef.current) {
|
||||
abortControllerRef.current.abort();
|
||||
}
|
||||
}, []);
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
setMessages([]);
|
||||
// Start a new session when clearing messages
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
// Reset loaded project ID so history can be loaded again
|
||||
setLoadedProjectId(null);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
messages,
|
||||
isStreaming,
|
||||
currentStreamingMessageId,
|
||||
sendMessage,
|
||||
stopStreaming,
|
||||
clearMessages,
|
||||
addMessage,
|
||||
updateMessage,
|
||||
isConfigured
|
||||
};
|
||||
}
|
||||
@@ -1,280 +0,0 @@
|
||||
import { join } from "@std/path";
|
||||
import { JSRuntimeFS } from "./JSRuntime";
|
||||
|
||||
export interface AIMessage {
|
||||
role: string;
|
||||
content: string | { type: string }[];
|
||||
}
|
||||
|
||||
/** NodeFS interface for file system operations */
|
||||
export interface NodeFS {
|
||||
access(path: string): Promise<void>;
|
||||
readFile(path: string, encoding: "utf8"): Promise<string>;
|
||||
writeFile(path: string, data: string, encoding: "utf8"): Promise<void>;
|
||||
appendFile(path: string, data: string, encoding: "utf8"): Promise<void>;
|
||||
mkdir(path: string, options: { recursive: boolean }): Promise<unknown>;
|
||||
}
|
||||
|
||||
/** AI message history manager and .ai directory utilities */
|
||||
export class DotAI {
|
||||
private readonly fs: JSRuntimeFS;
|
||||
private readonly historyDir: string;
|
||||
private readonly workingDir: string;
|
||||
|
||||
constructor(fs: JSRuntimeFS, workingDir: string = process.cwd()) {
|
||||
this.fs = fs;
|
||||
this.workingDir = workingDir;
|
||||
this.historyDir = join(workingDir, ".ai", "history");
|
||||
}
|
||||
|
||||
/** Generate a unique session name based on the current date and time */
|
||||
static generateSessionName(): string {
|
||||
// Generate filename with date, time in milliseconds, and random value
|
||||
const now = new Date();
|
||||
const dateString = now.toISOString();
|
||||
|
||||
// Generate a random 3-character suffix to avoid collisions
|
||||
const randomSuffix = Math.random().toString(36).substring(2, 5);
|
||||
|
||||
// Format: YYYY-MM-DDTHH-MM-SSZ-suffix.jsonl
|
||||
const filename = `${
|
||||
dateString.replace(/:/g, "-").slice(0, dateString.indexOf("."))
|
||||
}Z-${randomSuffix}`;
|
||||
|
||||
return filename;
|
||||
}
|
||||
|
||||
/** Check if AI history should be enabled based on the new criteria */
|
||||
async isEnabled(): Promise<boolean> {
|
||||
// Check if .ai directory exists
|
||||
try {
|
||||
const stat = await this.fs.stat(join(this.workingDir, ".ai"));
|
||||
return stat.isDirectory();
|
||||
} catch {
|
||||
// Continue to next check
|
||||
}
|
||||
|
||||
// Check if .ai/ or .ai is gitignored
|
||||
try {
|
||||
const gitignorePath = join(this.workingDir, ".gitignore");
|
||||
const gitignoreContent = await this.fs.readFile(gitignorePath, "utf8");
|
||||
const lines = gitignoreContent.split("\n").map((line) => line.trim());
|
||||
|
||||
// Check for .ai/ or .ai patterns (ignore comments and empty lines)
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("#") || line === "") {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check for various .ai patterns
|
||||
if (
|
||||
line === ".ai" || line === ".ai/" || line === "/.ai" ||
|
||||
line === "/.ai/" ||
|
||||
line === ".ai/*" || line === "/.ai/*"
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// .gitignore doesn't exist or can't be read
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Check if the history directory exists */
|
||||
async historyDirExists(): Promise<boolean> {
|
||||
try {
|
||||
const stat = await this.fs.stat(this.historyDir);
|
||||
return stat.isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Save a message to the history file */
|
||||
async addToHistory(sessionName: string, message: AIMessage): Promise<void> {
|
||||
// Only save if history should be enabled based on the new criteria
|
||||
if (!(await this.isEnabled())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Create the history directory if it doesn't exist
|
||||
if (!(await this.historyDirExists())) {
|
||||
await this.setupAiHistoryDir();
|
||||
}
|
||||
|
||||
const jsonLine = JSON.stringify(message);
|
||||
const sessionFile = join(this.historyDir, sessionName + ".jsonl");
|
||||
|
||||
try {
|
||||
// Try to read existing content
|
||||
const existingContent = await this.fs.readFile(sessionFile, "utf8");
|
||||
await this.fs.writeFile(sessionFile, existingContent + "\n" + jsonLine, "utf8");
|
||||
} catch {
|
||||
// File doesn't exist, create it with the data
|
||||
await this.fs.writeFile(sessionFile, jsonLine, "utf8");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates .ai/history directory and ensures .ai/ is gitignored at the project root.
|
||||
*/
|
||||
async setupAiHistoryDir(): Promise<void> {
|
||||
const aiHistoryDir = join(this.workingDir, ".ai", "history");
|
||||
|
||||
try {
|
||||
// Create .ai/history directory
|
||||
await this.fs.mkdir(aiHistoryDir, { recursive: true });
|
||||
|
||||
// Ensure .ai/ is gitignored at the project root
|
||||
await this.ensureAiGitignored();
|
||||
} catch (error) {
|
||||
// Log error but don't fail the main operation
|
||||
console.warn(`Failed to setup .ai/history directory: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the model from .ai/MODEL file
|
||||
*/
|
||||
async readAiModel(): Promise<string | undefined> {
|
||||
try {
|
||||
const modelPath = join(this.workingDir, ".ai", "MODEL");
|
||||
const content = await this.fs.readFile(modelPath, "utf8");
|
||||
return content.trim();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the model to .ai/MODEL file
|
||||
*/
|
||||
async writeAiModel(model: string): Promise<void> {
|
||||
const aiDir = join(this.workingDir, ".ai");
|
||||
const modelPath = join(aiDir, "MODEL");
|
||||
|
||||
try {
|
||||
// Ensure .ai directory exists
|
||||
await this.fs.mkdir(aiDir, { recursive: true });
|
||||
|
||||
// Write the model
|
||||
await this.fs.writeFile(modelPath, model.trim() + "\n", "utf8");
|
||||
} catch (error) {
|
||||
console.warn(`Failed to write .ai/MODEL file: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read parameters from .ai/PARAMETERS file
|
||||
*/
|
||||
async readAiParameters(): Promise<Record<string, string>> {
|
||||
try {
|
||||
const parametersPath = join(this.workingDir, ".ai", "PARAMETERS");
|
||||
const content = await this.fs.readFile(parametersPath, "utf8");
|
||||
|
||||
const parameters: Record<string, string> = {};
|
||||
const lines = content.split("\n");
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine && !trimmedLine.startsWith("#")) {
|
||||
const equalIndex = trimmedLine.indexOf("=");
|
||||
if (equalIndex > 0) {
|
||||
const key = trimmedLine.substring(0, equalIndex).trim();
|
||||
const value = trimmedLine.substring(equalIndex + 1).trim();
|
||||
parameters[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return parameters;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write parameters to .ai/PARAMETERS file
|
||||
*/
|
||||
async writeAiParameters(parameters: Record<string, string>): Promise<void> {
|
||||
// Check if we should create the .ai directory based on the same logic as MODEL
|
||||
const shouldCreate = await this.isEnabled();
|
||||
|
||||
if (!shouldCreate) {
|
||||
return;
|
||||
}
|
||||
|
||||
const aiDir = join(this.workingDir, ".ai");
|
||||
const parametersPath = join(aiDir, "PARAMETERS");
|
||||
|
||||
try {
|
||||
// Ensure .ai directory exists
|
||||
await this.fs.mkdir(aiDir, { recursive: true });
|
||||
|
||||
// Format parameters as key=value pairs
|
||||
const lines = Object.entries(parameters).map(([key, value]) =>
|
||||
`${key}=${value}`
|
||||
);
|
||||
const content = lines.join("\n") + (lines.length > 0 ? "\n" : "");
|
||||
|
||||
// Write the parameters
|
||||
await this.fs.writeFile(parametersPath, content, "utf8");
|
||||
} catch (error) {
|
||||
console.warn(`Failed to write .ai/PARAMETERS file: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a single parameter in .ai/PARAMETERS file
|
||||
*/
|
||||
async updateAiParameter(key: string, value: string): Promise<void> {
|
||||
const currentParameters = await this.readAiParameters();
|
||||
currentParameters[key] = value;
|
||||
await this.writeAiParameters(currentParameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that .ai/ is gitignored at the project root level.
|
||||
* Creates a .gitignore file if it doesn't exist, or adds the line if not already present.
|
||||
*/
|
||||
async ensureAiGitignored(): Promise<void> {
|
||||
const gitignorePath = join(this.workingDir, ".gitignore");
|
||||
const aiPattern = ".ai/";
|
||||
|
||||
try {
|
||||
// Try to read existing .gitignore
|
||||
let gitignoreContent = "";
|
||||
try {
|
||||
gitignoreContent = await this.fs.readFile(gitignorePath, "utf8");
|
||||
} catch {
|
||||
// .gitignore doesn't exist, will create it
|
||||
}
|
||||
|
||||
// Check if .ai/ is already gitignored
|
||||
const lines = gitignoreContent.split("\n").map((line) => line.trim());
|
||||
const hasAiPattern = lines.some((line) => {
|
||||
if (line.startsWith("#") || line === "") {
|
||||
return false;
|
||||
}
|
||||
// Check for various .ai patterns
|
||||
return line === ".ai" || line === ".ai/" || line === "/.ai" ||
|
||||
line === "/.ai/" ||
|
||||
line === ".ai/*" || line === "/.ai/*";
|
||||
});
|
||||
|
||||
if (!hasAiPattern) {
|
||||
// Add .ai/ to .gitignore
|
||||
const newContent = gitignoreContent.trim() === ""
|
||||
? aiPattern
|
||||
: gitignoreContent.trim() + "\n" + aiPattern;
|
||||
|
||||
await this.fs.writeFile(gitignorePath, newContent + "\n", "utf8");
|
||||
}
|
||||
} catch (error) {
|
||||
// Log error but don't fail the main operation
|
||||
console.warn(`Failed to ensure .ai/ is gitignored: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import git from 'isomorphic-git';
|
||||
import http from 'isomorphic-git/http/web';
|
||||
import { Buffer } from 'buffer';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import { DotAI } from './DotAI';
|
||||
|
||||
|
||||
// Polyfill Buffer for browser
|
||||
if (typeof window !== 'undefined') {
|
||||
@@ -38,8 +38,6 @@ export class ProjectsManager {
|
||||
|
||||
async createProject(name: string): Promise<Project> {
|
||||
const project = await this.cloneProject(name, GIT_TEMPLATE_URL);
|
||||
const dotAI = new DotAI(this.fs, project.path);
|
||||
await dotAI.setupAiHistoryDir();
|
||||
return project;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
import { ModelMessage, generateId } from 'ai';
|
||||
import { ChatMessage } from '@/hooks/useStreamingChat';
|
||||
|
||||
/**
|
||||
* Convert ModelMessage array to ChatMessage array
|
||||
* This is useful when loading chat history from storage
|
||||
*/
|
||||
export function convertModelMessagesToChatMessages(modelMessages: ModelMessage[]): ChatMessage[] {
|
||||
return modelMessages.map(msg => ({
|
||||
...msg,
|
||||
id: generateId(),
|
||||
timestamp: Date.now()
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert ChatMessage array to ModelMessage array
|
||||
* This is useful when saving chat history to storage or sending to AI
|
||||
*/
|
||||
export function convertChatMessagesToModelMessages(chatMessages: ChatMessage[]): ModelMessage[] {
|
||||
return chatMessages.map(({ id, isStreaming, timestamp, ...modelMessage }) => modelMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save chat history as ModelMessage array (for persistence)
|
||||
*/
|
||||
export function prepareChatHistoryForStorage(chatMessages: ChatMessage[]): ModelMessage[] {
|
||||
return convertChatMessagesToModelMessages(chatMessages);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load chat history from ModelMessage array (from persistence)
|
||||
*/
|
||||
export function loadChatHistoryFromStorage(modelMessages: ModelMessage[]): ChatMessage[] {
|
||||
return convertModelMessagesToChatMessages(modelMessages);
|
||||
}
|
||||
Reference in new issue
Block a user