From 5875771de334855fa4d0d81c11da7f271249f91c Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 24 Aug 2025 16:53:48 -0500 Subject: [PATCH] DotAI: addToHistory -> setHistory --- src/hooks/useAIChat.ts | 19 +++++---- src/lib/DotAI.test.ts | 85 ++++++++++++++++++++++++++++++++++++++ src/lib/DotAI.ts | 23 +++++------ src/lib/ProjectsManager.ts | 7 ++++ 4 files changed, 113 insertions(+), 21 deletions(-) diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts index a0fd5360..772b73ad 100644 --- a/src/hooks/useAIChat.ts +++ b/src/hooks/useAIChat.ts @@ -31,23 +31,26 @@ export function useAIChat({ const { settings, isConfigured } = useAISettings(); const { fs } = useFS(); - // Save message to history - const saveMessageToHistory = useCallback(async (message: AIMessage) => { + // Save all messages to history + const saveMessagesToHistory = useCallback(async (allMessages: AIMessage[]) => { if (!sessionName) return; try { const dotAI = new DotAI(fs, `/projects/${projectId}`); - await dotAI.addToHistory(sessionName, message); + await dotAI.setHistory(sessionName, allMessages); } catch (error) { - console.warn('Failed to save message to history:', error); + console.warn('Failed to save messages to history:', error); } }, [fs, projectId, sessionName]); const addMessage = useCallback((message: AIMessage) => { - setMessages(prev => [...prev, message]); - // Save to history asynchronously - saveMessageToHistory(message); - }, [saveMessageToHistory]); + setMessages(prev => { + const newMessages = [...prev, message]; + // Save to history asynchronously with all messages + saveMessagesToHistory(newMessages); + return newMessages; + }); + }, [saveMessagesToHistory]); // Load message history when component mounts or projectId changes useEffect(() => { diff --git a/src/lib/DotAI.test.ts b/src/lib/DotAI.test.ts index 58c453d3..8543349b 100644 --- a/src/lib/DotAI.test.ts +++ b/src/lib/DotAI.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { DotAI } from './DotAI'; import type { JSRuntimeFS } from './JSRuntime'; +import type OpenAI from 'openai'; // Mock filesystem const createMockFS = (): JSRuntimeFS => ({ @@ -105,6 +106,90 @@ invalid json line }); }); + describe('setHistory', () => { + it('should not save when AI is not enabled', async () => { + // Mock isEnabled to return false + vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(false); + + const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [ + { role: 'user', content: 'Hello' }, + { role: 'assistant', content: 'Hi there!' } + ]; + + await dotAI.setHistory('test-session', messages); + + // Verify writeFile was not called + expect(mockFS.writeFile).not.toHaveBeenCalled(); + }); + + it('should create history directory if it does not exist', async () => { + // Mock isEnabled to return true + vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true); + // Mock historyDirExists to return false initially + vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false); + // Mock setupAiHistoryDir + vi.spyOn(dotAI, 'setupAiHistoryDir').mockResolvedValue(); + + const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [ + { role: 'user', content: 'Hello' } + ]; + + await dotAI.setHistory('test-session', messages); + + // Verify setupAiHistoryDir was called + expect(dotAI.setupAiHistoryDir).toHaveBeenCalled(); + }); + + it('should write messages as JSONL format', async () => { + // Mock isEnabled to return true + vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true); + // Mock historyDirExists to return true + vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true); + + const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [ + { role: 'user', content: 'Hello' }, + { role: 'assistant', content: 'Hi there!' } + ]; + + await dotAI.setHistory('test-session', messages); + + // Verify writeFile was called with correct content + expect(mockFS.writeFile).toHaveBeenCalledWith( + '/test-project/.ai/history/test-session.jsonl', + '{"role":"user","content":"Hello"}\n{"role":"assistant","content":"Hi there!"}\n' + ); + }); + + it('should handle empty messages array', async () => { + // Mock isEnabled to return true + vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true); + // Mock historyDirExists to return true + vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true); + + await dotAI.setHistory('test-session', []); + + // Verify writeFile was called with empty content + expect(mockFS.writeFile).toHaveBeenCalledWith( + '/test-project/.ai/history/test-session.jsonl', + '' + ); + }); + + it('should handle write errors gracefully', async () => { + // Mock isEnabled to return true + vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true); + // Mock historyDirExists to return true + vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true); + // Mock writeFile to throw an error + vi.mocked(mockFS.writeFile).mockRejectedValue(new Error('Write failed')); + + const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [{ role: 'user', content: 'Hello' }]; + + // Should not throw + await expect(dotAI.setHistory('test-session', messages)).resolves.toBeUndefined(); + }); + }); + describe('generateSessionName', () => { it('should generate a unique session name', () => { const sessionName1 = DotAI.generateSessionName(); diff --git a/src/lib/DotAI.ts b/src/lib/DotAI.ts index 65bfbb38..2f8580fa 100644 --- a/src/lib/DotAI.ts +++ b/src/lib/DotAI.ts @@ -81,10 +81,10 @@ export class DotAI { } } - /** Save a message to the history file */ - async addToHistory( + /** Save the full message history to the history file */ + async setHistory( sessionName: string, - message: OpenAI.Chat.Completions.ChatCompletionMessageParam, + messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[], ): Promise { // Only save if history should be enabled based on the new criteria if (!(await this.isEnabled())) { @@ -96,21 +96,18 @@ export class DotAI { await this.setupAiHistoryDir(); } - const jsonLine = JSON.stringify(message) + "\n"; const sessionFile = join(this.historyDir, sessionName + ".jsonl"); try { - // JSRuntimeFS doesn't have appendFile, so we read, append, and write - let existingContent = ""; - try { - existingContent = await this.fs.readFile(sessionFile, "utf8"); - } catch { - // File doesn't exist yet, that's fine - } - await this.fs.writeFile(sessionFile, existingContent + jsonLine); + // Convert messages to JSONL format + const jsonlContent = messages.map(message => JSON.stringify(message)).join('\n'); + const finalContent = jsonlContent + (messages.length > 0 ? '\n' : ''); + + // Write the entire file + await this.fs.writeFile(sessionFile, finalContent); } catch (error) { // Log error but don't fail the main operation - console.warn(`Failed to save message to AI history: ${error}`); + console.warn(`Failed to save messages to AI history: ${error}`); } } diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 75e01318..8aa66751 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -38,6 +38,13 @@ export class ProjectsManager { async createProject(name: string): Promise { const project = await this.cloneProject(name, GIT_TEMPLATE_URL); + + try { + await this.fs.mkdir(this.dir + `/${name}/.ai/history`, { recursive: true }); + } catch { + // Directory might already exist + } + return project; }