From ba2cfe7b6876f17c62a7f9bba6f849baac8f80e7 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 11 Sep 2025 15:44:42 -0500 Subject: [PATCH] Fix loading project --- src/components/Shakespeare/ChatPane.tsx | 18 ++++--- src/hooks/useAIChat.ts | 65 ++++++++----------------- src/lib/SessionManager.ts | 58 ++++++++++++++-------- 3 files changed, 69 insertions(+), 72 deletions(-) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 7df319ea..a409f0b9 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -199,7 +199,7 @@ export const ChatPane = forwardRef(({ const autostart = searchParams.get('autostart'); const urlModel = searchParams.get('model'); - if (autostart === 'true' && isConfigured && !isLoading) { + if (autostart === 'true' && isConfigured) { // Use model from URL if available, otherwise use current selection const modelToUse = urlModel?.trim() || providerModel.trim(); @@ -220,7 +220,7 @@ export const ChatPane = forwardRef(({ startGeneration(modelToUse); } } - }, [addRecentlyUsedModel, isConfigured, isLoading, providerModel, searchParams, setSearchParams, startGeneration]); + }, [addRecentlyUsedModel, isConfigured, providerModel, searchParams, setSearchParams, startGeneration]); // Function to check if user is at the bottom of the scroll area const checkScrollPosition = () => { @@ -376,14 +376,16 @@ export const ChatPane = forwardRef(({ isCurrentlyLoading={isLoading} /> ) : ( -
-
-
- - + !(streamingMessage?.tool_calls?.[0]?.type === 'function') && ( +
+
+
+ + +
-
+ ) ) )} {streamingMessage?.tool_calls?.[0]?.type === 'function' && ( diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts index b48e171c..52af4cdb 100644 --- a/src/hooks/useAIChat.ts +++ b/src/hooks/useAIChat.ts @@ -43,37 +43,21 @@ export function useAIChat({ const [totalCost, setTotalCost] = useState(0); const [lastInputTokens, setLastInputTokens] = useState(0); + const initSession = useCallback(async () => { + // Load or update session + const session = await sessionManager.loadSession(projectId, tools, customTools, systemPrompt, maxSteps); + // Initialize individual state variables from existing session + setMessages([...session.messages]); + setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined); + setIsLoading(session.isLoading); + setTotalCost(session.totalCost || 0); + setLastInputTokens(session.lastInputTokens || 0); + }, [sessionManager, projectId, tools, customTools, systemPrompt, maxSteps]); + // Initialize session useEffect(() => { - const initSession = async () => { - // Check if there's already an active session for this project - const existingSession = sessionManager.getSession(projectId); - - if (existingSession) { - // Initialize individual state variables from existing session - setMessages([...existingSession.messages]); - setStreamingMessage(existingSession.streamingMessage ? { ...existingSession.streamingMessage } : undefined); - setIsLoading(existingSession.isLoading); - setTotalCost(existingSession.totalCost || 0); - setLastInputTokens(existingSession.lastInputTokens || 0); - } else { - // Create new session - await sessionManager.createSession(projectId, tools, customTools, systemPrompt, maxSteps); - - const newSession = sessionManager.getSession(projectId); - if (newSession) { - // Initialize individual state variables from new session - setMessages([...newSession.messages]); - setStreamingMessage(newSession.streamingMessage ? { ...newSession.streamingMessage } : undefined); - setIsLoading(newSession.isLoading); - setTotalCost(newSession.totalCost || 0); - setLastInputTokens(newSession.lastInputTokens || 0); - } - } - }; - initSession(); - }, [sessionManager, projectId, tools, customTools, maxSteps, systemPrompt]); + }, [initSession]); // Subscribe to atomic session events for efficient updates useSessionSubscription('messageAdded', (updatedProjectId: string, message: AIMessage) => { @@ -81,7 +65,10 @@ export function useAIChat({ setMessages(prev => [...prev, message]); // Whenever an assistant message is added, it means streaming is done (until we get another streamingUpdate) if (message.role === 'assistant') { - setStreamingMessage(undefined); + setStreamingMessage({ + role: 'assistant', + content: '', + }); } } }, [projectId]); @@ -125,24 +112,14 @@ export function useAIChat({ // Actions const sendMessage = useCallback(async (content: string, providerModel: string) => { + await initSession(); await sessionManager.sendMessage(projectId, content, providerModel); - }, [projectId, sessionManager]); - - const startGeneration = useCallback(async (providerModel: string, messagesToUse?: AIMessage[]) => { - // If specific messages are provided, we need to update the session first - if (messagesToUse) { - const session = sessionManager.getSession(projectId); - if (session) { - // Replace session messages with provided messages - session.messages = [...messagesToUse]; - - // Update local state to match - setMessages([...messagesToUse]); - } - } + }, [projectId, sessionManager, initSession]); + const startGeneration = useCallback(async (providerModel: string) => { + await initSession(); await sessionManager.startGeneration(projectId, providerModel); - }, [projectId, sessionManager]); + }, [projectId, sessionManager, initSession]); const stopGeneration = useCallback(() => { sessionManager.stopGeneration(projectId); diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index d0e98903..bdd0d744 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -60,44 +60,56 @@ export class SessionManager { /** * Create a new session for a project */ - async createSession( + async loadSession( projectId: string, tools: Record, customTools: Record>, systemPrompt?: string, maxSteps?: number - ): Promise { - const sessionState: SessionState = { - projectId, - tools, - customTools, - systemPrompt, - maxSteps, - messages: [], - isLoading: false, - sessionName: DotAI.generateSessionName(), - lastActivity: new Date(), - totalCost: 0, - lastInputTokens: 0, - }; + ): Promise { + let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = []; + let sessionName = DotAI.generateSessionName(); // Try to load existing history try { const dotAI = new DotAI(this.fs, `/projects/${projectId}`); const lastSession = await dotAI.readLastSessionHistory(); if (lastSession) { - sessionState.messages = lastSession.messages; - sessionState.sessionName = lastSession.sessionName; + messages = lastSession.messages; + sessionName = lastSession.sessionName; } } catch (error) { console.warn('Failed to load session history:', error); } - this.sessions.set(projectId, sessionState); + const session = this.sessions.get(projectId) ?? { + projectId, + tools, + customTools, + systemPrompt, + maxSteps, + isLoading: false, + lastActivity: new Date(), + totalCost: 0, + lastInputTokens: 0, + ...this.sessions.get(projectId), + messages, + sessionName, + }; + + // Update session configuration + session.projectId = projectId; + session.tools = tools; + + session.customTools = customTools; + session.systemPrompt = systemPrompt; + session.maxSteps = maxSteps; + + this.sessions.set(projectId, session); this.emit('sessionCreated', projectId); - return projectId; + return session; } /** @@ -158,7 +170,12 @@ export class SessionManager { async startGeneration(projectId: string, providerModel: string): Promise { let session = this.sessions.get(projectId); - if (!session || session.isLoading || session.messages.length === 0) return; + if (!session) { + throw new Error('Session not found'); + } + if (session.messages.length === 0) { + throw new Error('No messages in session'); + } // Check if last message is from user const lastMessage = session.messages[session.messages.length - 1]; @@ -167,6 +184,7 @@ export class SessionManager { session.isLoading = true; session.abortController = new AbortController(); session.lastActivity = new Date(); + this.sessions.set(projectId, session); this.emit('loadingChanged', projectId, true);