lazy chat loading

This commit is contained in:
lemonknowsall committed 2026-01-12 22:18:45 -08:00
1 parent 5fc96c9007
commit 316ddf284d
11 files changed
+166 -184

No files matched your search

+30 -1
View File
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { OnboardingDialog } from '@/components/OnboardingDialog';
import { ChevronDown, Play } from 'lucide-react';
import { ChevronDown, ChevronUp, Play } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
@@ -300,6 +300,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
streamingMessage,
isLoading: internalIsLoading,
isLoadingHistory,
hasMoreHistory,
isLoadingMoreHistory,
totalCost,
lastInputTokens,
lastFinishReason,
@@ -308,6 +310,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
startGeneration,
stopGeneration,
startNewSession: internalStartNewSession,
loadMoreHistory,
} = useAIChat({
projectId,
tools,
@@ -794,6 +797,32 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
)}
{/* Load older messages button */}
{!isLoadingHistory && hasMoreHistory && (
<div className="flex justify-center py-3">
<Button
variant="ghost"
size="sm"
onClick={async () => {
const container = scrollAreaRef.current;
const oldScrollHeight = container?.scrollHeight || 0;
await loadMoreHistory();
// Preserve scroll position after prepending content
if (container) {
requestAnimationFrame(() => {
container.scrollTop += container.scrollHeight - oldScrollHeight;
});
}
}}
disabled={isLoadingMoreHistory}
className="gap-2 text-muted-foreground"
>
<ChevronUp className="h-4 w-4" />
{isLoadingMoreHistory ? t('loading') : t('loadOlderMessages', 'Load older messages')}
</Button>
</div>
)}
{!isLoadingHistory && displayMessages.map((message, index) => {
// Get the current message's session ID and compare to previous
const currentSessionId = (message as DisplayMessage).sessionId;
+24
View File
@@ -47,6 +47,8 @@ export function useAIChat({
const [lastInputTokens, setLastInputTokens] = useState<number>(0);
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
const [hasMoreHistory, setHasMoreHistory] = useState<boolean>(false);
const [isLoadingMoreHistory, setIsLoadingMoreHistory] = useState<boolean>(false);
const initSession = useCallback(async () => {
setIsLoadingHistory(true);
@@ -62,6 +64,8 @@ export function useAIChat({
setTotalCost(session.totalCost || 0);
setLastInputTokens(session.lastInputTokens || 0);
setLastFinishReason(session.lastFinishReason ?? null);
setHasMoreHistory(sessionManager.hasMoreHistory(projectId));
setIsLoadingMoreHistory(session.isLoadingMoreHistory || false);
} finally {
setIsLoadingHistory(false);
}
@@ -133,6 +137,19 @@ export function useAIChat({
}
}, [projectId]);
useSessionSubscription('displayMessagesPrepended', (updatedProjectId: string, newMessages: DisplayMessage[]) => {
if (updatedProjectId === projectId) {
setDisplayMessages(prev => [...newMessages, ...prev]);
setHasMoreHistory(sessionManager.hasMoreHistory(projectId));
}
}, [projectId, sessionManager]);
useSessionSubscription('loadingMoreHistoryChanged', (updatedProjectId: string, loading: boolean) => {
if (updatedProjectId === projectId) {
setIsLoadingMoreHistory(loading);
}
}, [projectId]);
// Actions
const sendMessage = useCallback(async (
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
@@ -193,6 +210,10 @@ export function useAIChat({
await startNewSession();
}, [startNewSession]);
const loadMoreHistory = useCallback(async () => {
await sessionManager.loadOlderSession(projectId);
}, [projectId, sessionManager]);
return {
messages,
displayMessages,
@@ -200,6 +221,8 @@ export function useAIChat({
streamingMessage,
isLoading,
isLoadingHistory,
hasMoreHistory,
isLoadingMoreHistory,
totalCost,
lastInputTokens,
lastFinishReason,
@@ -209,6 +232,7 @@ export function useAIChat({
clearMessages,
startNewSession,
addMessage,
loadMoreHistory,
isConfigured,
projectId
};
-67
View File
@@ -27,73 +27,6 @@ describe('DotAI', () => {
dotAI = new DotAI(mockFS, '/test-project');
});
describe('readLastSessionHistory', () => {
it('should return null when history directory does not exist', async () => {
// Mock historyDirExists to return false
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 historyDirExists to return 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 historyDirExists to return 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 historyDirExists to return 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('setHistory', () => {
it('should create history directory if it does not exist', async () => {
// Mock historyDirExists to return false initially
+26 -101
View File
@@ -216,125 +216,50 @@ export class DotAI {
}
/**
* Read all session histories sorted chronologically by filename
* @returns Array of session histories with messages
* List all session names sorted chronologically (oldest first)
* Fast operation - does not load message content
* @returns Array of session names (filenames without .jsonl extension)
*/
async readAllSessionHistories(): Promise<Array<{
sessionName: string;
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[];
}>> {
const sessions: Array<{
sessionName: string;
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[];
}> = [];
async listSessionNames(): Promise<string[]> {
try {
if (!(await this.historyDirExists())) {
return sessions;
return [];
}
const files = await this.fs.readdir(this.historyDir);
const sessionFiles = files
return files
.filter(file => file.endsWith('.jsonl'))
.map(file => file.replace('.jsonl', ''))
.sort(); // Chronological order (oldest first) - filenames contain timestamps
for (const file of sessionFiles) {
const sessionPath = join(this.historyDir, file);
const sessionName = file.replace('.jsonl', '');
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 {
// Skip malformed lines
}
}
// Only include sessions with messages
if (messages.length > 0) {
sessions.push({
sessionName,
messages,
});
}
} catch {
// Skip unreadable files
}
}
} catch (error) {
console.warn('Failed to read all session histories:', error);
} catch {
return [];
}
return sessions;
}
/**
* Read the most recent session history
* @returns Object containing messages array and session name, or null if no history found
* Read messages for a single session
* @param sessionName The session name (filename without .jsonl)
* @returns Array of messages, or empty array if session not found
*/
async readLastSessionHistory(): Promise<{
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[];
sessionName: string;
} | null> {
async readSessionHistory(sessionName: string): Promise<OpenAI.Chat.Completions.ChatCompletionMessageParam[]> {
try {
// Check if history directory exists
if (!(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);
const sessionPath = join(this.historyDir, sessionName + '.jsonl');
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 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;
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
messages.push(message);
} catch {
// Skip malformed lines
}
} 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;
return messages;
} catch {
return [];
}
}
+80 -15
View File
@@ -36,6 +36,8 @@ export interface SessionState {
maxSteps?: number;
messages: AIMessage[]; // Current session messages (sent to AI)
displayMessages: DisplayMessage[]; // All messages from all sessions (for UI, with sessionId)
availableSessionNames: string[]; // All session names (for lazy loading)
loadedSessionCount: number; // How many sessions loaded from the end
streamingMessage?: {
role: 'assistant';
content: string;
@@ -43,6 +45,7 @@ export interface SessionState {
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
};
isLoading: boolean;
isLoadingMoreHistory: boolean; // Loading older sessions
sessionName: string;
lastActivity: Date;
abortController?: AbortController;
@@ -57,8 +60,10 @@ export interface SessionManagerEvents {
sessionDeleted: (projectId: string) => void;
messageAdded: (projectId: string, message: AIMessage) => void;
displayMessageAdded: (projectId: string, message: DisplayMessage) => void;
displayMessagesPrepended: (projectId: string, messages: DisplayMessage[]) => void;
streamingUpdate: (projectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
loadingChanged: (projectId: string, isLoading: boolean) => void;
loadingMoreHistoryChanged: (projectId: string, isLoading: boolean) => void;
costUpdated: (projectId: string, totalCost: number) => void;
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
fileChanged: (projectId: string, filePath: string) => void;
@@ -104,7 +109,7 @@ export class SessionManager {
}
/**
* Create a new session for a project
* Create a new session for a project (lazy loading - only loads most recent session)
*/
async loadSession(
projectId: string,
@@ -115,32 +120,36 @@ export class SessionManager {
const messages: AIMessage[] = [];
const displayMessages: DisplayMessage[] = [];
let sessionName = DotAI.generateSessionName();
let availableSessionNames: string[] = [];
let loadedSessionCount = 0;
let lastFinishReason: string | null | undefined;
// Try to load existing history
// Try to load existing history (lazy - only load last session)
try {
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
// Load all session histories for display
const allSessions = await dotAI.readAllSessionHistories();
// Get all available session names (fast - no content loading)
availableSessionNames = await dotAI.listSessionNames();
if (allSessions.length > 0) {
// Build displayMessages with sessionId annotations
for (const session of allSessions) {
// Add all messages from this session with sessionId annotation
for (const msg of session.messages) {
if (availableSessionNames.length > 0) {
// Only load the most recent session
const lastSessionName = availableSessionNames[availableSessionNames.length - 1];
const lastSessionMessages = await dotAI.readSessionHistory(lastSessionName);
if (lastSessionMessages.length > 0) {
// Add messages with sessionId annotation
for (const msg of lastSessionMessages) {
displayMessages.push({
...msg as AIMessage,
sessionId: session.sessionName,
sessionId: lastSessionName,
});
}
messages.push(...lastSessionMessages as AIMessage[]);
sessionName = lastSessionName;
loadedSessionCount = 1;
}
// Current session messages come from the last session
const lastSession = allSessions[allSessions.length - 1];
messages.push(...lastSession.messages as AIMessage[]);
sessionName = lastSession.sessionName;
}
// Load last finish reason
@@ -155,6 +164,7 @@ export class SessionManager {
customTools,
maxSteps,
isLoading: false,
isLoadingMoreHistory: false,
lastActivity: new Date(),
totalCost: 0,
lastInputTokens: 0,
@@ -162,6 +172,8 @@ export class SessionManager {
...this.sessions.get(projectId),
messages,
displayMessages,
availableSessionNames,
loadedSessionCount,
sessionName,
};
@@ -175,6 +187,8 @@ export class SessionManager {
if (!this.sessions.has(projectId)) {
session.messages = messages;
session.displayMessages = displayMessages;
session.availableSessionNames = availableSessionNames;
session.loadedSessionCount = loadedSessionCount;
session.sessionName = sessionName;
}
@@ -232,6 +246,57 @@ export class SessionManager {
this.emit('displayMessageAdded', projectId, displayMessage);
}
/**
* Check if there are more historical sessions to load
*/
hasMoreHistory(projectId: string): boolean {
const session = this.sessions.get(projectId);
if (!session) return false;
return session.loadedSessionCount < session.availableSessionNames.length;
}
/**
* Load the next older session and prepend to displayMessages
*/
async loadOlderSession(projectId: string): Promise<void> {
const session = this.sessions.get(projectId);
if (!session || !this.hasMoreHistory(projectId) || session.isLoadingMoreHistory) return;
session.isLoadingMoreHistory = true;
this.emit('loadingMoreHistoryChanged', projectId, true);
try {
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
// Get the next older session (counting from the end)
const nextIndex = session.availableSessionNames.length - session.loadedSessionCount - 1;
if (nextIndex < 0) return;
const olderSessionName = session.availableSessionNames[nextIndex];
const olderMessages = await dotAI.readSessionHistory(olderSessionName);
if (olderMessages.length > 0) {
// Create display messages with sessionId
const newDisplayMessages: DisplayMessage[] = olderMessages.map(msg => ({
...msg as AIMessage,
sessionId: olderSessionName,
}));
// Prepend to displayMessages
session.displayMessages = [...newDisplayMessages, ...session.displayMessages];
session.loadedSessionCount++;
this.emit('displayMessagesPrepended', projectId, newDisplayMessages);
}
} catch (error) {
console.warn('Failed to load older session:', error);
} finally {
session.isLoadingMoreHistory = false;
this.emit('loadingMoreHistoryChanged', projectId, false);
}
}
/**
* Send a message and start AI generation
*/
+1
View File
@@ -10,6 +10,7 @@
"logIn": "Log in",
"signUp": "Sign up",
"newChat": "New Chat",
"loadOlderMessages": "Load older messages",
"preferencesDescription": "Manage your general application preferences and appearance settings.",
"theme": "Theme",
"themeDescription": "Choose between light, dark, or system theme preference.",
+1
View File
@@ -10,6 +10,7 @@
"logIn": "Shiga",
"signUp": "Yi Rajista",
"newChat": "Sabon Tattaunawa",
"loadOlderMessages": "Loda saƙonni masu tsufa",
"preferencesDescription": "Sarrafa zaɓuɓɓukan aikace-aikacenku da saitunan bayyanar.",
"theme": "Jigogi",
"themeDescription": "Zaɓi tsakanin haske, duhu, ko zaɓin jigogi na tsarin.",
+1
View File
@@ -10,6 +10,7 @@
"logIn": "Banye",
"signUp": "Debanye aha",
"newChat": "Nkata Ọhụrụ",
"loadOlderMessages": "Bulite ozi ochie",
"preferencesDescription": "Jikwaa nhọrọ ngwa gị na ntọala ngosipụta.",
"theme": "Isiokwu",
"themeDescription": "Họrọ n'etiti ìhè, ọchịchịrị, ma ọ bụ nhọrọ isiokwu sistemu.",
+1
View File
@@ -10,6 +10,7 @@
"logIn": "Entrar",
"signUp": "Cadastrar",
"newChat": "Nova Conversa",
"loadOlderMessages": "Carregar mensagens anteriores",
"preferencesDescription": "Gerencie suas preferências gerais da aplicação e configurações de aparência.",
"theme": "Tema",
"themeDescription": "Escolha entre preferência de tema claro, escuro ou do sistema.",
+1
View File
@@ -10,6 +10,7 @@
"logIn": "Wọle",
"signUp": "Forukọsilẹ",
"newChat": "Ọrọ Tuntun",
"loadOlderMessages": "Gbe awọn ifiranṣẹ atijọ",
"preferencesDescription": "Ṣakoso awọn ayanfẹ ohun elo rẹ ati awọn eto iwoye.",
"theme": "Akori",
"themeDescription": "Yan laarin imọlẹ, okunkun, tabi ayanfẹ akori eto.",
+1
View File
@@ -10,6 +10,7 @@
"logIn": "登录",
"signUp": "注册",
"newChat": "新对话",
"loadOlderMessages": "加载更早的消息",
"preferencesDescription": "管理您的应用程序偏好设置和外观设置。",
"theme": "主题",
"themeDescription": "选择浅色、深色或系统主题偏好。",