mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
DotAI: addToHistory -> setHistory
This commit is contained in:
4 files changed
+113
-21
No files matched your search
+11
-8
@@ -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(() => {
|
||||
|
||||
@@ -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
@@ -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}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user