baseline session management

This commit is contained in:
Chad Curtis committed 2025-09-04 06:35:55 +00:00
1 parent da1d221e1d
commit 8475ca7c1a
18 files changed
+1459 -222

No files matched your search

+215
View File
@@ -0,0 +1,215 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
import { useSessionManager } from '@/hooks/useSessionManager';
import { useAISettings } from '@/hooks/useAISettings';
import type { SessionState, SessionConfig, AIMessage } from '@/lib/SessionManager';
import type OpenAI from 'openai';
import type { Tool } from '@/lib/tools/Tool';
interface UseAIChatSessionOptions {
projectId: string;
projectName: string;
tools?: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
customTools?: Record<string, Tool<unknown>>;
systemPrompt?: string;
maxSteps?: number;
onUpdateMetadata?: (title: string, description: string) => void;
}
interface StreamingMessage {
role: 'assistant';
content: string;
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
}
/**
* Hook that provides AI chat functionality using the global session manager.
* Sessions persist and can run in the background when switching between projects.
*/
export function useAIChatSession({
projectId,
projectName,
tools = {},
customTools = {},
systemPrompt,
maxSteps = 50,
onUpdateMetadata
}: UseAIChatSessionOptions) {
const sessionManager = useSessionManager();
const { isConfigured } = useAISettings();
const [sessionId, setSessionId] = useState<string>('');
const [sessionState, setSessionState] = useState<SessionState | null>(null);
// Generate consistent session ID for this project
const generatedSessionId = useMemo(() => {
return `session-${projectId}`;
}, [projectId]);
// Initialize session
useEffect(() => {
const initSession = async () => {
// Check if there's already an active session for this project
const existingSessions = sessionManager.getProjectSessions(projectId);
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];
setSessionId(mostRecent.id);
setSessionState(mostRecent);
// Get the latest session state immediately
const currentSession = sessionManager.getSession(mostRecent.id);
if (currentSession) {
setSessionState(currentSession);
}
} else {
// Create new session
const config: SessionConfig = {
id: generatedSessionId,
projectId,
projectName,
tools,
customTools,
systemPrompt,
maxSteps
};
const newSessionId = await sessionManager.createSession(config);
setSessionId(newSessionId);
const newSession = sessionManager.getSession(newSessionId);
if (newSession) {
setSessionState(newSession);
}
}
};
initSession();
}, [sessionManager, projectId, projectName, tools, customTools, systemPrompt, maxSteps, generatedSessionId]);
// Subscribe to session updates
useEffect(() => {
if (!sessionId) return;
const handleSessionUpdate = (updatedSessionId: string, state: SessionState) => {
if (updatedSessionId === sessionId) {
setSessionState(state);
}
};
const handleMessageAdded = (updatedSessionId: string, _message: AIMessage) => {
if (updatedSessionId === sessionId) {
// Get fresh session state
const session = sessionManager.getSession(sessionId);
if (session) {
setSessionState({ ...session });
}
}
};
const handleStreamingUpdate = (updatedSessionId: string, _content: string, _toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
if (updatedSessionId === sessionId) {
// Get fresh session state
const session = sessionManager.getSession(sessionId);
if (session) {
setSessionState({ ...session });
}
}
};
const handleLoadingChanged = (updatedSessionId: string, isLoading: boolean) => {
if (updatedSessionId === sessionId) {
// Update session state immediately
const session = sessionManager.getSession(sessionId);
if (session) {
setSessionState({ ...session });
}
if (onUpdateMetadata) {
if (isLoading) {
onUpdateMetadata('Shakespeare', `Working on ${projectName}...`);
}
}
}
};
sessionManager.on('sessionUpdated', handleSessionUpdate);
sessionManager.on('messageAdded', handleMessageAdded);
sessionManager.on('streamingUpdate', handleStreamingUpdate);
sessionManager.on('loadingChanged', handleLoadingChanged);
return () => {
sessionManager.off('sessionUpdated', handleSessionUpdate);
sessionManager.off('messageAdded', handleMessageAdded);
sessionManager.off('streamingUpdate', handleStreamingUpdate);
sessionManager.off('loadingChanged', handleLoadingChanged);
};
}, [sessionId, sessionManager, onUpdateMetadata, projectName]);
// Derived state
const messages = sessionState?.messages || [];
const streamingMessage: StreamingMessage | undefined = sessionState?.streamingMessage;
const isLoading = sessionState?.isLoading || false;
// Actions
const sendMessage = useCallback(async (content: string, providerModel: string) => {
if (!sessionId) return;
await sessionManager.sendMessage(sessionId, content, providerModel);
}, [sessionId, sessionManager]);
const startGeneration = useCallback(async (providerModel: string, messagesToUse?: AIMessage[]) => {
if (!sessionId) return;
// If specific messages are provided, we need to update the session first
if (messagesToUse) {
const session = sessionManager.getSession(sessionId);
if (session) {
// Replace session messages with provided messages
session.messages = [...messagesToUse];
// Manually trigger session update
sessionManager.emit('sessionUpdated', sessionId, session);
}
}
await sessionManager.startGeneration(sessionId, providerModel);
}, [sessionId, sessionManager]);
const stopGeneration = useCallback(() => {
if (!sessionId) return;
sessionManager.stopGeneration(sessionId);
}, [sessionId, sessionManager]);
const addMessage = useCallback(async (message: AIMessage) => {
if (!sessionId) return;
await sessionManager.addMessage(sessionId, message);
}, [sessionId, sessionManager]);
const startNewSession = useCallback(async () => {
if (!sessionId) return;
await sessionManager.startNewSession(sessionId);
}, [sessionId, sessionManager]);
const clearMessages = useCallback(async () => {
// Alias for startNewSession for backward compatibility
await startNewSession();
}, [startNewSession]);
return {
messages,
streamingMessage,
isLoading,
sendMessage,
startGeneration,
stopGeneration,
clearMessages,
startNewSession,
addMessage,
isConfigured,
sessionId
};
}
+26
View File
@@ -0,0 +1,26 @@
import { useEffect } from 'react';
import { useSessionManager } from '@/hooks/useSessionManager';
/**
* Hook to clean up sessions when projects are deleted or components unmount
*/
export function useProjectSessionCleanup(projectId: string) {
const sessionManager = useSessionManager();
useEffect(() => {
// Cleanup function that runs when the project component unmounts
// or when the projectId changes
return () => {
// Note: We don't auto-cleanup sessions when navigating away from a project
// since we want sessions to persist in the background. Sessions are only
// cleaned up when explicitly deleted or when the project is deleted.
};
}, [projectId, sessionManager]);
// Return a cleanup function that can be called when a project is deleted
const cleanupProjectSessions = () => {
sessionManager.deleteProjectSessions(projectId);
};
return { cleanupProjectSessions };
}
+42
View File
@@ -0,0 +1,42 @@
import { useState, useEffect } from 'react';
import { useSessionManager } from '@/hooks/useSessionManager';
/**
* Hook to get session status for a specific project
*/
export function useProjectSessionStatus(projectId: string) {
const sessionManager = useSessionManager();
const [hasActiveSessions, setHasActiveSessions] = useState(false);
const [hasRunningSessions, setHasRunningSessions] = useState(false);
useEffect(() => {
const updateStatus = () => {
const projectSessions = sessionManager.getProjectSessions(projectId);
const runningSessions = projectSessions.filter(session => session.isLoading);
setHasActiveSessions(projectSessions.length > 0);
setHasRunningSessions(runningSessions.length > 0);
};
// Initial update
updateStatus();
// 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);
};
}, [sessionManager, projectId]);
return {
hasActiveSessions,
hasRunningSessions
};
}
+15
View File
@@ -0,0 +1,15 @@
import { useContext } from 'react';
import { SessionManagerContext } from '@/contexts/SessionManagerContext';
/**
* Hook to access the global session manager
*/
export function useSessionManager() {
const sessionManager = useContext(SessionManagerContext);
if (!sessionManager) {
throw new Error('useSessionManager must be used within a SessionManagerProvider');
}
return sessionManager;
}