Break user texts up into separate messages

This commit is contained in:
Alex Gleason committed 2025-09-14 14:25:02 -05:00
1 parent 76fa9940db
commit 425976bb82
8 files changed
+151 -55

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@ Shakespeare is an AI chat application that allows users to build custom Nostr we
## Features
- **AI-Powered Development**: Chat with an AI assistant to build your Nostr website
- **File Attachments**: Attach files directly to chat messages with visual badges and deduplication
- **File Attachments**: Attach files directly to chat messages with structured text parts, visual badges, and deduplication
- **Project Management**: Create and manage multiple projects with sidebar navigation
- **Real-time Editing**: Edit files directly in the browser with syntax highlighting
- **File Explorer**: Browse and manage your project files
+7 -1
View File
@@ -206,11 +206,17 @@ export const AIMessageItem = memo(({
// Regular rendering for non-tool messages
if (message.role === 'user') {
// User messages: right-aligned bubble without avatar/name
const userContent = typeof message.content === 'string'
? message.content
: Array.isArray(message.content)
? message.content.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
: '';
return (
<div className="flex justify-end py-6">
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
<div className="text-sm break-words">
<UserMessage content={getContent()} />
<UserMessage content={userContent} />
</div>
</div>
</div>
+21 -8
View File
@@ -288,10 +288,20 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const handleSend = async () => {
if ((!input.trim() && attachedFiles.length === 0) || isLoading || !providerModel.trim()) return;
let messageContent = input;
const modelToUse = providerModel.trim();
// Process attached files
// Build message content as text parts
const contentParts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
// Add user input as text part if present
if (input.trim()) {
contentParts.push({
type: 'text',
text: input.trim()
});
}
// Process attached files and add as separate text parts
if (attachedFiles.length > 0) {
const filePromises = attachedFiles.map(async (file) => {
try {
@@ -305,12 +315,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const fileResults = await Promise.all(filePromises);
// Append file information to the message
if (messageContent.trim()) {
messageContent += '\n\n' + fileResults.join('\n');
} else {
messageContent = fileResults.join('\n');
}
// Add each file as a separate text part
fileResults.forEach(fileResult => {
contentParts.push({
type: 'text',
text: fileResult
});
});
}
setInput('');
@@ -320,6 +331,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
addRecentlyUsedModel(modelToUse);
try {
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
await sendMessage(messageContent, modelToUse);
} catch (error) {
console.error('AI chat error:', error);
@@ -0,0 +1,59 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { UserMessage } from './UserMessage';
describe('UserMessage Integration', () => {
it('renders text parts with file attachments correctly', () => {
// Simulate the new text parts structure that ChatPane would create
const content = [
{ type: 'text' as const, text: 'Please analyze this file:' },
{ type: 'text' as const, text: 'File added to /tmp/data.csv' },
{ type: 'text' as const, text: 'Let me know what you find!' }
];
render(<UserMessage content={content} />);
// Check that regular text is displayed
expect(screen.getByText('Please analyze this file:')).toBeInTheDocument();
expect(screen.getByText('Let me know what you find!')).toBeInTheDocument();
// Check that file attachment is rendered as a badge
expect(screen.getByText('data.csv')).toBeInTheDocument();
expect(screen.getByText('added to /tmp/data.csv')).toBeInTheDocument();
});
it('handles single text part with file attachment', () => {
const content = [
{ type: 'text' as const, text: 'File added to /tmp/script.js' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('script.js')).toBeInTheDocument();
expect(screen.getByText('added to /tmp/script.js')).toBeInTheDocument();
});
it('handles multiple file attachments in separate parts', () => {
const content = [
{ type: 'text' as const, text: 'Here are my files:' },
{ type: 'text' as const, text: 'File added to /tmp/config.json' },
{ type: 'text' as const, text: 'File added to /tmp/styles.css' },
{ type: 'text' as const, text: 'File added to /tmp/main.js' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('Here are my files:')).toBeInTheDocument();
expect(screen.getByText('config.json')).toBeInTheDocument();
expect(screen.getByText('styles.css')).toBeInTheDocument();
expect(screen.getByText('main.js')).toBeInTheDocument();
});
it('handles empty content gracefully', () => {
const content: Array<{ type: 'text'; text: string }> = [];
const { container } = render(<UserMessage content={content} />);
expect(container.firstChild).toBeNull();
});
});
+32 -8
View File
@@ -11,18 +11,35 @@ describe('UserMessage', () => {
expect(screen.getByText(content)).toBeInTheDocument();
});
it('renders file attachment badges for single file', () => {
it('handles backward compatibility with string content containing file attachments', () => {
const content = 'Here is my file: File added to /tmp/test.txt';
render(<UserMessage content={content} />);
// When using string content, it should still work but won't separate file attachments
expect(screen.getByText(content)).toBeInTheDocument();
});
it('renders file attachment badges for single file with text parts', () => {
const content = [
{ type: 'text' as const, text: 'Here is my file:' },
{ type: 'text' as const, text: 'File added to /tmp/test.txt' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('Here is my file:')).toBeInTheDocument();
expect(screen.getByText('test.txt')).toBeInTheDocument();
expect(screen.getByText('added to /tmp/test.txt')).toBeInTheDocument();
});
it('renders multiple file attachments', () => {
const content = 'Files uploaded:\nFile added to /tmp/document.pdf\nFile added to /tmp/image.jpg\nAll done!';
it('renders multiple file attachments with text parts', () => {
const content = [
{ type: 'text' as const, text: 'Files uploaded:' },
{ type: 'text' as const, text: 'File added to /tmp/document.pdf' },
{ type: 'text' as const, text: 'File added to /tmp/image.jpg' },
{ type: 'text' as const, text: 'All done!' }
];
render(<UserMessage content={content} />);
@@ -33,7 +50,7 @@ describe('UserMessage', () => {
});
it('renders text files with FileText icon', () => {
const content = 'File added to /tmp/script.js';
const content = [{ type: 'text' as const, text: 'File added to /tmp/script.js' }];
render(<UserMessage content={content} />);
@@ -42,7 +59,7 @@ describe('UserMessage', () => {
});
it('handles files without extensions', () => {
const content = 'File added to /tmp/README';
const content = [{ type: 'text' as const, text: 'File added to /tmp/README' }];
render(<UserMessage content={content} />);
@@ -51,7 +68,7 @@ describe('UserMessage', () => {
});
it('handles complex filenames with underscores and numbers', () => {
const content = 'File added to /tmp/my_file_1.txt';
const content = [{ type: 'text' as const, text: 'File added to /tmp/my_file_1.txt' }];
render(<UserMessage content={content} />);
@@ -60,7 +77,10 @@ describe('UserMessage', () => {
});
it('preserves whitespace in text content', () => {
const content = 'Line 1\n\nLine 3 with spaces \nFile added to /tmp/test.txt\n\nFinal line';
const content = [
{ type: 'text' as const, text: 'Line 1\n\nLine 3 with spaces \n\nFinal line' },
{ type: 'text' as const, text: 'File added to /tmp/test.txt' }
];
const { container } = render(<UserMessage content={content} />);
@@ -72,7 +92,11 @@ describe('UserMessage', () => {
});
it('handles mixed content with file attachments in the middle', () => {
const content = 'Starting text File added to /tmp/middle.txt ending text';
const content = [
{ type: 'text' as const, text: 'Starting text' },
{ type: 'text' as const, text: 'File added to /tmp/middle.txt' },
{ type: 'text' as const, text: 'ending text' }
];
render(<UserMessage content={content} />);
+29 -35
View File
@@ -1,51 +1,45 @@
import { FileText, File } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import type OpenAI from 'openai';
interface UserMessageProps {
content: string;
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>;
}
/**
* Component to render user messages nicely
* Handles both string content and array content (text parts)
* Detects "File added to /tmp/<filename>" patterns and renders them as badges
*/
export function UserMessage({ content }: UserMessageProps) {
// Convert content to array format for uniform processing
const contentParts = typeof content === 'string'
? [{ type: 'text' as const, text: content }]
: content.filter(part => part.type === 'text') as Array<{ type: 'text'; text: string }>;
// Regular expression to match "File added to /tmp/<filename>" patterns
const filePattern = /File added to (\/tmp\/[^\s\n]+)/g;
const filePattern = /^File added to (\/tmp\/[^\s\n]+)$/;
// Split content by file attachments to render them separately
const parts: Array<{ type: 'text' | 'file'; content: string; filepath?: string }> = [];
let lastIndex = 0;
let match;
// Process each content part and categorize as text or file
const processedParts: Array<{ type: 'text' | 'file'; content: string; filepath?: string }> = [];
while ((match = filePattern.exec(content)) !== null) {
// Add text before the file attachment
if (match.index > lastIndex) {
const textBefore = content.slice(lastIndex, match.index);
if (textBefore.trim()) {
parts.push({ type: 'text', content: textBefore });
}
contentParts.forEach(part => {
const text = part.text.trim();
const match = text.match(filePattern);
if (match) {
// This is a file attachment
const filepath = match[1]; // "/tmp/filename.txt"
processedParts.push({ type: 'file', content: text, filepath });
} else if (text) {
// This is regular text content
processedParts.push({ type: 'text', content: text });
}
});
// Add the file attachment
const fullMatch = match[0]; // "File added to /tmp/filename.txt"
const filepath = match[1]; // "/tmp/filename.txt"
parts.push({ type: 'file', content: fullMatch, filepath });
lastIndex = match.index + fullMatch.length;
}
// Add remaining text after the last file attachment
if (lastIndex < content.length) {
const remainingText = content.slice(lastIndex);
if (remainingText.trim()) {
parts.push({ type: 'text', content: remainingText });
}
}
// If no file attachments found, render as normal text
if (parts.length === 0) {
return <span className="whitespace-pre-wrap">{content}</span>;
// If no content, return empty
if (processedParts.length === 0) {
return null;
}
const getFileIcon = (filename: string) => {
@@ -67,12 +61,12 @@ export function UserMessage({ content }: UserMessageProps) {
return (
<div className="space-y-2">
{parts.map((part, index) => {
{processedParts.map((part, index) => {
if (part.type === 'text') {
return (
<span key={index} className="whitespace-pre-wrap">
<div key={index} className="whitespace-pre-wrap">
{part.content}
</span>
</div>
);
} else {
const filename = getFileName(part.filepath!);
+1 -1
View File
@@ -111,7 +111,7 @@ export function useAIChat({
}, [projectId]);
// Actions
const sendMessage = useCallback(async (content: string, providerModel: string) => {
const sendMessage = useCallback(async (content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string) => {
await initSession();
await sessionManager.sendMessage(projectId, content, providerModel);
}, [projectId, sessionManager, initSession]);
+1 -1
View File
@@ -160,7 +160,7 @@ export class SessionManager {
/**
* Send a message and start AI generation
*/
async sendMessage(projectId: string, content: string, providerModel: string): Promise<void> {
async sendMessage(projectId: string, content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string): Promise<void> {
const session = this.sessions.get(projectId);
if (!session || session.isLoading) return;