From af6942c04f98992062b09151ef6df23c05e25e53 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 11 Sep 2025 12:42:34 -0500 Subject: [PATCH] Sessions should be keyed by projectId, not a generated ID --- src/components/SessionMonitor.tsx | 20 ++-- src/hooks/useAIChat.ts | 96 +++++++---------- src/hooks/useProjectSessionStatus.ts | 7 +- src/lib/SessionManager.ts | 147 +++++++++++++-------------- 4 files changed, 121 insertions(+), 149 deletions(-) diff --git a/src/components/SessionMonitor.tsx b/src/components/SessionMonitor.tsx index d54bf781..302cf6fc 100644 --- a/src/components/SessionMonitor.tsx +++ b/src/components/SessionMonitor.tsx @@ -15,13 +15,13 @@ export function SessionMonitor() { const previousLoadingStates = useRef>(new Map()); useEffect(() => { - const handleLoadingChanged = (sessionId: string, isLoading: boolean) => { - const wasLoading = previousLoadingStates.current.get(sessionId); - previousLoadingStates.current.set(sessionId, isLoading); + const handleLoadingChanged = (projectId: string, isLoading: boolean) => { + const wasLoading = previousLoadingStates.current.get(projectId); + previousLoadingStates.current.set(projectId, isLoading); // If session just finished loading (was loading, now not loading) if (wasLoading && !isLoading) { - const session = sessionManager.getSession(sessionId); + const session = sessionManager.getSession(projectId); if (!session) return; // Check if user is currently viewing this project @@ -46,20 +46,20 @@ export function SessionMonitor() { } }; - const handleSessionCreated = (sessionId: string) => { - const session = sessionManager.getSession(sessionId); + const handleSessionCreated = (projectId: string) => { + const session = sessionManager.getSession(projectId); if (session) { - previousLoadingStates.current.set(sessionId, session.isLoading); + previousLoadingStates.current.set(projectId, session.isLoading); } }; - const handleSessionDeleted = (sessionId: string) => { - previousLoadingStates.current.delete(sessionId); + const handleSessionDeleted = (projectId: string) => { + previousLoadingStates.current.delete(projectId); }; // Initialize with current sessions sessionManager.getAllSessions().forEach(session => { - previousLoadingStates.current.set(session.id, session.isLoading); + previousLoadingStates.current.set(session.projectId, session.isLoading); }); // Subscribe to events diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts index f0efe2f2..a313d999 100644 --- a/src/hooks/useAIChat.ts +++ b/src/hooks/useAIChat.ts @@ -1,4 +1,4 @@ -import { useState, useEffect, useCallback, useMemo } from 'react'; +import { useState, useEffect, useCallback } from 'react'; import { useSessionManager } from '@/hooks/useSessionManager'; import { useSessionSubscription } from '@/hooks/useSessionSubscription'; import { useAISettings } from '@/hooks/useAISettings'; @@ -35,7 +35,6 @@ export function useAIChat({ }: UseAIChatSessionOptions) { const sessionManager = useSessionManager(); const { isConfigured } = useAISettings(); - const [sessionId, setSessionId] = useState(''); // Split session state into individual variables for efficient updates const [messages, setMessages] = useState([]); @@ -44,34 +43,22 @@ export function useAIChat({ const [totalCost, setTotalCost] = useState(0); const [lastInputTokens, setLastInputTokens] = useState(0); - // Generate consistent session ID for this project - const generatedSessionId = useMemo(() => { - return `session-${projectId}`; - }, [projectId]); - // Initialize session useEffect(() => { const initSession = async () => { // Check if there's already an active session for this project - const existingSessions = sessionManager.getProjectSessions(projectId); - - if (existingSessions.length > 0) { - // Use the most recent session for this project - const mostRecent = existingSessions - .sort((a, b) => b.lastActivity.getTime() - a.lastActivity.getTime())[0]; - - setSessionId(mostRecent.id); + const existingSession = sessionManager.getProjectSession(projectId); + if (existingSession) { // Initialize individual state variables from existing session - setMessages([...mostRecent.messages]); - setStreamingMessage(mostRecent.streamingMessage ? { ...mostRecent.streamingMessage } : undefined); - setIsLoading(mostRecent.isLoading); - setTotalCost(mostRecent.totalCost || 0); - setLastInputTokens(mostRecent.lastInputTokens || 0); + setMessages([...existingSession.messages]); + setStreamingMessage(existingSession.streamingMessage ? { ...existingSession.streamingMessage } : undefined); + setIsLoading(existingSession.isLoading); + setTotalCost(existingSession.totalCost || 0); + setLastInputTokens(existingSession.lastInputTokens || 0); } else { // Create new session const config: SessionConfig = { - id: generatedSessionId, projectId, tools, customTools, @@ -79,10 +66,9 @@ export function useAIChat({ maxSteps }; - const newSessionId = await sessionManager.createSession(config); - setSessionId(newSessionId); + await sessionManager.createSession(config); - const newSession = sessionManager.getSession(newSessionId); + const newSession = sessionManager.getSession(projectId); if (newSession) { // Initialize individual state variables from new session setMessages([...newSession.messages]); @@ -95,27 +81,27 @@ export function useAIChat({ }; initSession(); - }, [sessionManager, projectId, tools, customTools, systemPrompt, maxSteps, generatedSessionId]); + }, [sessionManager, projectId, tools, customTools, systemPrompt, maxSteps]); // Subscribe to atomic session events for efficient updates - useSessionSubscription('messageAdded', (updatedSessionId: string, message: AIMessage) => { - if (updatedSessionId === sessionId) { + useSessionSubscription('messageAdded', (updatedProjectId: string, message: AIMessage) => { + if (updatedProjectId === projectId) { setMessages(prev => [...prev, message]); } - }, [sessionId]); + }, [projectId]); - useSessionSubscription('streamingUpdate', (updatedSessionId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => { - if (updatedSessionId === sessionId) { + useSessionSubscription('streamingUpdate', (updatedProjectId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => { + if (updatedProjectId === projectId) { setStreamingMessage({ role: 'assistant', content, tool_calls: toolCalls }); } - }, [sessionId]); + }, [projectId]); - useSessionSubscription('loadingChanged', (updatedSessionId: string, loading: boolean) => { - if (updatedSessionId === sessionId) { + useSessionSubscription('loadingChanged', (updatedProjectId: string, loading: boolean) => { + if (updatedProjectId === projectId) { setIsLoading(loading); // Clear streaming message when loading stops @@ -127,34 +113,31 @@ export function useAIChat({ onUpdateMetadata('Shakespeare', `Working on ${projectId}...`); } } - }, [sessionId, onUpdateMetadata, projectId]); + }, [projectId, onUpdateMetadata]); - useSessionSubscription('costUpdated', (updatedSessionId: string, cost: number) => { - if (updatedSessionId === sessionId) { + useSessionSubscription('costUpdated', (updatedProjectId: string, cost: number) => { + if (updatedProjectId === projectId) { setTotalCost(cost); } - }, [sessionId]); + }, [projectId]); - useSessionSubscription('contextUsageUpdated', (updatedSessionId: string, inputTokens: number) => { - if (updatedSessionId === sessionId) { + useSessionSubscription('contextUsageUpdated', (updatedProjectId: string, inputTokens: number) => { + if (updatedProjectId === projectId) { setLastInputTokens(inputTokens); } - }, [sessionId]); + }, [projectId]); // Actions const sendMessage = useCallback(async (content: string, providerModel: string) => { - if (!sessionId) return; - await sessionManager.sendMessage(sessionId, content, providerModel); - }, [sessionId, sessionManager]); + await sessionManager.sendMessage(projectId, content, providerModel); + }, [projectId, sessionManager]); const startGeneration = useCallback(async (providerModel: string, messagesToUse?: AIMessage[]) => { - if (!sessionId) return; - // If specific messages are provided, we need to update the session first if (messagesToUse) { - const session = sessionManager.getSession(sessionId); + const session = sessionManager.getSession(projectId); if (session) { // Replace session messages with provided messages session.messages = [...messagesToUse]; @@ -164,29 +147,26 @@ export function useAIChat({ } } - await sessionManager.startGeneration(sessionId, providerModel); - }, [sessionId, sessionManager]); + await sessionManager.startGeneration(projectId, providerModel); + }, [projectId, sessionManager]); const stopGeneration = useCallback(() => { - if (!sessionId) return; - sessionManager.stopGeneration(sessionId); - }, [sessionId, sessionManager]); + sessionManager.stopGeneration(projectId); + }, [projectId, sessionManager]); const addMessage = useCallback(async (message: AIMessage) => { - if (!sessionId) return; - await sessionManager.addMessage(sessionId, message); - }, [sessionId, sessionManager]); + await sessionManager.addMessage(projectId, message); + }, [projectId, sessionManager]); const startNewSession = useCallback(async () => { - if (!sessionId) return; - await sessionManager.startNewSession(sessionId); + await sessionManager.startNewSession(projectId); // Reset individual state variables setMessages([]); setStreamingMessage(undefined); setTotalCost(0); setLastInputTokens(0); - }, [sessionId, sessionManager]); + }, [projectId, sessionManager]); const clearMessages = useCallback(async () => { // Alias for startNewSession for backward compatibility @@ -206,6 +186,6 @@ export function useAIChat({ startNewSession, addMessage, isConfigured, - sessionId + projectId }; } \ No newline at end of file diff --git a/src/hooks/useProjectSessionStatus.ts b/src/hooks/useProjectSessionStatus.ts index c139e01e..0593d4e4 100644 --- a/src/hooks/useProjectSessionStatus.ts +++ b/src/hooks/useProjectSessionStatus.ts @@ -11,11 +11,10 @@ export function useProjectSessionStatus(projectId: string) { useEffect(() => { const updateStatus = () => { - const projectSessions = sessionManager.getProjectSessions(projectId); - const runningSessions = projectSessions.filter(session => session.isLoading); + const projectSession = sessionManager.getProjectSession(projectId); - setHasActiveSessions(projectSessions.length > 0); - setHasRunningSessions(runningSessions.length > 0); + setHasActiveSessions(!!projectSession); + setHasRunningSessions(!!projectSession?.isLoading); }; // Initial update diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 23b75dc9..81c74740 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -7,7 +7,6 @@ import type { Tool } from './tools/Tool'; export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam; export interface SessionConfig { - id: string; projectId: string; tools: Record; customTools: Record>; @@ -16,7 +15,6 @@ export interface SessionConfig { } export interface SessionState { - id: string; projectId: string; messages: AIMessage[]; streamingMessage?: { @@ -33,18 +31,18 @@ export interface SessionState { } export interface SessionManagerEvents { - sessionCreated: (sessionId: string) => void; - sessionDeleted: (sessionId: string) => void; - messageAdded: (sessionId: string, message: AIMessage) => void; - streamingUpdate: (sessionId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void; - loadingChanged: (sessionId: string, isLoading: boolean) => void; - costUpdated: (sessionId: string, totalCost: number) => void; - contextUsageUpdated: (sessionId: string, inputTokens: number) => void; + sessionCreated: (projectId: string) => void; + sessionDeleted: (projectId: string) => void; + messageAdded: (projectId: string, message: AIMessage) => void; + streamingUpdate: (projectId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void; + loadingChanged: (projectId: string, isLoading: boolean) => void; + costUpdated: (projectId: string, totalCost: number) => void; + contextUsageUpdated: (projectId: string, inputTokens: number) => void; } /** - * Global session manager that handles multiple AI chat sessions running concurrently. - * Sessions can run in the background without interruption when switching between projects. + * Global session manager that handles AI chat sessions keyed by project ID. + * Only one session can be active per project at once. */ export class SessionManager { private sessions = new Map(); @@ -73,7 +71,6 @@ export class SessionManager { */ async createSession(config: SessionConfig): Promise { const sessionState: SessionState = { - id: config.id, projectId: config.projectId, messages: [], isLoading: false, @@ -95,19 +92,19 @@ export class SessionManager { console.warn('Failed to load session history:', error); } - this.sessions.set(config.id, sessionState); - this.sessionConfigs.set(config.id, config); + this.sessions.set(config.projectId, sessionState); + this.sessionConfigs.set(config.projectId, config); - this.emit('sessionCreated', config.id); + this.emit('sessionCreated', config.projectId); - return config.id; + return config.projectId; } /** - * Get a session by ID + * Get a session by project ID */ - getSession(sessionId: string): SessionState | undefined { - return this.sessions.get(sessionId); + getSession(projectId: string): SessionState | undefined { + return this.sessions.get(projectId); } /** @@ -118,71 +115,67 @@ export class SessionManager { } /** - * Get sessions for a specific project + * Get session for a specific project */ - getProjectSessions(projectId: string): SessionState[] { - return Array.from(this.sessions.values()).filter( - session => session.projectId === projectId - ); + getProjectSession(projectId: string): SessionState | undefined { + return this.sessions.get(projectId); } /** * Delete a session */ - async deleteSession(sessionId: string): Promise { - const session = this.sessions.get(sessionId); + async deleteSession(projectId: string): Promise { + const session = this.sessions.get(projectId); session?.abortController?.abort(); - this.sessions.delete(sessionId); - this.sessionConfigs.delete(sessionId); + this.sessions.delete(projectId); + this.sessionConfigs.delete(projectId); - this.emit('sessionDeleted', sessionId); + this.emit('sessionDeleted', projectId); } /** - * Delete all sessions for a project + * Delete session for a project */ - async deleteProjectSessions(projectId: string): Promise { - await Promise.all( - this.getProjectSessions(projectId).map(session => this.deleteSession(session.id)) - ); + async deleteProjectSession(projectId: string): Promise { + await this.deleteSession(projectId); } /** * Add a message to a session */ - async addMessage(sessionId: string, message: AIMessage): Promise { - const session = this.sessions.get(sessionId); + async addMessage(projectId: string, message: AIMessage): Promise { + const session = this.sessions.get(projectId); if (!session) return; session.messages.push(message); session.lastActivity = new Date(); - await this.saveSessionHistory(sessionId); + await this.saveSessionHistory(projectId); this.cleanupOldSessions(); - this.emit('messageAdded', sessionId, message); + this.emit('messageAdded', projectId, message); } /** * Send a message and start AI generation */ - async sendMessage(sessionId: string, content: string, providerModel: string): Promise { - const session = this.sessions.get(sessionId); - const config = this.sessionConfigs.get(sessionId); + async sendMessage(projectId: string, content: string, providerModel: string): Promise { + const session = this.sessions.get(projectId); + const config = this.sessionConfigs.get(projectId); if (!session || !config || session.isLoading) return; - await this.addMessage(sessionId, { role: 'user', content }); - await this.startGeneration(sessionId, providerModel); + await this.addMessage(projectId, { role: 'user', content }); + await this.startGeneration(projectId, providerModel); } /** * Start AI generation for a session */ - async startGeneration(sessionId: string, providerModel: string): Promise { - const session = this.sessions.get(sessionId); - const config = this.sessionConfigs.get(sessionId); + async startGeneration(projectId: string, providerModel: string): Promise { + const session = this.sessions.get(projectId); + const config = this.sessionConfigs.get(projectId); if (!session || !config || session.isLoading || session.messages.length === 0) return; @@ -194,7 +187,7 @@ export class SessionManager { session.abortController = new AbortController(); session.lastActivity = new Date(); - this.emit('loadingChanged', sessionId, true); + this.emit('loadingChanged', projectId, true); try { // Parse provider and model @@ -263,7 +256,7 @@ export class SessionManager { accumulatedContent += delta.content; if (session.streamingMessage) { session.streamingMessage.content += delta.content; - this.emit('streamingUpdate', sessionId, session.streamingMessage.content, session.streamingMessage.tool_calls); + this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.tool_calls); } } @@ -286,7 +279,7 @@ export class SessionManager { if (session.streamingMessage) { session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined; - this.emit('streamingUpdate', sessionId, session.streamingMessage.content, session.streamingMessage.tool_calls); + this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.tool_calls); } } @@ -315,15 +308,15 @@ export class SessionManager { session.lastActivity = new Date(); // Save and emit all updates together - await this.saveSessionHistory(sessionId); + await this.saveSessionHistory(projectId); this.cleanupOldSessions(); - this.emit('messageAdded', sessionId, assistantMessage); + this.emit('messageAdded', projectId, assistantMessage); conversationMessages.push(assistantMessage); // Update cost if usage data is available if (usage) { - this.updateSessionCost(sessionId, usage, providerModel); + this.updateSessionCost(projectId, usage, providerModel); } // Check if we should stop @@ -341,17 +334,17 @@ export class SessionManager { const tool = config.customTools[toolName]; if (!tool) { - await this.addToolMessage(sessionId, conversationMessages, functionToolCall.id, `Tool ${toolName} not found`); + await this.addToolMessage(projectId, conversationMessages, functionToolCall.id, `Tool ${toolName} not found`); continue; } try { const toolArgs = tool.inputSchema.parse(JSON.parse(functionToolCall.function.arguments)); const content = await tool.execute(toolArgs); - await this.addToolMessage(sessionId, conversationMessages, functionToolCall.id, content); + await this.addToolMessage(projectId, conversationMessages, functionToolCall.id, content); } catch (error) { const errorMsg = error instanceof Error ? error.message : 'Unknown error'; - await this.addToolMessage(sessionId, conversationMessages, functionToolCall.id, `Error with tool ${toolName}: ${errorMsg}`); + await this.addToolMessage(projectId, conversationMessages, functionToolCall.id, `Error with tool ${toolName}: ${errorMsg}`); } } } @@ -376,21 +369,21 @@ export class SessionManager { errorMessage = `AI service error: ${errorMsg}`; } - await this.addMessage(sessionId, { role: 'assistant', content: errorMessage }); + await this.addMessage(projectId, { role: 'assistant', content: errorMessage }); } finally { session.isLoading = false; session.streamingMessage = undefined; session.abortController = undefined; - this.emit('loadingChanged', sessionId, false); + this.emit('loadingChanged', projectId, false); } } /** * Stop AI generation for a session */ - stopGeneration(sessionId: string): void { - const session = this.sessions.get(sessionId); + stopGeneration(projectId: string): void { + const session = this.sessions.get(projectId); if (!session) return; session.abortController?.abort(); @@ -398,7 +391,7 @@ export class SessionManager { session.streamingMessage = undefined; session.abortController = undefined; - this.emit('loadingChanged', sessionId, false); + this.emit('loadingChanged', projectId, false); } /** @@ -408,9 +401,9 @@ export class SessionManager { const now = Date.now(); // Delete old sessions - for (const [id, session] of this.sessions) { + for (const [projectId, session] of this.sessions) { if (now - session.lastActivity.getTime() > this.MAX_SESSION_AGE) { - this.deleteSession(id); + this.deleteSession(projectId); } } @@ -419,18 +412,18 @@ export class SessionManager { Array.from(this.sessions.entries()) .sort(([, a], [, b]) => a.lastActivity.getTime() - b.lastActivity.getTime()) .slice(0, this.sessions.size - this.MAX_SESSIONS) - .forEach(([id]) => this.deleteSession(id)); + .forEach(([projectId]) => this.deleteSession(projectId)); } } /** * Start a new session (clear messages but keep configuration) */ - async startNewSession(sessionId: string): Promise { - const session = this.sessions.get(sessionId); + async startNewSession(projectId: string): Promise { + const session = this.sessions.get(projectId); if (!session) return; - this.stopGeneration(sessionId); + this.stopGeneration(projectId); session.messages = []; session.streamingMessage = undefined; @@ -439,31 +432,31 @@ export class SessionManager { session.totalCost = 0; session.lastInputTokens = 0; - this.emit('costUpdated', sessionId, 0); - this.emit('contextUsageUpdated', sessionId, 0); + this.emit('costUpdated', projectId, 0); + this.emit('contextUsageUpdated', projectId, 0); } /** * Helper to add tool messages and update conversation */ - private async addToolMessage(sessionId: string, conversationMessages: AIMessage[], toolCallId: string, content: string): Promise { + private async addToolMessage(projectId: string, conversationMessages: AIMessage[], toolCallId: string, content: string): Promise { const toolMessage: AIMessage = { role: 'tool', content, tool_call_id: toolCallId }; - await this.addMessage(sessionId, toolMessage); + await this.addMessage(projectId, toolMessage); conversationMessages.push(toolMessage); } /** * Update session cost and context usage based on usage data */ - private updateSessionCost(sessionId: string, usage: { prompt_tokens: number; completion_tokens: number }, providerModel: string): void { + private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number }, providerModel: string): void { if (!this.getProviderModels) return; - const session = this.sessions.get(sessionId); + const session = this.sessions.get(projectId); if (!session) return; try { @@ -477,7 +470,7 @@ export class SessionManager { // Update input tokens for context usage tracking session.lastInputTokens = usage.prompt_tokens; - this.emit('contextUsageUpdated', sessionId, usage.prompt_tokens); + this.emit('contextUsageUpdated', projectId, usage.prompt_tokens); if (!model?.pricing) { return; @@ -491,7 +484,7 @@ export class SessionManager { // Update session total cost session.totalCost = (session.totalCost || 0) + requestCost; - this.emit('costUpdated', sessionId, session.totalCost); + this.emit('costUpdated', projectId, session.totalCost); } catch (error) { console.warn('Failed to calculate session cost:', error); } @@ -500,8 +493,8 @@ export class SessionManager { /** * Save session history to file */ - private async saveSessionHistory(sessionId: string): Promise { - const session = this.sessions.get(sessionId); + private async saveSessionHistory(projectId: string): Promise { + const session = this.sessions.get(projectId); if (!session) return; try { @@ -538,7 +531,7 @@ export class SessionManager { * Cleanup - stop all sessions and clear data */ async cleanup(): Promise { - this.sessions.forEach((_, sessionId) => this.stopGeneration(sessionId)); + this.sessions.forEach((_, projectId) => this.stopGeneration(projectId)); this.sessions.clear(); this.sessionConfigs.clear();