DotAI: addToHistory -> setHistory

This commit is contained in:
Alex Gleason committed 2025-08-24 16:53:48 -05:00
1 parent 479df7cdad
commit 5350506a89
4 files changed
+113 -21

No files matched your search

+85
View File
@@ -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();
+10 -13
View File
@@ -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<void> {
// 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}`);
}
}
+7
View File
@@ -38,6 +38,13 @@ export class ProjectsManager {
async createProject(name: string): Promise<Project> {
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;
}