From fcfcacb855de42595aca79c0e936d64f66172d12 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Fri, 5 Sep 2025 23:21:58 +0000 Subject: [PATCH] cleanup --- MULTI_SESSION_GUIDE.md | 208 ----------- src/components/AIMessageItem.tsx | 2 +- src/components/ProjectSessionIndicator.tsx | 34 -- src/components/ProjectSidebar.tsx | 8 +- src/components/SessionStatusIndicator.tsx | 166 --------- src/components/Shakespeare/ChatPane.tsx | 5 +- src/hooks/useAIChat.ts | 403 --------------------- src/hooks/useAIChatSession.ts | 118 ++---- src/hooks/useSessionSubscription.ts | 22 ++ src/lib/SessionManager.ts | 78 +++- src/pages/Index.tsx | 2 +- 11 files changed, 144 insertions(+), 902 deletions(-) delete mode 100644 MULTI_SESSION_GUIDE.md delete mode 100644 src/components/ProjectSessionIndicator.tsx delete mode 100644 src/components/SessionStatusIndicator.tsx delete mode 100644 src/hooks/useAIChat.ts create mode 100644 src/hooks/useSessionSubscription.ts diff --git a/MULTI_SESSION_GUIDE.md b/MULTI_SESSION_GUIDE.md deleted file mode 100644 index 06215ffc..00000000 --- a/MULTI_SESSION_GUIDE.md +++ /dev/null @@ -1,208 +0,0 @@ -# Multi-Session AI Management System - -Shakespeare now supports multiple AI agent sessions running concurrently across different projects without interruption. This guide explains how the system works and how to use it effectively. - -## Overview - -The multi-session system allows you to: -- **Run multiple AI sessions simultaneously** across different projects -- **Background processing** - AI agents continue working even when you switch to other projects -- **Session persistence** - Sessions are automatically saved and restored across browser sessions -- **Real-time monitoring** - Track all active sessions with live status indicators -- **Smart notifications** - Get notified when background sessions complete - -## Key Components - -### SessionManager -The core class that manages all AI sessions globally: -- Handles session creation, deletion, and state management -- Manages AI generation loops for multiple sessions -- Provides event-based communication between sessions and UI -- Persists session state to localStorage for browser session recovery - -### SessionManagerProvider -React context provider that creates and manages the global SessionManager instance: -- Automatically initializes on app startup -- Provides session manager to all components via context -- Handles cleanup on app shutdown - -### useAIChatSession Hook -Enhanced hook that replaces the original `useAIChat` hook: -- Integrates with the global session manager -- Automatically creates or reuses sessions for projects -- Maintains backward compatibility with existing chat components - -### SessionStatusIndicator -Visual component that shows active session status in the sidebar header: -- Displays total number of active sessions -- Shows how many sessions are currently processing -- Provides popover with detailed session information -- Allows stopping or deleting sessions directly from the UI - -### ProjectSessionIndicator -Small visual indicator next to project names in the sidebar: -- Shows a spinning loader when AI is actively processing -- Shows a green dot when session exists but is idle -- Hidden when no session exists for that project - -### SessionMonitor -Background component that monitors session state: -- Shows toast notifications when background sessions complete -- Provides navigation links to completed sessions -- Only notifies for sessions not currently being viewed - -## How It Works - -### Session Creation -When you open a project: -1. The system checks if an active session already exists for that project -2. If found, it reuses the existing session (preserving message history) -3. If not found, it creates a new session and loads the last saved history from `.ai/history/` - -### Background Processing -When you switch projects: -1. The current session continues running in the background -2. AI generation, tool execution, and file operations continue uninterrupted -3. Session state is continuously updated and persisted -4. You can monitor progress via the SessionStatusIndicator - -### Session Persistence -Sessions are automatically saved to localStorage: -- Message history is preserved across browser restarts -- Session configuration and state are restored -- Active sessions resume from where they left off - -### Notifications -When a background session completes: -- A toast notification appears with the project name -- Clicking "View" navigates directly to that project -- Notifications only appear for sessions you're not currently viewing - -## Using the System - -### Basic Usage -The multi-session system works transparently with existing functionality: -- Start AI conversations as usual - sessions are created automatically -- Switch between projects freely - sessions persist in the background -- **Messages stream in real-time** - see AI responses as they happen, even when switching projects -- **Stop generation directly** - use the stop button in the chat interface, no need to click indicators -- Monitor active sessions via the status indicator in the sidebar - -### Session Status Indicator -Located in the sidebar header, shows: -- **Number badge**: Total active sessions -- **Blue badge**: Currently processing sessions -- **Spinner icon**: When any session is active -- **Click to expand**: Detailed view of all sessions with management controls - -### Project Session Indicators -Visual indicators next to project names in the sidebar: -- **Spinning loader**: AI is actively processing for this project -- **Green dot**: Session exists but is currently idle -- **No indicator**: No active session for this project - -### Real-Time Chat Streaming -- **Live updates**: Messages stream directly to the chat interface in real-time -- **Cross-project visibility**: See AI responses even when viewing other projects -- **Immediate control**: Stop generation using the stop button in the chat interface -- **No manual refresh needed**: UI updates automatically as sessions progress - -### Session Management -From the SessionStatusIndicator popover: -- **View session details**: Project name, message count, last activity -- **Stop processing**: Cancel ongoing AI generation -- **Delete session**: Remove session completely -- **Navigate**: Click project name to switch to that session - -### Monitoring Background Work -- Sessions show real-time status updates -- Progress is visible even when working on other projects -- Streaming content and tool execution continue in background -- Keep-alive system prevents browser throttling during AI processing - -## Technical Implementation - -### Architecture -``` -App -├── SessionManagerProvider -│ ├── SessionManager (global state) -│ ├── SessionMonitor (notifications) -│ └── Components -│ ├── ChatPane (uses useAIChatSession) -│ └── SessionStatusIndicator -``` - -### Session Lifecycle -1. **Creation**: Project opened → Session created/restored -2. **Active**: AI processing, tool execution, message handling -3. **Background**: Project switched → Session continues processing -4. **Persistence**: State saved to localStorage continuously -5. **Restoration**: Browser restart → Sessions restored from localStorage -6. **Cleanup**: Project deleted → Associated sessions removed - -### Event System -The SessionManager uses an event-driven architecture: -- `sessionCreated`: New session initialized -- `sessionUpdated`: Session state changed -- `sessionDeleted`: Session removed -- `messageAdded`: New message in session -- `streamingUpdate`: Real-time AI response updates -- `loadingChanged`: Processing status changed - -### Performance Considerations -- Sessions run independently without blocking each other -- Background sessions use minimal resources when idle -- Keep-alive system only activates during AI processing -- localStorage persistence is throttled to avoid excessive writes - -## Migration from Single Session - -The new system is fully backward compatible: -- Existing `ChatPane` components work without changes -- Message history is preserved and migrated automatically -- All existing AI functionality continues to work -- No breaking changes to the API - -### Key Differences -- Sessions persist across project switches -- Multiple AI agents can work simultaneously -- Background processing continues uninterrupted -- Global session monitoring and management - -## Best Practices - -### For Users -1. **Monitor active sessions** via the status indicator -2. **Let background sessions complete** before closing the browser -3. **Use notifications** to track progress on multiple projects -4. **Clean up unused sessions** to maintain performance - -### For Developers -1. **Use useAIChatSession** instead of useAIChat for new components -2. **Subscribe to session events** for custom integrations -3. **Handle session cleanup** when projects are deleted -4. **Consider session limits** for resource management - -## Troubleshooting - -### Common Issues -- **Sessions not persisting**: Check localStorage permissions -- **Background processing stopped**: Verify keep-alive audio permissions -- **Memory usage high**: Clean up old sessions via the status indicator -- **Notifications not showing**: Ensure toast permissions are enabled - -### Debug Information -- Session state is logged to browser console -- SessionManager events can be monitored for debugging -- localStorage key: `shakespeare:sessions` -- Error handling includes graceful degradation - -## Future Enhancements - -Planned improvements include: -- Session resource limits and automatic cleanup -- Cross-tab session synchronization -- Enhanced session analytics and metrics -- Batch operations across multiple sessions -- Session templates and presets \ No newline at end of file diff --git a/src/components/AIMessageItem.tsx b/src/components/AIMessageItem.tsx index 8229be59..ea668d08 100644 --- a/src/components/AIMessageItem.tsx +++ b/src/components/AIMessageItem.tsx @@ -1,7 +1,7 @@ import { memo, useState } from 'react'; import { Streamdown } from 'streamdown'; import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus } from 'lucide-react'; -import { AIMessage } from '@/hooks/useAIChat'; +import type { AIMessage } from '@/lib/SessionManager'; import { cn } from '@/lib/utils'; import OpenAI from 'openai'; diff --git a/src/components/ProjectSessionIndicator.tsx b/src/components/ProjectSessionIndicator.tsx deleted file mode 100644 index f9e938f5..00000000 --- a/src/components/ProjectSessionIndicator.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { Loader2 } from 'lucide-react'; -import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; -import { cn } from '@/lib/utils'; - -interface ProjectSessionIndicatorProps { - projectId: string; - className?: string; -} - -/** - * Small indicator that shows if a project has active AI sessions - * Positioned as a status badge on the folder icon - */ -export function ProjectSessionIndicator({ projectId, className }: ProjectSessionIndicatorProps) { - const { hasActiveSessions, hasRunningSessions } = useProjectSessionStatus(projectId); - - if (!hasActiveSessions) { - return null; - } - - return ( -
- {hasRunningSessions ? ( - - ) : ( -
- )} -
- ); -} \ No newline at end of file diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index a235e69e..ed4c1749 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -1,4 +1,4 @@ -import React, { useState } from 'react'; +import React, { useState, memo } from 'react'; import { useNavigate } from 'react-router-dom'; import { Plus, Folder, Download, GitBranch, MoreVertical, Settings, Loader2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; @@ -22,7 +22,7 @@ interface ProjectItemProps { onSelect: (project: Project) => void; } -function ProjectItem({ project, isSelected, onSelect }: ProjectItemProps) { +const ProjectItem = memo(({ project, isSelected, onSelect }: ProjectItemProps) => { const navigate = useNavigate(); const { hasRunningSessions } = useProjectSessionStatus(project.id); @@ -72,7 +72,9 @@ function ProjectItem({ project, isSelected, onSelect }: ProjectItemProps) {
); -} +}); + +ProjectItem.displayName = 'ProjectItem'; interface ProjectSidebarProps { selectedProject: Project | null; diff --git a/src/components/SessionStatusIndicator.tsx b/src/components/SessionStatusIndicator.tsx deleted file mode 100644 index 9734f2cf..00000000 --- a/src/components/SessionStatusIndicator.tsx +++ /dev/null @@ -1,166 +0,0 @@ -import { useState, useEffect } from 'react'; -import { useSessionManager } from '@/hooks/useSessionManager'; -import { Badge } from '@/components/ui/badge'; -import { Button } from '@/components/ui/button'; -import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; -import { Activity, Clock, Loader2, MessageSquare, X } from 'lucide-react'; -import type { SessionState } from '@/lib/SessionManager'; -import { cn } from '@/lib/utils'; - -interface SessionStatusIndicatorProps { - className?: string; - currentProjectId?: string; -} - -/** - * Component that shows the status of all active AI sessions - */ -export function SessionStatusIndicator({ className, currentProjectId }: SessionStatusIndicatorProps) { - const sessionManager = useSessionManager(); - const [sessions, setSessions] = useState([]); - const [isOpen, setIsOpen] = useState(false); - - // Update sessions when they change - useEffect(() => { - const updateSessions = () => { - setSessions(sessionManager.getAllSessions()); - }; - - // Initial load - updateSessions(); - - // Subscribe to session changes - sessionManager.on('sessionCreated', updateSessions); - sessionManager.on('sessionUpdated', updateSessions); - sessionManager.on('sessionDeleted', updateSessions); - - return () => { - sessionManager.off('sessionCreated', updateSessions); - sessionManager.off('sessionUpdated', updateSessions); - sessionManager.off('sessionDeleted', updateSessions); - }; - }, [sessionManager]); - - const activeSessions = sessions.filter(session => session.isLoading); - const totalSessions = sessions.length; - - if (totalSessions === 0) { - return null; - } - - const handleStopSession = (sessionId: string, e: React.MouseEvent) => { - e.stopPropagation(); - sessionManager.stopGeneration(sessionId); - }; - - const handleDeleteSession = (sessionId: string, e: React.MouseEvent) => { - e.stopPropagation(); - sessionManager.deleteSession(sessionId); - }; - - const formatLastActivity = (date: Date) => { - const now = new Date(); - const diff = now.getTime() - date.getTime(); - const minutes = Math.floor(diff / 60000); - const hours = Math.floor(diff / 3600000); - - if (minutes < 1) return 'Just now'; - if (minutes < 60) return `${minutes}m ago`; - if (hours < 24) return `${hours}h ago`; - return date.toLocaleDateString(); - }; - - return ( - - - - - -
-

AI Sessions

-

- {totalSessions} active session{totalSessions !== 1 ? 's' : ''} - {activeSessions.length > 0 && ` (${activeSessions.length} running)`} -

-
-
- {sessions.map((session) => ( -
-
-
-
-
- {session.projectName} -
- {session.isLoading && ( - - )} -
-
- - {session.messages.length} messages - - {formatLastActivity(session.lastActivity)} -
- {session.streamingMessage?.content && ( -

- {session.streamingMessage.content.slice(0, 50)}... -

- )} -
-
- {session.isLoading && ( - - )} - -
-
-
- ))} -
-
-
- ); -} \ No newline at end of file diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 35563947..81aa927d 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -9,6 +9,7 @@ import { useFS } from '@/hooks/useFS'; import { useKeepAlive } from '@/hooks/useKeepAlive'; import { useAIChatSession } from '@/hooks/useAIChatSession'; +import type { AIMessage } from '@/lib/SessionManager'; import { ModelSelector } from '@/components/ModelSelector'; @@ -310,7 +311,7 @@ export const ChatPane = forwardRef(({ streamingMessage.content ? ( ) : ( @@ -329,7 +330,7 @@ export const ChatPane = forwardRef(({
- Running {(streamingMessage.tool_calls[0] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall).function.name}... + Running {streamingMessage.tool_calls?.[0]?.function?.name || 'tool'}...
diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts deleted file mode 100644 index ca195032..00000000 --- a/src/hooks/useAIChat.ts +++ /dev/null @@ -1,403 +0,0 @@ -import { useState, useCallback, useRef, useEffect } from 'react'; -import OpenAI from 'openai'; -import { useAISettings } from '@/hooks/useAISettings'; -import { useFS } from '@/hooks/useFS'; -import { DotAI } from '@/lib/DotAI'; -import { parseProviderModel } from '@/lib/parseProviderModel'; -import { Tool } from '@/lib/tools/Tool'; - -// Use OpenAI's native message type -export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam; - -export interface StreamingMessage { - role: 'assistant'; - content: string; - tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]; -} - -interface UseAIChatOptions { - projectId: string; - projectName: string; - tools?: Record; - customTools?: Record>; - systemPrompt?: string; - onUpdateMetadata?: (title: string, description: string) => void; - maxSteps?: number; -} - -export function useAIChat({ - projectId, - projectName, - tools = {}, - customTools = {}, - systemPrompt, - onUpdateMetadata, - maxSteps = 50 -}: UseAIChatOptions) { - const [messages, setMessages] = useState([]); - const [streamingMessage, setStreamingMessage] = useState(undefined); - const [isLoading, setIsLoading] = useState(false); - const [sessionName, setSessionName] = useState(''); - const abortControllerRef = useRef(null); - const { settings, isConfigured, addRecentlyUsedModel } = useAISettings(); - const { fs } = useFS(); - - // Save all messages to history - const saveMessagesToHistory = useCallback(async (allMessages: AIMessage[]) => { - if (!sessionName) return; - - try { - const dotAI = new DotAI(fs, `/projects/${projectId}`); - await dotAI.setHistory(sessionName, allMessages); - } catch (error) { - console.warn('Failed to save messages to history:', error); - } - }, [fs, projectId, sessionName]); - - const addMessage = useCallback((message: AIMessage) => { - setMessages(prev => { - const newMessages = [...prev, message]; - // Save to history asynchronously with all messages - saveMessagesToHistory(newMessages); - return newMessages; - }); - }, [saveMessagesToHistory]); - - const startGeneration = useCallback(async (providerModel: string, messagesToUse?: AIMessage[]) => { - const currentMessages = messagesToUse || messages; - - if (!isConfigured || isLoading || currentMessages.length === 0) return; - - // Get the last message - it should be a user message - const lastMessage = currentMessages[currentMessages.length - 1]; - if (lastMessage.role !== 'user') return; - - setIsLoading(true); - - try { - // Create abort controller for this request - abortControllerRef.current = new AbortController(); - - // Use all existing messages - const modelMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [...currentMessages]; - - // Add system message if provided - if (systemPrompt) { - modelMessages.unshift({ - role: 'system', - content: systemPrompt - }); - } - - // Parse provider and model - const parsed = parseProviderModel(providerModel, settings.providers); - const connectionConfig = parsed.connection; - const modelName = parsed.model; - - // Initialize OpenAI client with parsed connection - const openai = new OpenAI({ - baseURL: connectionConfig.baseURL, - apiKey: connectionConfig.apiKey, - dangerouslyAllowBrowser: true - }); - - // Update metadata - if (onUpdateMetadata) { - onUpdateMetadata('Shakespeare', `Working on ${projectName}...`); - } - - // Keep track of current messages for this conversation - const conversationMessages = [...modelMessages]; - let stepCount = 0; - - // Main loop for handling multiple steps with tool calls - while (stepCount < maxSteps) { - stepCount++; - console.log(`AI Chat Step ${stepCount}/${maxSteps}`); - - // Initialize streaming message - setStreamingMessage({ - role: 'assistant', - content: '', - tool_calls: undefined - }); - - // Prepare chat completion options - const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = { - model: modelName, - messages: conversationMessages, - tools: tools && Object.keys(tools).length > 0 ? Object.values(tools) : undefined, - tool_choice: tools && Object.keys(tools).length > 0 ? 'auto' : undefined, - stream: true - }; - - // Generate streaming response - const stream = await openai.chat.completions.create(completionOptions, { - signal: abortControllerRef.current.signal - }); - - let accumulatedContent = ''; - const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = []; - let finishReason: string | null = null; - let hasRecordedModel = false; - - // Process the stream - for await (const chunk of stream) { - const delta = chunk.choices[0]?.delta; - - // Track recently used model on first chunk - if (!hasRecordedModel && providerModel) { - addRecentlyUsedModel(providerModel); - hasRecordedModel = true; - } - - if (delta?.content) { - accumulatedContent += delta.content; - setStreamingMessage(prev => prev ? { - ...prev, - content: prev.content + delta.content - } : { - role: 'assistant', - content: delta.content, - tool_calls: undefined - }); - } - - if (delta?.tool_calls) { - for (const toolCallDelta of delta.tool_calls) { - const index = toolCallDelta.index; - if (index !== undefined) { - // Initialize tool call if it doesn't exist - if (!accumulatedToolCalls[index]) { - accumulatedToolCalls[index] = { - id: toolCallDelta.id || '', - type: 'function', - function: { - name: '', - arguments: '' - } - } as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall; - } - - // Update tool call properties - if (toolCallDelta.id) { - accumulatedToolCalls[index].id = toolCallDelta.id; - } - if (toolCallDelta.function?.name && accumulatedToolCalls[index].type === 'function') { - (accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall).function.name = toolCallDelta.function.name; - } - if (toolCallDelta.function?.arguments && accumulatedToolCalls[index].type === 'function') { - (accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall).function.arguments += toolCallDelta.function.arguments; - } - } - } - - // Update streaming message with current tool calls - setStreamingMessage(prev => prev ? { - ...prev, - tool_calls: accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined - } : { - role: 'assistant', - content: accumulatedContent, - tool_calls: accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined - }); - } - - if (chunk.choices[0]?.finish_reason) { - finishReason = chunk.choices[0].finish_reason; - } - } - - // Create final assistant message - const assistantMessage: AIMessage = { - role: 'assistant', - content: accumulatedContent, - ...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls }) - }; - - // Clear streaming message and add final message - setStreamingMessage(undefined); - addMessage(assistantMessage); - conversationMessages.push(assistantMessage); - - // Check if we should stop (no tool calls or finish reason is "stop") - if (finishReason === 'stop' || !accumulatedToolCalls || accumulatedToolCalls.length === 0) { - console.log(`AI Chat completed after ${stepCount} steps. Finish reason: ${finishReason}`); - break; - } - - // Handle tool calls if present - if (accumulatedToolCalls && accumulatedToolCalls.length > 0) { - console.log(`Processing ${accumulatedToolCalls.length} tool calls in step ${stepCount}`); - - for (const toolCall of accumulatedToolCalls) { - if (toolCall.type !== 'function') continue; - - const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall; - const toolName = functionToolCall.function.name; - const tool = customTools[toolName]; - - if (!tool) { - // Tool not found - const toolNotFoundMessage: AIMessage = { - role: 'tool', - content: `Tool ${toolName} not found`, - tool_call_id: functionToolCall.id - }; - - addMessage(toolNotFoundMessage); - conversationMessages.push(toolNotFoundMessage); - continue; - } - - let toolArgs: unknown; - try { - const json = JSON.parse(functionToolCall.function.arguments); - toolArgs = tool.inputSchema.parse(json); - } catch (parseError) { - console.error(`Failed to parse tool arguments for ${toolName}:`, parseError); - - const toolErrorMessage: AIMessage = { - role: 'tool', - content: `Error parsing arguments for tool ${toolName}: ${parseError instanceof Error ? parseError.message : 'Unknown error'}`, - tool_call_id: functionToolCall.id - }; - - addMessage(toolErrorMessage); - conversationMessages.push(toolErrorMessage); - continue; - } - - try { - console.log(`Executing tool: ${toolName}`, toolArgs); - - // Execute the custom tool - const content = await tool.execute(toolArgs); - - // Add tool result message - const toolResultMessage: AIMessage = { - role: 'tool', - content, - tool_call_id: functionToolCall.id - }; - - addMessage(toolResultMessage); - conversationMessages.push(toolResultMessage); - } catch (toolError) { - console.error(`Tool execution error for ${toolName}:`, toolError); - - const toolErrorMessage: AIMessage = { - role: 'tool', - content: `Error executing tool ${toolName}: ${toolError instanceof Error ? toolError.message : 'Unknown error'}`, - tool_call_id: functionToolCall.id - }; - - addMessage(toolErrorMessage); - conversationMessages.push(toolErrorMessage); - } - } - } - } - - // If we reached maxSteps, log a warning - if (stepCount >= maxSteps) { - console.warn(`AI Chat reached maximum steps (${maxSteps}). Conversation may be incomplete.`); - } - - } catch (error) { - console.error('AI chat error:', error); - - // Clear any streaming message on error - setStreamingMessage(undefined); - - // Add error message - const errorMessage: AIMessage = { - role: 'assistant', - content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.' - }; - - addMessage(errorMessage); - } finally { - setIsLoading(false); - abortControllerRef.current = null; - } - }, [isConfigured, isLoading, addMessage, messages, settings.providers, tools, customTools, systemPrompt, onUpdateMetadata, projectName, maxSteps, addRecentlyUsedModel]); - - // Load message history when component mounts or projectId changes - useEffect(() => { - const loadMessageHistory = async () => { - try { - const dotAI = new DotAI(fs, `/projects/${projectId}`); - const lastSession = await dotAI.readLastSessionHistory(); - - if (lastSession) { - setMessages(lastSession.messages); - setSessionName(lastSession.sessionName); - } else { - // No history to load, start fresh - setMessages([]); - setSessionName(DotAI.generateSessionName()); - } - } catch (error) { - console.warn('Failed to load message history:', error); - // Start fresh on any error - setMessages([]); - setSessionName(DotAI.generateSessionName()); - } - }; - - loadMessageHistory(); - }, [projectId, fs]); - - const sendMessage = useCallback(async (content: string, providerModel: string) => { - if (!isConfigured || isLoading) return; - - // Add user message - const userMessage: AIMessage = { - role: 'user', - content - }; - - // Calculate the new messages array that will exist after the state update - const newMessages = [...messages, userMessage]; - - // Add the message to state - addMessage(userMessage); - - // Start generation with the new messages array directly - startGeneration(providerModel, newMessages); - }, [isConfigured, isLoading, messages, addMessage, startGeneration]); - - const stopGeneration = useCallback(() => { - if (abortControllerRef.current) { - abortControllerRef.current.abort(); - } - setStreamingMessage(undefined); - }, []); - - const clearMessages = useCallback(() => { - setMessages([]); - setStreamingMessage(undefined); - // Start a new session when clearing messages - setSessionName(DotAI.generateSessionName()); - }, []); - - const startNewSession = useCallback(() => { - setMessages([]); - setStreamingMessage(undefined); - setSessionName(DotAI.generateSessionName()); - }, []); - - return { - messages, - streamingMessage, - isLoading, - sendMessage, - startGeneration, - stopGeneration, - clearMessages, - startNewSession, - addMessage, - isConfigured - }; -} \ No newline at end of file diff --git a/src/hooks/useAIChatSession.ts b/src/hooks/useAIChatSession.ts index 950c1d77..1dc40179 100644 --- a/src/hooks/useAIChatSession.ts +++ b/src/hooks/useAIChatSession.ts @@ -1,5 +1,6 @@ import { useState, useEffect, useCallback, useMemo } from 'react'; import { useSessionManager } from '@/hooks/useSessionManager'; +import { useSessionSubscription } from '@/hooks/useSessionSubscription'; import { useAISettings } from '@/hooks/useAISettings'; import type { SessionState, SessionConfig, AIMessage } from '@/lib/SessionManager'; import type OpenAI from 'openai'; @@ -89,92 +90,53 @@ export function useAIChatSession({ initSession(); }, [sessionManager, projectId, projectName, tools, customTools, systemPrompt, maxSteps, generatedSessionId]); - // Subscribe to session updates - useEffect(() => { - if (!sessionId) return; + // Update session state efficiently + const updateSessionState = useCallback((state: SessionState) => { + setSessionState({ + ...state, + // Only create new arrays/objects when they actually change + messages: state.messages.slice(), + streamingMessage: state.streamingMessage ? { ...state.streamingMessage } : undefined + }); + }, []); - const handleSessionUpdate = (updatedSessionId: string, state: SessionState) => { - if (updatedSessionId === sessionId) { - // Create a deep copy to ensure React detects the change - const newState = { - ...state, - messages: [...state.messages], - streamingMessage: state.streamingMessage ? { ...state.streamingMessage } : undefined, - abortController: state.abortController - }; - setSessionState(newState); + // Subscribe to session events using shared hook + useSessionSubscription('sessionUpdated', (updatedSessionId: string, state: SessionState) => { + if (updatedSessionId === sessionId) { + updateSessionState(state); + } + }, [sessionId, updateSessionState]); + + useSessionSubscription('messageAdded', (updatedSessionId: string, _message: AIMessage) => { + if (updatedSessionId === sessionId) { + const session = sessionManager.getSession(sessionId); + if (session) { + updateSessionState(session); } - }; + } + }, [sessionId, updateSessionState]); - const handleMessageAdded = (updatedSessionId: string, _message: AIMessage) => { - if (updatedSessionId === sessionId) { - // Get fresh session state and force update by creating new object - const session = sessionManager.getSession(sessionId); - if (session) { - // Create a deep copy to ensure React detects the change - const newState = { - ...session, - messages: [...session.messages], - streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined, - abortController: session.abortController - }; - setSessionState(newState); - } + useSessionSubscription('streamingUpdate', (updatedSessionId: string, _content: string, _toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => { + if (updatedSessionId === sessionId) { + const session = sessionManager.getSession(sessionId); + if (session) { + updateSessionState(session); } - }; + } + }, [sessionId, updateSessionState]); - const handleStreamingUpdate = (updatedSessionId: string, _content: string, _toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => { - if (updatedSessionId === sessionId) { - // Get fresh session state and force update by creating new object - const session = sessionManager.getSession(sessionId); - if (session) { - // Create a deep copy to ensure React detects the change - const newState = { - ...session, - messages: [...session.messages], - streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined, - abortController: session.abortController - }; - setSessionState(newState); - } + useSessionSubscription('loadingChanged', (updatedSessionId: string, isLoading: boolean) => { + if (updatedSessionId === sessionId) { + const session = sessionManager.getSession(sessionId); + if (session) { + updateSessionState(session); } - }; - const handleLoadingChanged = (updatedSessionId: string, isLoading: boolean) => { - if (updatedSessionId === sessionId) { - // Update session state immediately and force update by creating new object - const session = sessionManager.getSession(sessionId); - if (session) { - // Create a deep copy to ensure React detects the change - const newState = { - ...session, - messages: [...session.messages], - streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined, - abortController: session.abortController - }; - setSessionState(newState); - } - - if (onUpdateMetadata) { - if (isLoading) { - onUpdateMetadata('Shakespeare', `Working on ${projectName}...`); - } - } + if (onUpdateMetadata && isLoading) { + onUpdateMetadata('Shakespeare', `Working on ${projectName}...`); } - }; - - sessionManager.on('sessionUpdated', handleSessionUpdate); - sessionManager.on('messageAdded', handleMessageAdded); - sessionManager.on('streamingUpdate', handleStreamingUpdate); - sessionManager.on('loadingChanged', handleLoadingChanged); - - return () => { - sessionManager.off('sessionUpdated', handleSessionUpdate); - sessionManager.off('messageAdded', handleMessageAdded); - sessionManager.off('streamingUpdate', handleStreamingUpdate); - sessionManager.off('loadingChanged', handleLoadingChanged); - }; - }, [sessionId, sessionManager, onUpdateMetadata, projectName]); + } + }, [sessionId, updateSessionState, onUpdateMetadata, projectName]); diff --git a/src/hooks/useSessionSubscription.ts b/src/hooks/useSessionSubscription.ts new file mode 100644 index 00000000..7d13ca06 --- /dev/null +++ b/src/hooks/useSessionSubscription.ts @@ -0,0 +1,22 @@ +import { useEffect } from 'react'; +import { useSessionManager } from './useSessionManager'; +import type { SessionManagerEvents } from '@/lib/SessionManager'; + +/** + * Custom hook for subscribing to SessionManager events with automatic cleanup + */ +export function useSessionSubscription( + event: K, + handler: SessionManagerEvents[K], + deps: React.DependencyList = [] +): void { + const sessionManager = useSessionManager(); + + useEffect(() => { + sessionManager.on(event, handler); + + return () => { + sessionManager.off(event, handler); + }; + }, [sessionManager, event, handler, ...deps]); // eslint-disable-line react-hooks/exhaustive-deps +} \ No newline at end of file diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 241a067d..90679cb1 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -4,6 +4,15 @@ import { DotAI } from './DotAI'; import { parseProviderModel } from './parseProviderModel'; import type { Tool } from './tools/Tool'; +// Simple debounce utility +function debounce void>(func: T, wait: number): T { + let timeout: NodeJS.Timeout; + return ((...args: Parameters) => { + clearTimeout(timeout); + timeout = setTimeout(() => func(...args), wait); + }) as T; +} + export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam; export interface SessionConfig { @@ -56,6 +65,11 @@ export class SessionManager { providers: Record; }; + // Performance and memory management + private readonly MAX_SESSIONS = 50; + private readonly MAX_SESSION_AGE = 7 * 24 * 60 * 60 * 1000; // 7 days + private debouncedPersist = debounce(this.persistSessions.bind(this), 1000); + constructor(fs: JSRuntimeFS, aiSettings: { providers: Record }) { this.fs = fs; this.aiSettings = aiSettings; @@ -165,10 +179,14 @@ export class SessionManager { // Save to history await this.saveSessionHistory(sessionId); - this.persistSessions(); + // Use debounced persistence for performance + this.debouncedPersist(); this.emit('messageAdded', sessionId, message); this.emit('sessionUpdated', sessionId, session); + + // Clean up old sessions periodically + this.cleanupOldSessions(); } /** @@ -410,13 +428,32 @@ export class SessionManager { } catch (error) { console.error('AI generation error:', error); - // Add error message - const errorMessage: AIMessage = { + // Handle different types of errors appropriately + let errorMessage: string; + if (error && typeof error === 'object' && 'name' in error) { + if (error.name === 'AbortError') { + // User cancelled the request - don't add error message + return; + } else if (error.name === 'TypeError' && error.message.includes('fetch')) { + errorMessage = 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.'; + } else if (error.message?.includes('API key')) { + errorMessage = 'Authentication error: Please check your API key in AI settings.'; + } else if (error.message?.includes('rate limit')) { + errorMessage = 'Rate limit exceeded. Please wait a moment before trying again.'; + } else { + errorMessage = `AI service error: ${error.message || 'Unknown error occurred'}`; + } + } else { + errorMessage = 'Sorry, I encountered an unexpected error. Please try again.'; + } + + // Add user-friendly error message + const errorAIMessage: AIMessage = { role: 'assistant', - content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.' + content: errorMessage }; - await this.addMessage(sessionId, errorMessage); + await this.addMessage(sessionId, errorAIMessage); } finally { session.isLoading = false; session.streamingMessage = undefined; @@ -446,6 +483,35 @@ export class SessionManager { this.emit('sessionUpdated', sessionId, session); } + /** + * Clean up old sessions to prevent memory bloat + */ + private cleanupOldSessions(): void { + const now = Date.now(); + const sessionIdsToDelete: string[] = []; + + for (const [id, session] of this.sessions) { + if (now - session.lastActivity.getTime() > this.MAX_SESSION_AGE) { + sessionIdsToDelete.push(id); + } + } + + // Delete old sessions + sessionIdsToDelete.forEach(id => this.deleteSession(id)); + + // If we still have too many sessions, delete the oldest ones + if (this.sessions.size > this.MAX_SESSIONS) { + const sortedSessions = Array.from(this.sessions.entries()) + .sort(([, a], [, b]) => a.lastActivity.getTime() - b.lastActivity.getTime()); + + const sessionsToDelete = sortedSessions + .slice(0, this.sessions.size - this.MAX_SESSIONS) + .map(([id]) => id); + + sessionsToDelete.forEach(id => this.deleteSession(id)); + } + } + /** * Start a new session (clear messages but keep configuration) */ @@ -462,7 +528,7 @@ export class SessionManager { session.sessionName = DotAI.generateSessionName(); session.lastActivity = new Date(); - this.persistSessions(); + this.debouncedPersist(); this.emit('sessionUpdated', sessionId, session); } diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index f1509fbb..be4d80ea 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -9,7 +9,7 @@ import { useIsMobile } from '@/hooks/useIsMobile'; import { useAISettings } from '@/hooks/useAISettings'; import { AppLayout } from '@/components/AppLayout'; import { DotAI } from '@/lib/DotAI'; -import type { AIMessage } from '@/hooks/useAIChat'; +import type { AIMessage } from '@/lib/SessionManager'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea';