mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Start refactoring SessionManager
This commit is contained in:
3 files changed
+56
-203
No files matched your search
+55
-85
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import type { SessionState, SessionConfig, AIMessage } from '@/lib/SessionManager';
|
||||
import type { SessionConfig, AIMessage } from '@/lib/SessionManager';
|
||||
import type OpenAI from 'openai';
|
||||
import type { Tool } from '@/lib/tools/Tool';
|
||||
|
||||
@@ -38,7 +38,13 @@ export function useAIChat({
|
||||
const sessionManager = useSessionManager();
|
||||
const { isConfigured } = useAISettings();
|
||||
const [sessionId, setSessionId] = useState<string>('');
|
||||
const [sessionState, setSessionState] = useState<SessionState | null>(null);
|
||||
|
||||
// Split session state into individual variables for efficient updates
|
||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const [totalCost, setTotalCost] = useState<number>(0);
|
||||
const [lastInputTokens, setLastInputTokens] = useState<number>(0);
|
||||
|
||||
// Generate consistent session ID for this project
|
||||
const generatedSessionId = useMemo(() => {
|
||||
@@ -53,18 +59,17 @@ export function useAIChat({
|
||||
|
||||
if (existingSessions.length > 0) {
|
||||
// Use the most recent session for this project
|
||||
const mostRecent = existingSessions.sort((a, b) =>
|
||||
b.lastActivity.getTime() - a.lastActivity.getTime()
|
||||
)[0];
|
||||
const mostRecent = existingSessions
|
||||
.sort((a, b) => b.lastActivity.getTime() - a.lastActivity.getTime())[0];
|
||||
|
||||
setSessionId(mostRecent.id);
|
||||
setSessionState(mostRecent);
|
||||
|
||||
// Get the latest session state immediately
|
||||
const currentSession = sessionManager.getSession(mostRecent.id);
|
||||
if (currentSession) {
|
||||
setSessionState(currentSession);
|
||||
}
|
||||
// Initialize individual state variables from existing session
|
||||
setMessages([...mostRecent.messages]);
|
||||
setStreamingMessage(mostRecent.streamingMessage ? { ...mostRecent.streamingMessage } : undefined);
|
||||
setIsLoading(mostRecent.isLoading);
|
||||
setTotalCost(mostRecent.totalCost || 0);
|
||||
setLastInputTokens(mostRecent.lastInputTokens || 0);
|
||||
} else {
|
||||
// Create new session
|
||||
const config: SessionConfig = {
|
||||
@@ -82,7 +87,12 @@ export function useAIChat({
|
||||
|
||||
const newSession = sessionManager.getSession(newSessionId);
|
||||
if (newSession) {
|
||||
setSessionState(newSession);
|
||||
// Initialize individual state variables from new session
|
||||
setMessages([...newSession.messages]);
|
||||
setStreamingMessage(newSession.streamingMessage ? { ...newSession.streamingMessage } : undefined);
|
||||
setIsLoading(newSession.isLoading);
|
||||
setTotalCost(newSession.totalCost || 0);
|
||||
setLastInputTokens(newSession.lastInputTokens || 0);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -90,98 +100,52 @@ export function useAIChat({
|
||||
initSession();
|
||||
}, [sessionManager, projectId, projectName, tools, customTools, systemPrompt, maxSteps, generatedSessionId]);
|
||||
|
||||
|
||||
|
||||
// Subscribe to session events using shared hook
|
||||
useSessionSubscription('sessionUpdated', (updatedSessionId: string, state: SessionState) => {
|
||||
// Subscribe to atomic session events for efficient updates
|
||||
useSessionSubscription('messageAdded', (updatedSessionId: string, message: AIMessage) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
// Directly update state with the provided state object
|
||||
setSessionState({
|
||||
...state,
|
||||
messages: [...state.messages],
|
||||
streamingMessage: state.streamingMessage ? { ...state.streamingMessage } : undefined
|
||||
setMessages(prev => [...prev, message]);
|
||||
}
|
||||
}, [sessionId]);
|
||||
|
||||
useSessionSubscription('streamingUpdate', (updatedSessionId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
setStreamingMessage({
|
||||
role: 'assistant',
|
||||
content,
|
||||
tool_calls: toolCalls
|
||||
});
|
||||
}
|
||||
}, [sessionId]);
|
||||
|
||||
useSessionSubscription('messageAdded', (updatedSessionId: string, _message: AIMessage) => {
|
||||
useSessionSubscription('loadingChanged', (updatedSessionId: string, loading: boolean) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
setSessionState({
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [sessionId, sessionManager]);
|
||||
setIsLoading(loading);
|
||||
|
||||
useSessionSubscription('streamingUpdate', (updatedSessionId: string, _content: string, _toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
setSessionState({
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [sessionId, sessionManager]);
|
||||
|
||||
useSessionSubscription('loadingChanged', (updatedSessionId: string, isLoading: boolean) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
setSessionState({
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
|
||||
});
|
||||
// Clear streaming message when loading stops
|
||||
if (!loading) {
|
||||
setStreamingMessage(undefined);
|
||||
}
|
||||
|
||||
if (onUpdateMetadata && isLoading) {
|
||||
if (onUpdateMetadata && loading) {
|
||||
onUpdateMetadata('Shakespeare', `Working on ${projectName}...`);
|
||||
}
|
||||
}
|
||||
}, [sessionId, sessionManager, onUpdateMetadata, projectName]);
|
||||
}, [sessionId, onUpdateMetadata, projectName]);
|
||||
|
||||
useSessionSubscription('costUpdated', (updatedSessionId: string, _totalCost: number) => {
|
||||
useSessionSubscription('costUpdated', (updatedSessionId: string, cost: number) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
setSessionState({
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
|
||||
});
|
||||
}
|
||||
setTotalCost(cost);
|
||||
}
|
||||
}, [sessionId, sessionManager]);
|
||||
}, [sessionId]);
|
||||
|
||||
useSessionSubscription('contextUsageUpdated', (updatedSessionId: string, _inputTokens: number) => {
|
||||
useSessionSubscription('contextUsageUpdated', (updatedSessionId: string, inputTokens: number) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
setSessionState({
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
|
||||
});
|
||||
}
|
||||
setLastInputTokens(inputTokens);
|
||||
}
|
||||
}, [sessionId, sessionManager]);
|
||||
}, [sessionId]);
|
||||
|
||||
|
||||
|
||||
// Derived state
|
||||
const messages = sessionState?.messages || [];
|
||||
const streamingMessage: StreamingMessage | undefined = sessionState?.streamingMessage;
|
||||
const isLoading = sessionState?.isLoading || false;
|
||||
const totalCost = sessionState?.totalCost || 0;
|
||||
const lastInputTokens = sessionState?.lastInputTokens || 0;
|
||||
|
||||
// Actions
|
||||
const sendMessage = useCallback(async (content: string, providerModel: string) => {
|
||||
if (!sessionId) return;
|
||||
@@ -198,8 +162,8 @@ export function useAIChat({
|
||||
// Replace session messages with provided messages
|
||||
session.messages = [...messagesToUse];
|
||||
|
||||
// Manually trigger session update
|
||||
sessionManager.emit('sessionUpdated', sessionId, session);
|
||||
// Update local state to match
|
||||
setMessages([...messagesToUse]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,6 +183,12 @@ export function useAIChat({
|
||||
const startNewSession = useCallback(async () => {
|
||||
if (!sessionId) return;
|
||||
await sessionManager.startNewSession(sessionId);
|
||||
|
||||
// Reset individual state variables
|
||||
setMessages([]);
|
||||
setStreamingMessage(undefined);
|
||||
setTotalCost(0);
|
||||
setLastInputTokens(0);
|
||||
}, [sessionId, sessionManager]);
|
||||
|
||||
const clearMessages = useCallback(async () => {
|
||||
|
||||
@@ -13,7 +13,7 @@ export function useProjectSessionStatus(projectId: string) {
|
||||
const updateStatus = () => {
|
||||
const projectSessions = sessionManager.getProjectSessions(projectId);
|
||||
const runningSessions = projectSessions.filter(session => session.isLoading);
|
||||
|
||||
|
||||
setHasActiveSessions(projectSessions.length > 0);
|
||||
setHasRunningSessions(runningSessions.length > 0);
|
||||
};
|
||||
@@ -23,13 +23,11 @@ export function useProjectSessionStatus(projectId: string) {
|
||||
|
||||
// Subscribe to session changes
|
||||
sessionManager.on('sessionCreated', updateStatus);
|
||||
sessionManager.on('sessionUpdated', updateStatus);
|
||||
sessionManager.on('sessionDeleted', updateStatus);
|
||||
sessionManager.on('loadingChanged', updateStatus);
|
||||
|
||||
return () => {
|
||||
sessionManager.off('sessionCreated', updateStatus);
|
||||
sessionManager.off('sessionUpdated', updateStatus);
|
||||
sessionManager.off('sessionDeleted', updateStatus);
|
||||
sessionManager.off('loadingChanged', updateStatus);
|
||||
};
|
||||
|
||||
@@ -3,19 +3,6 @@ import type { JSRuntimeFS } from './JSRuntime';
|
||||
import { DotAI } from './DotAI';
|
||||
import { parseProviderModel } from './parseProviderModel';
|
||||
import type { Tool } from './tools/Tool';
|
||||
import { join } from '@std/path';
|
||||
|
||||
// Simple debounce utility
|
||||
const debounce = <T extends (...args: unknown[]) => void>(
|
||||
func: T,
|
||||
wait: number
|
||||
): ((...args: Parameters<T>) => void) => {
|
||||
let timeout: NodeJS.Timeout;
|
||||
return (...args: Parameters<T>) => {
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(() => func(...args), wait);
|
||||
};
|
||||
};
|
||||
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||
|
||||
@@ -49,7 +36,6 @@ export interface SessionState {
|
||||
|
||||
export interface SessionManagerEvents {
|
||||
sessionCreated: (sessionId: string) => void;
|
||||
sessionUpdated: (sessionId: string, state: SessionState) => void;
|
||||
sessionDeleted: (sessionId: string) => void;
|
||||
messageAdded: (sessionId: string, message: AIMessage) => void;
|
||||
streamingUpdate: (sessionId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
|
||||
@@ -73,8 +59,6 @@ export class SessionManager {
|
||||
// Performance constants
|
||||
private readonly MAX_SESSIONS = 50;
|
||||
private readonly MAX_SESSION_AGE = 7 * 24 * 60 * 60 * 1000; // 7 days
|
||||
private debouncedPersist = debounce(() => this.persistSessions(), 1000);
|
||||
private dotAI: DotAI;
|
||||
|
||||
constructor(
|
||||
fs: JSRuntimeFS,
|
||||
@@ -84,12 +68,6 @@ export class SessionManager {
|
||||
this.fs = fs;
|
||||
this.aiSettings = aiSettings;
|
||||
this.getProviderModels = getProviderModels;
|
||||
this.dotAI = new DotAI(fs, '/');
|
||||
|
||||
// Load persisted sessions on initialization
|
||||
this.loadPersistedSessions().catch(error => {
|
||||
console.warn('Failed to load sessions during initialization:', error);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,9 +101,7 @@ export class SessionManager {
|
||||
this.sessions.set(config.id, sessionState);
|
||||
this.sessionConfigs.set(config.id, config);
|
||||
|
||||
this.persistSessions();
|
||||
this.emit('sessionCreated', config.id);
|
||||
this.emit('sessionUpdated', config.id, sessionState);
|
||||
|
||||
return config.id;
|
||||
}
|
||||
@@ -163,7 +139,6 @@ export class SessionManager {
|
||||
this.sessions.delete(sessionId);
|
||||
this.sessionConfigs.delete(sessionId);
|
||||
|
||||
await this.persistSessions();
|
||||
this.emit('sessionDeleted', sessionId);
|
||||
}
|
||||
|
||||
@@ -187,11 +162,9 @@ export class SessionManager {
|
||||
session.lastActivity = new Date();
|
||||
|
||||
await this.saveSessionHistory(sessionId);
|
||||
this.debouncedPersist();
|
||||
this.cleanupOldSessions();
|
||||
|
||||
this.emit('messageAdded', sessionId, message);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -225,7 +198,6 @@ export class SessionManager {
|
||||
session.lastActivity = new Date();
|
||||
|
||||
this.emit('loadingChanged', sessionId, true);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
|
||||
try {
|
||||
// Parse provider and model
|
||||
@@ -264,8 +236,6 @@ export class SessionManager {
|
||||
tool_calls: undefined
|
||||
};
|
||||
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
|
||||
// Prepare completion options
|
||||
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||
model: modelName,
|
||||
@@ -297,7 +267,6 @@ export class SessionManager {
|
||||
if (session.streamingMessage) {
|
||||
session.streamingMessage.content += delta.content;
|
||||
this.emit('streamingUpdate', sessionId, session.streamingMessage.content, session.streamingMessage.tool_calls);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,7 +290,6 @@ export class SessionManager {
|
||||
if (session.streamingMessage) {
|
||||
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
|
||||
this.emit('streamingUpdate', sessionId, session.streamingMessage.content, session.streamingMessage.tool_calls);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,11 +319,9 @@ export class SessionManager {
|
||||
|
||||
// Save and emit all updates together
|
||||
await this.saveSessionHistory(sessionId);
|
||||
this.debouncedPersist();
|
||||
this.cleanupOldSessions();
|
||||
|
||||
this.emit('messageAdded', sessionId, assistantMessage);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
conversationMessages.push(assistantMessage);
|
||||
|
||||
// Update cost if usage data is available
|
||||
@@ -420,7 +386,6 @@ export class SessionManager {
|
||||
session.abortController = undefined;
|
||||
|
||||
this.emit('loadingChanged', sessionId, false);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -437,7 +402,6 @@ export class SessionManager {
|
||||
session.abortController = undefined;
|
||||
|
||||
this.emit('loadingChanged', sessionId, false);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -478,10 +442,8 @@ export class SessionManager {
|
||||
session.totalCost = 0;
|
||||
session.lastInputTokens = 0;
|
||||
|
||||
this.debouncedPersist();
|
||||
this.emit('costUpdated', sessionId, 0);
|
||||
this.emit('contextUsageUpdated', sessionId, 0);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -521,7 +483,6 @@ export class SessionManager {
|
||||
this.emit('contextUsageUpdated', sessionId, usage.prompt_tokens);
|
||||
|
||||
if (!model?.pricing) {
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -534,7 +495,6 @@ export class SessionManager {
|
||||
session.totalCost = (session.totalCost || 0) + requestCost;
|
||||
|
||||
this.emit('costUpdated', sessionId, session.totalCost);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
} catch (error) {
|
||||
console.warn('Failed to calculate session cost:', error);
|
||||
}
|
||||
@@ -577,85 +537,10 @@ export class SessionManager {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Save session states using DotAI for persistence
|
||||
*/
|
||||
private async persistSessions(): Promise<void> {
|
||||
try {
|
||||
if (!this.dotAI.fs?.writeFile) return;
|
||||
|
||||
const sessionData = {
|
||||
sessions: Array.from(this.sessions.entries()).map(([id, session]) => ({
|
||||
id,
|
||||
session: {
|
||||
...session,
|
||||
isLoading: false,
|
||||
streamingMessage: undefined,
|
||||
abortController: undefined
|
||||
}
|
||||
})),
|
||||
configs: Array.from(this.sessionConfigs.entries()),
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
|
||||
// Ensure .ai directory exists before writing
|
||||
const aiDir = join(this.dotAI.workingDir, '.ai');
|
||||
try {
|
||||
await this.dotAI.fs.mkdir(aiDir, { recursive: true });
|
||||
} catch {
|
||||
// Directory might already exist, continue
|
||||
}
|
||||
|
||||
await this.dotAI.fs.writeFile(
|
||||
join(aiDir, 'sessions.json'),
|
||||
JSON.stringify(sessionData)
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn('Failed to persist sessions:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load persisted sessions using DotAI
|
||||
*/
|
||||
private async loadPersistedSessions(): Promise<void> {
|
||||
try {
|
||||
if (!this.dotAI.fs?.readFile) return;
|
||||
|
||||
const sessionsPath = join(this.dotAI.workingDir, '.ai', 'sessions.json');
|
||||
|
||||
try {
|
||||
const sessionsJson = await this.dotAI.fs.readFile(sessionsPath, 'utf8');
|
||||
const sessionData = JSON.parse(sessionsJson);
|
||||
|
||||
// Restore sessions
|
||||
sessionData.sessions?.forEach(({ id, session }: { id: string; session: Omit<SessionState, 'lastActivity'> & { lastActivity: string } }) => {
|
||||
this.sessions.set(id, {
|
||||
...session,
|
||||
lastActivity: new Date(session.lastActivity),
|
||||
totalCost: session.totalCost || 0, // Ensure totalCost is set for older sessions
|
||||
lastInputTokens: session.lastInputTokens || 0 // Ensure lastInputTokens is set for older sessions
|
||||
});
|
||||
});
|
||||
|
||||
// Restore configs
|
||||
sessionData.configs?.forEach(([id, config]: [string, SessionConfig]) => {
|
||||
this.sessionConfigs.set(id, config);
|
||||
});
|
||||
} catch {
|
||||
// File doesn't exist or is invalid - start fresh
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load sessions:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup - stop all sessions and clear data
|
||||
*/
|
||||
async cleanup(): Promise<void> {
|
||||
await this.persistSessions();
|
||||
|
||||
this.sessions.forEach((_, sessionId) => this.stopGeneration(sessionId));
|
||||
|
||||
this.sessions.clear();
|
||||
|
||||
Reference in new issue
Block a user