Start implementing streaming API

This commit is contained in:
Alex Gleason committed 2025-08-21 13:45:56 -05:00
1 parent 5557ad9505
commit f917453b30
6 files changed
+618 -170

No files matched your search

+86 -170
View File
@@ -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<AIMessage[]>([]);
const [input, setInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [isBuildLoading, setIsBuildLoading] = useState(false);
const [isDeployLoading, setIsDeployLoading] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement>(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 ? (
<Loader2 className="h-4 w-4 animate-spin" />
@@ -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 ? (
<Loader2 className="h-4 w-4 animate-spin" />
@@ -398,52 +351,15 @@ When creating new components or pages, follow the existing patterns in the codeb
<div className="flex-1 overflow-y-scroll overflow-x-hidden" ref={scrollAreaRef}>
<div className="p-4 space-y-4">
{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 (
<MessageItem
key={index}
message={message}
userDisplayName="You"
toolResults={toolResults}
/>
);
})}
{isLoading && (
<div className="flex gap-3">
<div className="w-8 h-8 rounded-full bg-muted flex items-center justify-center flex-shrink-0">
<div className="flex space-x-1">
<div className="h-1 w-1 bg-current rounded-full animate-bounce [animation-delay:-0.3s]"></div>
<div className="h-1 w-1 bg-current rounded-full animate-bounce [animation-delay:-0.15s]"></div>
<div className="h-1 w-1 bg-current rounded-full animate-bounce"></div>
</div>
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium text-sm">Assistant</span>
<span className="text-xs text-muted-foreground">AI</span>
</div>
<div className="text-sm text-muted-foreground">
Thinking...
</div>
</div>
</div>
)}
{messages.map((message) => (
<StreamingMessageItem
key={message.id}
message={message}
userDisplayName="You"
isCurrentlyStreaming={isStreaming && message.id === currentStreamingMessageId}
onStopStreaming={stopStreaming}
/>
))}
</div>
</div>
@@ -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}
/>
<Button
onClick={handleSend}
onMouseDown={handleFirstInteraction}
disabled={!input.trim() || isLoading}
disabled={!input.trim() || isStreaming}
className="self-end"
size="icon"
>
+150
View File
@@ -0,0 +1,150 @@
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 { Response } from '@/components/ai-elements/response';
import { StreamingMessage } from '@/hooks/useStreamingChat';
import { AssistantContent } from '@/components/ai/AssistantContent';
import { CoreToolMessage } from 'ai';
interface StreamingMessageItemProps {
message: StreamingMessage;
userDisplayName?: string;
userProfileImage?: string;
isCurrentlyStreaming?: boolean;
onStopStreaming?: () => void;
}
export const StreamingMessageItem = 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;
}
return (
<div className="flex gap-3">
<Avatar className="h-8 w-8 flex-shrink-0">
{message.role === 'user' ? (
<>
<AvatarImage src={userProfileImage} alt={userDisplayName} />
<AvatarFallback>
<User className="h-4 w-4" />
</AvatarFallback>
</>
) : (
<>
<AvatarFallback>
<Bot className="h-4 w-4" />
</AvatarFallback>
</>
)}
</Avatar>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium text-sm">
{message.role === 'user' ? userDisplayName : 'Assistant'}
</span>
<span className="text-xs text-muted-foreground">
{message.role === 'user' ? 'User' : 'AI'}
</span>
{isCurrentlyStreaming && onStopStreaming && (
<Button
variant="outline"
size="sm"
onClick={onStopStreaming}
className="ml-auto gap-1 h-6 px-2 text-xs"
>
<Square className="h-3 w-3" />
Stop
</Button>
)}
</div>
<div className="text-sm">
{message.role === 'user' ? (
<div className="whitespace-pre-wrap break-words">
{message.content}
</div>
) : message.role === 'assistant' ? (
<div>
{/* Text content */}
{message.content && (
<div className="mb-2">
{message.isStreaming ? (
<Response>{message.content}</Response>
) : (
<div className="prose prose-sm max-w-none dark:prose-invert">
<Response>{message.content}</Response>
</div>
)}
{message.isStreaming && (
<span className="inline-block w-2 h-4 bg-current animate-pulse ml-1" />
)}
</div>
)}
{/* Tool calls */}
{message.toolCalls && message.toolCalls.length > 0 && (
<div className="space-y-2">
{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 (
<AssistantContent
key={toolCall.id}
content={[
{
type: 'tool-call',
toolCallId: toolCall.id,
toolName: toolCall.toolName,
input: toolCall.input
}
]}
toolResults={mockToolResults}
/>
);
})}
</div>
)}
{/* Streaming indicator for when there's no content yet */}
{message.isStreaming && !message.content && !message.toolCalls?.length && (
<div className="flex items-center gap-2 text-muted-foreground">
<div className="flex space-x-1">
<div className="h-1 w-1 bg-current rounded-full animate-bounce [animation-delay:-0.3s]"></div>
<div className="h-1 w-1 bg-current rounded-full animate-bounce [animation-delay:-0.15s]"></div>
<div className="h-1 w-1 bg-current rounded-full animate-bounce"></div>
</div>
<span className="text-xs">Thinking...</span>
</div>
)}
</div>
) : null}
</div>
</div>
</div>
);
});
StreamingMessageItem.displayName = 'StreamingMessageItem';
+254
View File
@@ -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<string, Tool>;
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<StreamingMessage[]>([]);
const [isStreaming, setIsStreaming] = useState(false);
const [currentStreamingMessageId, setCurrentStreamingMessageId] = useState<string | null>(null);
const abortControllerRef = useRef<AbortController | null>(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<StreamingMessage>) => {
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
};
}
+114
View File
@@ -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);
}
+13
View File
@@ -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,
+1
View File
@@ -22,6 +22,7 @@ export default defineConfig(() => ({
env: {
DEBUG_PRINT_LIMIT: '0', // Suppress DOM output that exceeds AI context windows
},
css: true
},
resolve: {
alias: {