Save and load chat history again

This commit is contained in:
Alex Gleason committed 2025-08-24 16:34:46 -05:00
1 parent b813dbe8c4
commit 570f594dc7
4 files changed
+250 -4

No files matched your search

+118
View File
@@ -0,0 +1,118 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { DotAI } from './DotAI';
import type { JSRuntimeFS } from './JSRuntime';
// Mock filesystem
const createMockFS = (): JSRuntimeFS => ({
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
mkdir: vi.fn(),
stat: vi.fn(),
lstat: vi.fn(),
unlink: vi.fn(),
rmdir: vi.fn(),
rename: vi.fn(),
readlink: vi.fn(),
symlink: vi.fn(),
});
describe('DotAI', () => {
let mockFS: JSRuntimeFS;
let dotAI: DotAI;
beforeEach(() => {
mockFS = createMockFS();
dotAI = new DotAI(mockFS, '/test-project');
});
describe('readLastSessionHistory', () => {
it('should return null when AI is not enabled', async () => {
// Mock isEnabled to return false
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(false);
const result = await dotAI.readLastSessionHistory();
expect(result).toBeNull();
});
it('should return null when history directory does not exist', async () => {
// Mock isEnabled to return true but historyDirExists to return false
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
const result = await dotAI.readLastSessionHistory();
expect(result).toBeNull();
});
it('should return null when no session files exist', async () => {
// Mock isEnabled and historyDirExists to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return empty array
vi.mocked(mockFS.readdir).mockResolvedValue([]);
const result = await dotAI.readLastSessionHistory();
expect(result).toBeNull();
});
it('should return messages and session name from most recent file', async () => {
// Mock isEnabled and historyDirExists to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return session files
vi.mocked(mockFS.readdir).mockResolvedValue([
'2024-08-24T16-30-45Z-abc.jsonl',
'2024-08-24T17-15-22Z-def.jsonl', // This should be the most recent
'2024-08-24T15-00-00Z-xyz.jsonl'
]);
// Mock readFile to return JSONL content
const mockContent = `{"role":"user","content":"Hello"}
{"role":"assistant","content":"Hi there!"}`;
vi.mocked(mockFS.readFile).mockResolvedValue(mockContent);
const result = await dotAI.readLastSessionHistory();
expect(result).not.toBeNull();
expect(result?.sessionName).toBe('2024-08-24T17-15-22Z-def');
expect(result?.messages).toHaveLength(2);
expect(result?.messages[0]).toEqual({ role: 'user', content: 'Hello' });
expect(result?.messages[1]).toEqual({ role: 'assistant', content: 'Hi there!' });
});
it('should handle malformed JSON lines gracefully', async () => {
// Mock isEnabled and historyDirExists to return true
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
// Mock readdir to return session files
vi.mocked(mockFS.readdir).mockResolvedValue(['session.jsonl']);
// Mock readFile to return content with malformed JSON
const mockContent = `{"role":"user","content":"Hello"}
invalid json line
{"role":"assistant","content":"Hi there!"}`;
vi.mocked(mockFS.readFile).mockResolvedValue(mockContent);
const result = await dotAI.readLastSessionHistory();
expect(result).not.toBeNull();
expect(result?.messages).toHaveLength(2); // Should skip the malformed line
expect(result?.messages[0]).toEqual({ role: 'user', content: 'Hello' });
expect(result?.messages[1]).toEqual({ role: 'assistant', content: 'Hi there!' });
});
});
describe('generateSessionName', () => {
it('should generate a unique session name', () => {
const sessionName1 = DotAI.generateSessionName();
const sessionName2 = DotAI.generateSessionName();
expect(sessionName1).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}Z-[a-z0-9]{3}$/);
expect(sessionName2).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}Z-[a-z0-9]{3}$/);
expect(sessionName1).not.toBe(sessionName2);
});
});
});
+64
View File
@@ -232,6 +232,70 @@ export class DotAI {
await this.writeAiParameters(currentParameters);
}
/**
* Read the most recent session history
* @returns Object containing messages array and session name, or null if no history found
*/
async readLastSessionHistory(): Promise<{
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[];
sessionName: string;
} | null> {
try {
// Check if AI history is enabled for this project
if (!(await this.isEnabled()) || !(await this.historyDirExists())) {
return null;
}
// Find the most recent session file
try {
const files = await this.fs.readdir(this.historyDir);
const sessionFiles = files
.filter(file => file.endsWith('.jsonl'))
.sort()
.reverse(); // Most recent first
if (sessionFiles.length === 0) {
return null;
}
const latestSessionFile = sessionFiles[0];
const sessionPath = join(this.historyDir, latestSessionFile);
try {
const content = await this.fs.readFile(sessionPath, 'utf8');
const lines = content.trim().split('\n').filter(line => line.trim());
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
for (const line of lines) {
try {
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
messages.push(message);
} catch (parseError) {
console.warn('Failed to parse message from history:', parseError);
}
}
// Return session name without .jsonl extension
const sessionName = latestSessionFile.replace('.jsonl', '');
return {
messages,
sessionName
};
} catch (readError) {
console.warn('Failed to read session file:', readError);
return null;
}
} catch (readdirError) {
console.warn('Failed to read history directory:', readdirError);
return null;
}
} catch (error) {
console.warn('Failed to read last session history:', error);
return null;
}
}
/**
* Ensures that .ai/ is gitignored at the project root level.
* Creates a .gitignore file if it doesn't exist, or adds the line if not already present.