From 7ceb99ec793abd0e2042f7113c6536102dfbd330 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 21 Aug 2025 13:45:56 -0500 Subject: [PATCH] Start implementing streaming API --- src/components/Shakespeare/ChatPane.tsx | 256 +++++++-------------- src/components/ai/StreamingMessageItem.tsx | 150 ++++++++++++ src/hooks/useStreamingChat.ts | 254 ++++++++++++++++++++ src/lib/messageConversion.ts | 114 +++++++++ src/test/setup.ts | 13 ++ vite.config.ts | 1 + 6 files changed, 618 insertions(+), 170 deletions(-) create mode 100644 src/components/ai/StreamingMessageItem.tsx create mode 100644 src/hooks/useStreamingChat.ts create mode 100644 src/lib/messageConversion.ts diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 2c4a1cc9..9cafb4f9 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -1,6 +1,5 @@ -import { createOpenAICompatible } from '@ai-sdk/openai-compatible'; import { useState, useRef, useEffect } from 'react'; -import { ModelMessage, generateText, UserModelMessage, AssistantModelMessage, ToolModelMessage, generateId } from 'ai'; +import { generateId } from 'ai'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; import { Send, Settings, Play, CloudUpload, Loader2 } from 'lucide-react'; @@ -8,10 +7,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 { copyDirectory } from '@/lib/copyFiles'; import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools'; import { bytesToHex } from 'nostr-tools/utils'; -import { MessageItem } from '@/components/ai/MessageItem'; +import { StreamingMessageItem } from '@/components/ai/StreamingMessageItem'; import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog'; import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool'; import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool'; @@ -26,22 +26,77 @@ interface ChatPaneProps { projectName: string; } -type AIMessage = (UserModelMessage | AssistantModelMessage | ToolModelMessage) & { id: string }; - export function ChatPane({ projectId, projectName }: ChatPaneProps) { - const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); - const [isLoading, setIsLoading] = useState(false); const [isBuildLoading, setIsBuildLoading] = useState(false); const [isDeployLoading, setIsDeployLoading] = useState(false); const scrollAreaRef = useRef(null); - const { settings, isConfigured } = useAISettings(); + const { isConfigured } = useAISettings(); const { fs: browserFS } = useFS(); const { runtime } = useJSRuntime(); + // Initialize streaming chat with tools + const cwd = `/projects/${projectId}`; + const tools = { + git_commit: new GitCommitTool(browserFS, cwd), + text_editor_view: new TextEditorViewTool(browserFS, cwd), + text_editor_write: new TextEditorWriteTool(browserFS, cwd), + text_editor_str_replace: new TextEditorStrReplaceTool(browserFS, cwd), + npm_add_package: new NpmAddPackageTool(browserFS, cwd), + npm_remove_package: new NpmRemovePackageTool(browserFS, cwd), + }; + + const systemPrompt = `You are an AI assistant helping users build custom Nostr websites. You have access to tools that allow you to read, write, and manage files in the project, as well as build the project and manage npm packages. + +Key capabilities: +- Read and write files in the project +- List directory contents +- Check if files exist +- Build the project using Vite +- Get project structure overview +- Search through files +- Add and remove npm packages +- Install dependencies and dev dependencies +- Commit changes to git with automatic staging + +Guidelines: +- Always check if files exist before writing to avoid overwriting +- Provide helpful explanations of what you're doing +- Suggest improvements and best practices +- Use modern React patterns and TypeScript +- Follow Nostr protocol standards when relevant +- Ensure the project builds successfully + +The project uses: +- React 18 with TypeScript +- Vite for building +- TailwindCSS for styling +- Nostrify for Nostr integration +- shadcn/ui components + +When creating new components or pages, follow the existing patterns in the codebase.`; + + const { + messages, + isStreaming, + currentStreamingMessageId, + sendMessage, + stopStreaming, + clearMessages, + addMessage + } = useStreamingChat({ + projectId, + projectName, + tools, + systemPrompt, + onUpdateMetadata: (title, description) => { + updateMetadata(title, description); + } + }); + // Keep-alive functionality to prevent tab throttling during AI processing const { updateMetadata } = useKeepAlive({ - enabled: isLoading || isBuildLoading || isDeployLoading, + enabled: isStreaming || isBuildLoading || isDeployLoading, title: 'Shakespeare', artist: `Working on ${projectName}...`, artwork: [ @@ -53,21 +108,6 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { ] }); - const addMessage = (message: AIMessage) => { - setMessages((prev) => { - const messageMap = new Map(prev.map(m => [m.id, m])).set(message.id, message); - return Array.from(messageMap.values()); - }); - }; - - const addMessages = (newMessages: AIMessage[]) => { - setMessages((prev) => { - const messageMap = new Map(prev.map(m => [m.id, m])); - newMessages.forEach(msg => messageMap.set(msg.id, msg)); - return Array.from(messageMap.values()); - }); - }; - const runBuild = async () => { if (isBuildLoading) return; @@ -155,8 +195,8 @@ BASE_DOMAIN=nostrdeploy.com`); // Clear messages when navigating between projects useEffect(() => { - setMessages([]); - }, [projectId]) + clearMessages(); + }, [projectId, clearMessages]); useEffect(() => { // Add welcome message @@ -165,9 +205,10 @@ BASE_DOMAIN=nostrdeploy.com`); id: generateId(), role: 'assistant', content: `Hello! I'm here to help you build "${projectName}". I can help you edit files, add new features, and build your Nostr website. What would you like to work on?`, + timestamp: Date.now() }); } - }, [projectName, messages]); + }, [projectName, messages, addMessage]); useEffect(() => { if (scrollAreaRef.current && messages) { @@ -181,107 +222,19 @@ BASE_DOMAIN=nostrdeploy.com`); container.scrollTop = container.scrollHeight; } } - }, [messages, isLoading]); - - const createAIChat = async (projectId: string, messages: ModelMessage[]) => { - if (!isConfigured) { - throw new Error('AI settings not configured'); - } - - // Import the appropriate provider based on the base URL - const openai = createOpenAICompatible({ - name: 'custom', - baseURL: settings.baseUrl, - apiKey: settings.apiKey, - }); - - const provider = openai(settings.model); - const cwd = `/projects/${projectId}`; - - return generateText({ - model: provider, - messages, - onStepFinish(stepResult) { - console.log(stepResult); - addMessages(stepResult.response.messages.map(msg => ({ ...msg, id: generateId() }))); - - // Update media session with current step info - const lastMessage = stepResult.response.messages[stepResult.response.messages.length - 1]; - if (lastMessage?.role === 'tool') { - const toolName = lastMessage.content?.[0]?.toolName; - if (toolName) { - updateMetadata('Shakespeare', `Working on ${projectName} - ${toolName}`); - } - } - }, - tools: { - git_commit: new GitCommitTool(browserFS, cwd), - text_editor_view: new TextEditorViewTool(browserFS, cwd), - text_editor_write: new TextEditorWriteTool(browserFS, cwd), - text_editor_str_replace: new TextEditorStrReplaceTool(browserFS, cwd), - npm_add_package: new NpmAddPackageTool(browserFS, cwd), - npm_remove_package: new NpmRemovePackageTool(browserFS, cwd), - }, - system: `You are an AI assistant helping users build custom Nostr websites. You have access to tools that allow you to read, write, and manage files in the project, as well as build the project and manage npm packages. - -Key capabilities: -- Read and write files in the project -- List directory contents -- Check if files exist -- Build the project using Vite -- Get project structure overview -- Search through files -- Add and remove npm packages -- Install dependencies and dev dependencies -- Commit changes to git with automatic staging - -Guidelines: -- Always check if files exist before writing to avoid overwriting -- Provide helpful explanations of what you're doing -- Suggest improvements and best practices -- Use modern React patterns and TypeScript -- Follow Nostr protocol standards when relevant -- Ensure the project builds successfully - -The project uses: -- React 18 with TypeScript -- Vite for building -- TailwindCSS for styling -- Nostrify for Nostr integration -- shadcn/ui components - -When creating new components or pages, follow the existing patterns in the codebase.` - }); - }; + }, [messages, isStreaming]); const handleSend = async () => { - if (!input.trim() || isLoading) return; + if (!input.trim() || isStreaming) return; - const userMessage: AIMessage = { - id: generateId(), - role: 'user', - content: input, - }; - - addMessage(userMessage); + const messageContent = input; setInput(''); - setIsLoading(true); try { - const aiMessages: AIMessage[] = [...messages, userMessage]; - updateMetadata('Shakespeare', `Processing your request for ${projectName}...`); - - await createAIChat(projectId, aiMessages); + await sendMessage(messageContent); } catch (error) { console.error('AI chat error:', error); - const errorMessage: AIMessage = { - id: generateId(), - role: 'assistant', - content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.', - }; - addMessage(errorMessage); - } finally { - setIsLoading(false); + // Error handling is done in the useStreamingChat hook } }; @@ -365,7 +318,7 @@ When creating new components or pages, follow the existing patterns in the codeb className="gap-1 sm:gap-2 hover:bg-primary/10 hover:border-primary/20" onClick={runBuild} onMouseDown={handleFirstInteraction} - disabled={isBuildLoading || isDeployLoading} + disabled={isBuildLoading || isDeployLoading || isStreaming} > {isBuildLoading ? ( @@ -382,7 +335,7 @@ When creating new components or pages, follow the existing patterns in the codeb className="gap-1 sm:gap-2 hover:bg-accent/10 hover:border-accent/20" onClick={runDeploy} onMouseDown={handleFirstInteraction} - disabled={isDeployLoading || isBuildLoading} + disabled={isDeployLoading || isBuildLoading || isStreaming} > {isDeployLoading ? ( @@ -398,52 +351,15 @@ When creating new components or pages, follow the existing patterns in the codeb
- {messages.map((message, index) => { - // For assistant messages, find corresponding tool results - const toolResults: ToolModelMessage[] = []; - if (message.role === 'assistant') { - // Look for tool messages that come after this assistant message - for (let i = index + 1; i < messages.length; i++) { - const nextMessage = messages[i]; - if (nextMessage?.role === 'tool') { - toolResults.push(nextMessage); - } else if (nextMessage?.role === 'assistant' || nextMessage?.role === 'user') { - // Stop looking when we hit the next non-tool message - break; - } - } - } - - return ( - - ); - })} - - {isLoading && ( -
-
-
-
-
-
-
-
-
-
- Assistant - AI -
-
- Thinking... -
-
-
- )} + {messages.map((message) => ( + + ))}
@@ -456,12 +372,12 @@ When creating new components or pages, follow the existing patterns in the codeb onFocus={handleFirstInteraction} placeholder="Ask me to add features, edit files, or build your project..." className="min-h-[60px] resize-none" - disabled={isLoading} + disabled={isStreaming} /> + )} + +
+ {message.role === 'user' ? ( +
+ {message.content} +
+ ) : message.role === 'assistant' ? ( +
+ {/* Text content */} + {message.content && ( +
+ {message.isStreaming ? ( + {message.content} + ) : ( +
+ {message.content} +
+ )} + {message.isStreaming && ( + + )} +
+ )} + + {/* Tool calls */} + {message.toolCalls && message.toolCalls.length > 0 && ( +
+ {message.toolCalls.map((toolCall) => { + // Create a mock CoreToolMessage for compatibility with AssistantContent + const mockToolResults: CoreToolMessage[] = message.toolResults ? [ + { + role: 'tool', + content: message.toolResults + .filter(result => result.toolCallId === toolCall.id) + .map(result => ({ + type: 'tool-result' as const, + toolCallId: result.toolCallId, + toolName: result.toolName, + output: { + type: 'text' as const, + value: typeof result.output === 'string' ? result.output : JSON.stringify(result.output) + } + })) + } + ] : []; + + return ( + + ); + })} +
+ )} + + {/* Streaming indicator for when there's no content yet */} + {message.isStreaming && !message.content && !message.toolCalls?.length && ( +
+
+
+
+
+
+ Thinking... +
+ )} +
+ ) : null} +
+ + + ); +}); + +StreamingMessageItem.displayName = 'StreamingMessageItem'; \ No newline at end of file diff --git a/src/hooks/useStreamingChat.ts b/src/hooks/useStreamingChat.ts new file mode 100644 index 00000000..72431b55 --- /dev/null +++ b/src/hooks/useStreamingChat.ts @@ -0,0 +1,254 @@ +import { useState, useCallback, useRef } from 'react'; +import { createOpenAICompatible } from '@ai-sdk/openai-compatible'; +import { streamText, ModelMessage, generateId, Tool, stepCountIs } from 'ai'; +import { useAISettings } from '@/hooks/useAISettings'; + +export interface StreamingMessage { + id: string; + role: 'user' | 'assistant' | 'tool'; + content: string; + toolCalls?: Array<{ + id: string; + toolName: string; + input: unknown; + }>; + toolResults?: Array<{ + toolCallId: string; + toolName: string; + output: unknown; + }>; + isStreaming?: boolean; + timestamp?: number; +} + +interface UseStreamingChatOptions { + projectId: string; + projectName: string; + tools?: Record; + systemPrompt?: string; + onStepFinish?: (stepResult: unknown) => void; + onUpdateMetadata?: (title: string, description: string) => void; +} + +export function useStreamingChat({ + projectName, + tools = {}, + systemPrompt, + onStepFinish, + onUpdateMetadata +}: UseStreamingChatOptions) { + const [messages, setMessages] = useState([]); + const [isStreaming, setIsStreaming] = useState(false); + const [currentStreamingMessageId, setCurrentStreamingMessageId] = useState(null); + const abortControllerRef = useRef(null); + const { settings, isConfigured } = useAISettings(); + + // Convert StreamingMessage to ModelMessage for AI SDK + const convertToModelMessages = useCallback((streamingMessages: StreamingMessage[]): ModelMessage[] => { + const modelMessages: ModelMessage[] = []; + + for (const msg of streamingMessages) { + if (msg.role === 'user') { + modelMessages.push({ + role: 'user', + content: msg.content + }); + } else if (msg.role === 'assistant') { + // For assistant messages, just use text content for now + // Tool calls will be handled by the AI SDK automatically + if (msg.content) { + modelMessages.push({ + role: 'assistant', + content: msg.content + }); + } + } + } + + return modelMessages; + }, []); + + const addMessage = useCallback((message: StreamingMessage) => { + 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) => { + setMessages(prev => prev.map(msg => + msg.id === id ? { ...msg, ...updates } : msg + )); + }, []); + + const sendMessage = useCallback(async (content: string) => { + if (!isConfigured || isStreaming) return; + + // Add user message + const userMessage: StreamingMessage = { + id: generateId(), + role: 'user', + content, + timestamp: Date.now() + }; + + addMessage(userMessage); + + // Create assistant message for streaming + const assistantMessageId = generateId(); + const assistantMessage: StreamingMessage = { + id: assistantMessageId, + role: 'assistant', + content: '', + isStreaming: true, + timestamp: Date.now() + }; + + addMessage(assistantMessage); + setCurrentStreamingMessageId(assistantMessageId); + setIsStreaming(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 = 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: (stepResult) => { + console.log('Step finished:', stepResult); + + // Handle tool calls and results + if (stepResult.toolCalls && stepResult.toolCalls.length > 0) { + updateMessage(assistantMessageId, { + toolCalls: stepResult.toolCalls.map(tc => ({ + id: tc.toolCallId, + toolName: tc.toolName, + input: tc.input + })) + }); + } + + if (stepResult.toolResults && stepResult.toolResults.length > 0) { + // Add tool results as separate message + const toolMessage: StreamingMessage = { + id: generateId(), + role: 'tool', + content: '', + toolResults: stepResult.toolResults.map(tr => ({ + toolCallId: tr.toolCallId, + toolName: tr.toolName, + output: tr.output + })), + timestamp: Date.now() + }; + addMessage(toolMessage); + } + + // 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}`); + } + + // Call custom step finish handler + if (onStepFinish) { + onStepFinish(stepResult); + } + } + }); + + // Stream the text content + let streamedContent = ''; + + for await (const chunk of result.textStream) { + if (abortControllerRef.current?.signal.aborted) { + break; + } + + streamedContent += chunk; + updateMessage(assistantMessageId, { + content: streamedContent, + isStreaming: true + }); + } + + // Wait for the final result + const finalResult = await result; + const finalText = await finalResult.text; + + // Update final message + updateMessage(assistantMessageId, { + content: finalText, + isStreaming: false + }); + + } catch (error) { + console.error('Streaming error:', error); + + // Handle error - update the assistant message with error content + updateMessage(assistantMessageId, { + content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.', + isStreaming: false + }); + } finally { + setIsStreaming(false); + setCurrentStreamingMessageId(null); + abortControllerRef.current = null; + } + }, [ + isConfigured, + isStreaming, + messages, + settings, + tools, + systemPrompt, + projectName, + convertToModelMessages, + addMessage, + updateMessage, + onStepFinish, + onUpdateMetadata + ]); + + const stopStreaming = useCallback(() => { + if (abortControllerRef.current) { + abortControllerRef.current.abort(); + } + }, []); + + const clearMessages = useCallback(() => { + setMessages([]); + }, []); + + return { + messages, + isStreaming, + currentStreamingMessageId, + sendMessage, + stopStreaming, + clearMessages, + addMessage, + updateMessage, + isConfigured + }; +} \ No newline at end of file diff --git a/src/lib/messageConversion.ts b/src/lib/messageConversion.ts new file mode 100644 index 00000000..1107c1c0 --- /dev/null +++ b/src/lib/messageConversion.ts @@ -0,0 +1,114 @@ +import { ModelMessage, generateId } from 'ai'; +import { StreamingMessage } from '@/hooks/useStreamingChat'; + +/** + * Convert ModelMessage array to StreamingMessage array + * This is useful when loading chat history from storage + */ +export function convertModelMessagesToStreamingMessages(modelMessages: ModelMessage[]): StreamingMessage[] { + const streamingMessages: StreamingMessage[] = []; + + for (const msg of modelMessages) { + if (msg.role === 'user') { + streamingMessages.push({ + id: generateId(), + role: 'user', + content: typeof msg.content === 'string' ? msg.content : msg.content.map(part => { + if (part.type === 'text') return part.text; + return ''; + }).join(''), + timestamp: Date.now() + }); + } else if (msg.role === 'assistant') { + const streamingMessage: StreamingMessage = { + id: generateId(), + role: 'assistant', + content: '', + timestamp: Date.now() + }; + + if (typeof msg.content === 'string') { + streamingMessage.content = msg.content; + } else if (Array.isArray(msg.content)) { + // Extract text content + const textParts = msg.content.filter(part => part.type === 'text'); + streamingMessage.content = textParts.map(part => part.text).join(''); + + // Extract tool calls + const toolCalls = msg.content.filter(part => part.type === 'tool-call'); + if (toolCalls.length > 0) { + streamingMessage.toolCalls = toolCalls.map(tc => ({ + id: tc.toolCallId, + toolName: tc.toolName, + input: tc.input + })); + } + } + + streamingMessages.push(streamingMessage); + } else if (msg.role === 'tool') { + // Tool results are typically integrated into the assistant message + // but we can create a separate tool message if needed + if (Array.isArray(msg.content)) { + const toolResults = msg.content.map(result => ({ + toolCallId: result.toolCallId, + toolName: result.toolName, + output: result.output + })); + + streamingMessages.push({ + id: generateId(), + role: 'tool', + content: '', + toolResults, + timestamp: Date.now() + }); + } + } + } + + return streamingMessages; +} + +/** + * Convert StreamingMessage array to ModelMessage array + * This is useful when saving chat history to storage or sending to AI + */ +export function convertStreamingMessagesToModelMessages(streamingMessages: StreamingMessage[]): ModelMessage[] { + const modelMessages: ModelMessage[] = []; + + for (const msg of streamingMessages) { + if (msg.role === 'user') { + modelMessages.push({ + role: 'user', + content: msg.content + }); + } else if (msg.role === 'assistant') { + // For assistant messages, just use text content for now + // Tool calls will be handled by the AI SDK automatically during streaming + if (msg.content) { + modelMessages.push({ + role: 'assistant', + content: msg.content + }); + } + } + // Skip tool messages as they're handled differently in the streaming context + } + + return modelMessages; +} + +/** + * Save chat history as ModelMessage array (for persistence) + */ +export function prepareChatHistoryForStorage(streamingMessages: StreamingMessage[]): ModelMessage[] { + return convertStreamingMessagesToModelMessages(streamingMessages); +} + +/** + * Load chat history from ModelMessage array (from persistence) + */ +export function loadChatHistoryFromStorage(modelMessages: ModelMessage[]): StreamingMessage[] { + return convertModelMessagesToStreamingMessages(modelMessages); +} \ No newline at end of file diff --git a/src/test/setup.ts b/src/test/setup.ts index 91466edd..4f140f99 100644 --- a/src/test/setup.ts +++ b/src/test/setup.ts @@ -1,6 +1,19 @@ import '@testing-library/jest-dom'; import { vi } from 'vitest'; +// Mock CSS imports +vi.mock('*.css', () => ({})); +vi.mock('*.scss', () => ({})); +vi.mock('*.sass', () => ({})); + +// Mock KaTeX CSS specifically +vi.mock('katex/dist/katex.min.css', () => ({})); + +// Mock Streamdown component that might be importing KaTeX +vi.mock('@soapbox.pub/streamdown', () => ({ + Streamdown: ({ children }: { children: React.ReactNode }) => children +})); + // Mock window.matchMedia Object.defineProperty(window, 'matchMedia', { writable: true, diff --git a/vite.config.ts b/vite.config.ts index 650ac557..f3420ea1 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -22,6 +22,7 @@ export default defineConfig(() => ({ env: { DEBUG_PRINT_LIMIT: '0', // Suppress DOM output that exceeds AI context windows }, + css: true }, resolve: { alias: {