mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Save and load chat history again
This commit is contained in:
1 parent
629249e5ed
commit
9b37c89dad
4 files changed
+250
-4
No files matched your search
@@ -1,7 +1,7 @@
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Send, Settings, Play, CloudUpload, Loader2 } from 'lucide-react';
|
||||
import { Send, Settings, Play, CloudUpload, Loader2, MessageSquarePlus } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useJSRuntime } from '@/hooks/useJSRuntime';
|
||||
@@ -89,6 +89,7 @@ When creating new components or pages, follow the existing patterns in the codeb
|
||||
isLoading,
|
||||
sendMessage,
|
||||
stopGeneration,
|
||||
startNewSession,
|
||||
} = useAIChat({
|
||||
projectId,
|
||||
projectName,
|
||||
@@ -300,6 +301,17 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
<p className="text-sm text-muted-foreground hidden sm:block">Chat to build your project</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-1 sm:gap-2 hover:bg-secondary/10 hover:border-secondary/20"
|
||||
onClick={startNewSession}
|
||||
disabled={isLoading}
|
||||
title="Start a new chat session"
|
||||
>
|
||||
<MessageSquarePlus className="h-4 w-4" />
|
||||
<span className="hidden sm:inline">New Chat</span>
|
||||
</Button>
|
||||
<GitHistoryDialog projectId={projectId} />
|
||||
<Button
|
||||
variant="outline"
|
||||
|
||||
+55
-3
@@ -1,6 +1,8 @@
|
||||
import { useState, useCallback, useRef } from 'react';
|
||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import OpenAI from 'openai';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
|
||||
// Use OpenAI's native message type
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||
@@ -15,7 +17,7 @@ interface UseAIChatOptions {
|
||||
}
|
||||
|
||||
export function useAIChat({
|
||||
projectId: _projectId,
|
||||
projectId,
|
||||
projectName,
|
||||
tools = {},
|
||||
customTools = {},
|
||||
@@ -24,12 +26,54 @@ export function useAIChat({
|
||||
}: UseAIChatOptions) {
|
||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [sessionName, setSessionName] = useState<string>('');
|
||||
const abortControllerRef = useRef<AbortController | null>(null);
|
||||
const { settings, isConfigured } = useAISettings();
|
||||
const { fs } = useFS();
|
||||
|
||||
// Save message to history
|
||||
const saveMessageToHistory = useCallback(async (message: AIMessage) => {
|
||||
if (!sessionName) return;
|
||||
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `/projects/${projectId}`);
|
||||
await dotAI.addToHistory(sessionName, message);
|
||||
} catch (error) {
|
||||
console.warn('Failed to save message to history:', error);
|
||||
}
|
||||
}, [fs, projectId, sessionName]);
|
||||
|
||||
const addMessage = useCallback((message: AIMessage) => {
|
||||
setMessages(prev => [...prev, message]);
|
||||
}, []);
|
||||
// Save to history asynchronously
|
||||
saveMessageToHistory(message);
|
||||
}, [saveMessageToHistory]);
|
||||
|
||||
// Load message history when component mounts or projectId changes
|
||||
useEffect(() => {
|
||||
const loadMessageHistory = async () => {
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `/projects/${projectId}`);
|
||||
const lastSession = await dotAI.readLastSessionHistory();
|
||||
|
||||
if (lastSession) {
|
||||
setMessages(lastSession.messages);
|
||||
setSessionName(lastSession.sessionName);
|
||||
} else {
|
||||
// No history to load, start fresh
|
||||
setMessages([]);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load message history:', error);
|
||||
// Start fresh on any error
|
||||
setMessages([]);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}
|
||||
};
|
||||
|
||||
loadMessageHistory();
|
||||
}, [projectId, fs]);
|
||||
|
||||
const sendMessage = useCallback(async (content: string) => {
|
||||
if (!isConfigured || isLoading) return;
|
||||
@@ -193,6 +237,13 @@ export function useAIChat({
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
setMessages([]);
|
||||
// Start a new session when clearing messages
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}, []);
|
||||
|
||||
const startNewSession = useCallback(() => {
|
||||
setMessages([]);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}, []);
|
||||
|
||||
return {
|
||||
@@ -201,6 +252,7 @@ export function useAIChat({
|
||||
sendMessage,
|
||||
stopGeneration,
|
||||
clearMessages,
|
||||
startNewSession,
|
||||
addMessage,
|
||||
isConfigured
|
||||
};
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user