mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 00:27:24 +00:00
cleanup
This commit is contained in:
1 parent
a3d491f1a5
commit
6583e29d08
11 files changed
+144
-902
No files matched your search
@@ -1,7 +1,7 @@
|
||||
import { memo, useState } from 'react';
|
||||
import { Streamdown } from 'streamdown';
|
||||
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus } from 'lucide-react';
|
||||
import { AIMessage } from '@/hooks/useAIChat';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import OpenAI from 'openai';
|
||||
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ProjectSessionIndicatorProps {
|
||||
projectId: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Small indicator that shows if a project has active AI sessions
|
||||
* Positioned as a status badge on the folder icon
|
||||
*/
|
||||
export function ProjectSessionIndicator({ projectId, className }: ProjectSessionIndicatorProps) {
|
||||
const { hasActiveSessions, hasRunningSessions } = useProjectSessionStatus(projectId);
|
||||
|
||||
if (!hasActiveSessions) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn(
|
||||
"absolute -bottom-0.5 -right-0.5 flex items-center justify-center",
|
||||
"bg-background border border-border rounded-full shadow-sm",
|
||||
className
|
||||
)}>
|
||||
{hasRunningSessions ? (
|
||||
<Loader2 className="h-2.5 w-2.5 animate-spin text-blue-600 dark:text-blue-400" />
|
||||
) : (
|
||||
<div className="h-1.5 w-1.5 rounded-full bg-green-500" title="AI session active" />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useState, memo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Plus, Folder, Download, GitBranch, MoreVertical, Settings, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -22,7 +22,7 @@ interface ProjectItemProps {
|
||||
onSelect: (project: Project) => void;
|
||||
}
|
||||
|
||||
function ProjectItem({ project, isSelected, onSelect }: ProjectItemProps) {
|
||||
const ProjectItem = memo(({ project, isSelected, onSelect }: ProjectItemProps) => {
|
||||
const navigate = useNavigate();
|
||||
const { hasRunningSessions } = useProjectSessionStatus(project.id);
|
||||
|
||||
@@ -72,7 +72,9 @@ function ProjectItem({ project, isSelected, onSelect }: ProjectItemProps) {
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
ProjectItem.displayName = 'ProjectItem';
|
||||
|
||||
interface ProjectSidebarProps {
|
||||
selectedProject: Project | null;
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Activity, Clock, Loader2, MessageSquare, X } from 'lucide-react';
|
||||
import type { SessionState } from '@/lib/SessionManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface SessionStatusIndicatorProps {
|
||||
className?: string;
|
||||
currentProjectId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Component that shows the status of all active AI sessions
|
||||
*/
|
||||
export function SessionStatusIndicator({ className, currentProjectId }: SessionStatusIndicatorProps) {
|
||||
const sessionManager = useSessionManager();
|
||||
const [sessions, setSessions] = useState<SessionState[]>([]);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
// Update sessions when they change
|
||||
useEffect(() => {
|
||||
const updateSessions = () => {
|
||||
setSessions(sessionManager.getAllSessions());
|
||||
};
|
||||
|
||||
// Initial load
|
||||
updateSessions();
|
||||
|
||||
// Subscribe to session changes
|
||||
sessionManager.on('sessionCreated', updateSessions);
|
||||
sessionManager.on('sessionUpdated', updateSessions);
|
||||
sessionManager.on('sessionDeleted', updateSessions);
|
||||
|
||||
return () => {
|
||||
sessionManager.off('sessionCreated', updateSessions);
|
||||
sessionManager.off('sessionUpdated', updateSessions);
|
||||
sessionManager.off('sessionDeleted', updateSessions);
|
||||
};
|
||||
}, [sessionManager]);
|
||||
|
||||
const activeSessions = sessions.filter(session => session.isLoading);
|
||||
const totalSessions = sessions.length;
|
||||
|
||||
if (totalSessions === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const handleStopSession = (sessionId: string, e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
sessionManager.stopGeneration(sessionId);
|
||||
};
|
||||
|
||||
const handleDeleteSession = (sessionId: string, e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
sessionManager.deleteSession(sessionId);
|
||||
};
|
||||
|
||||
const formatLastActivity = (date: Date) => {
|
||||
const now = new Date();
|
||||
const diff = now.getTime() - date.getTime();
|
||||
const minutes = Math.floor(diff / 60000);
|
||||
const hours = Math.floor(diff / 3600000);
|
||||
|
||||
if (minutes < 1) return 'Just now';
|
||||
if (minutes < 60) return `${minutes}m ago`;
|
||||
if (hours < 24) return `${hours}h ago`;
|
||||
return date.toLocaleDateString();
|
||||
};
|
||||
|
||||
return (
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn(
|
||||
"h-8 px-2 gap-1 text-xs",
|
||||
activeSessions.length > 0 && "text-blue-600 dark:text-blue-400",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{activeSessions.length > 0 ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<Activity className="h-3 w-3" />
|
||||
)}
|
||||
<span>{totalSessions}</span>
|
||||
{activeSessions.length > 0 && (
|
||||
<Badge variant="secondary" className="h-4 px-1 text-xs">
|
||||
{activeSessions.length}
|
||||
</Badge>
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-80 p-0" align="end">
|
||||
<div className="p-3 border-b">
|
||||
<h4 className="font-semibold text-sm">AI Sessions</h4>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{totalSessions} active session{totalSessions !== 1 ? 's' : ''}
|
||||
{activeSessions.length > 0 && ` (${activeSessions.length} running)`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="max-h-64 overflow-y-auto">
|
||||
{sessions.map((session) => (
|
||||
<div
|
||||
key={session.id}
|
||||
className={cn(
|
||||
"p-3 border-b last:border-b-0 hover:bg-muted/50",
|
||||
session.projectId === currentProjectId && "bg-primary/5"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<h5 className="font-medium text-sm truncate">
|
||||
{session.projectName}
|
||||
</h5>
|
||||
{session.isLoading && (
|
||||
<Loader2 className="h-3 w-3 animate-spin text-blue-600" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
|
||||
<MessageSquare className="h-3 w-3" />
|
||||
<span>{session.messages.length} messages</span>
|
||||
<Clock className="h-3 w-3 ml-1" />
|
||||
<span>{formatLastActivity(session.lastActivity)}</span>
|
||||
</div>
|
||||
{session.streamingMessage?.content && (
|
||||
<p className="text-xs text-muted-foreground mt-1 truncate">
|
||||
{session.streamingMessage.content.slice(0, 50)}...
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{session.isLoading && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0"
|
||||
onClick={(e) => handleStopSession(session.id, e)}
|
||||
title="Stop generation"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 text-destructive hover:text-destructive"
|
||||
onClick={(e) => handleDeleteSession(session.id, e)}
|
||||
title="Delete session"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { useFS } from '@/hooks/useFS';
|
||||
|
||||
import { useKeepAlive } from '@/hooks/useKeepAlive';
|
||||
import { useAIChatSession } from '@/hooks/useAIChatSession';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { ModelSelector } from '@/components/ModelSelector';
|
||||
|
||||
|
||||
@@ -310,7 +311,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
streamingMessage.content ? (
|
||||
<AIMessageItem
|
||||
key="streaming-message"
|
||||
message={streamingMessage as OpenAI.Chat.Completions.ChatCompletionMessageParam}
|
||||
message={streamingMessage as AIMessage}
|
||||
isCurrentlyLoading
|
||||
/>
|
||||
) : (
|
||||
@@ -329,7 +330,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
<div className="flex items-center gap-2 px-2 py-1 text-xs text-muted-foreground">
|
||||
<Loader2 className="h-3 w-3 animate-spin flex-shrink-0" />
|
||||
<span className="font-medium">
|
||||
Running {(streamingMessage.tool_calls[0] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall).function.name}...
|
||||
Running {streamingMessage.tool_calls?.[0]?.function?.name || 'tool'}...
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,403 +0,0 @@
|
||||
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';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
|
||||
// Use OpenAI's native message type
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||
|
||||
export interface StreamingMessage {
|
||||
role: 'assistant';
|
||||
content: string;
|
||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||
}
|
||||
|
||||
interface UseAIChatOptions {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
tools?: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
customTools?: Record<string, Tool<unknown>>;
|
||||
systemPrompt?: string;
|
||||
onUpdateMetadata?: (title: string, description: string) => void;
|
||||
maxSteps?: number;
|
||||
}
|
||||
|
||||
export function useAIChat({
|
||||
projectId,
|
||||
projectName,
|
||||
tools = {},
|
||||
customTools = {},
|
||||
systemPrompt,
|
||||
onUpdateMetadata,
|
||||
maxSteps = 50
|
||||
}: UseAIChatOptions) {
|
||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [sessionName, setSessionName] = useState<string>('');
|
||||
const abortControllerRef = useRef<AbortController | null>(null);
|
||||
const { settings, isConfigured, addRecentlyUsedModel } = useAISettings();
|
||||
const { fs } = useFS();
|
||||
|
||||
// Save all messages to history
|
||||
const saveMessagesToHistory = useCallback(async (allMessages: AIMessage[]) => {
|
||||
if (!sessionName) return;
|
||||
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `/projects/${projectId}`);
|
||||
await dotAI.setHistory(sessionName, allMessages);
|
||||
} catch (error) {
|
||||
console.warn('Failed to save messages to history:', error);
|
||||
}
|
||||
}, [fs, projectId, sessionName]);
|
||||
|
||||
const addMessage = useCallback((message: AIMessage) => {
|
||||
setMessages(prev => {
|
||||
const newMessages = [...prev, message];
|
||||
// Save to history asynchronously with all messages
|
||||
saveMessagesToHistory(newMessages);
|
||||
return newMessages;
|
||||
});
|
||||
}, [saveMessagesToHistory]);
|
||||
|
||||
const startGeneration = useCallback(async (providerModel: string, messagesToUse?: AIMessage[]) => {
|
||||
const currentMessages = messagesToUse || messages;
|
||||
|
||||
if (!isConfigured || isLoading || currentMessages.length === 0) return;
|
||||
|
||||
// Get the last message - it should be a user message
|
||||
const lastMessage = currentMessages[currentMessages.length - 1];
|
||||
if (lastMessage.role !== 'user') return;
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Create abort controller for this request
|
||||
abortControllerRef.current = new AbortController();
|
||||
|
||||
// Use all existing messages
|
||||
const modelMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [...currentMessages];
|
||||
|
||||
// Add system message if provided
|
||||
if (systemPrompt) {
|
||||
modelMessages.unshift({
|
||||
role: 'system',
|
||||
content: systemPrompt
|
||||
});
|
||||
}
|
||||
|
||||
// Parse provider and model
|
||||
const parsed = parseProviderModel(providerModel, settings.providers);
|
||||
const connectionConfig = parsed.connection;
|
||||
const modelName = parsed.model;
|
||||
|
||||
// Initialize OpenAI client with parsed connection
|
||||
const openai = new OpenAI({
|
||||
baseURL: connectionConfig.baseURL,
|
||||
apiKey: connectionConfig.apiKey,
|
||||
dangerouslyAllowBrowser: true
|
||||
});
|
||||
|
||||
// Update metadata
|
||||
if (onUpdateMetadata) {
|
||||
onUpdateMetadata('Shakespeare', `Working on ${projectName}...`);
|
||||
}
|
||||
|
||||
// Keep track of current messages for this conversation
|
||||
const conversationMessages = [...modelMessages];
|
||||
let stepCount = 0;
|
||||
|
||||
// Main loop for handling multiple steps with tool calls
|
||||
while (stepCount < maxSteps) {
|
||||
stepCount++;
|
||||
console.log(`AI Chat Step ${stepCount}/${maxSteps}`);
|
||||
|
||||
// Initialize streaming message
|
||||
setStreamingMessage({
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
tool_calls: undefined
|
||||
});
|
||||
|
||||
// Prepare chat completion options
|
||||
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||
model: modelName,
|
||||
messages: conversationMessages,
|
||||
tools: tools && Object.keys(tools).length > 0 ? Object.values(tools) : undefined,
|
||||
tool_choice: tools && Object.keys(tools).length > 0 ? 'auto' : undefined,
|
||||
stream: true
|
||||
};
|
||||
|
||||
// Generate streaming response
|
||||
const stream = await openai.chat.completions.create(completionOptions, {
|
||||
signal: abortControllerRef.current.signal
|
||||
});
|
||||
|
||||
let accumulatedContent = '';
|
||||
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
|
||||
let finishReason: string | null = null;
|
||||
let hasRecordedModel = false;
|
||||
|
||||
// Process the stream
|
||||
for await (const chunk of stream) {
|
||||
const delta = chunk.choices[0]?.delta;
|
||||
|
||||
// Track recently used model on first chunk
|
||||
if (!hasRecordedModel && providerModel) {
|
||||
addRecentlyUsedModel(providerModel);
|
||||
hasRecordedModel = true;
|
||||
}
|
||||
|
||||
if (delta?.content) {
|
||||
accumulatedContent += delta.content;
|
||||
setStreamingMessage(prev => prev ? {
|
||||
...prev,
|
||||
content: prev.content + delta.content
|
||||
} : {
|
||||
role: 'assistant',
|
||||
content: delta.content,
|
||||
tool_calls: undefined
|
||||
});
|
||||
}
|
||||
|
||||
if (delta?.tool_calls) {
|
||||
for (const toolCallDelta of delta.tool_calls) {
|
||||
const index = toolCallDelta.index;
|
||||
if (index !== undefined) {
|
||||
// Initialize tool call if it doesn't exist
|
||||
if (!accumulatedToolCalls[index]) {
|
||||
accumulatedToolCalls[index] = {
|
||||
id: toolCallDelta.id || '',
|
||||
type: 'function',
|
||||
function: {
|
||||
name: '',
|
||||
arguments: ''
|
||||
}
|
||||
} as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||
}
|
||||
|
||||
// Update tool call properties
|
||||
if (toolCallDelta.id) {
|
||||
accumulatedToolCalls[index].id = toolCallDelta.id;
|
||||
}
|
||||
if (toolCallDelta.function?.name && accumulatedToolCalls[index].type === 'function') {
|
||||
(accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall).function.name = toolCallDelta.function.name;
|
||||
}
|
||||
if (toolCallDelta.function?.arguments && accumulatedToolCalls[index].type === 'function') {
|
||||
(accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall).function.arguments += toolCallDelta.function.arguments;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update streaming message with current tool calls
|
||||
setStreamingMessage(prev => prev ? {
|
||||
...prev,
|
||||
tool_calls: accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined
|
||||
} : {
|
||||
role: 'assistant',
|
||||
content: accumulatedContent,
|
||||
tool_calls: accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined
|
||||
});
|
||||
}
|
||||
|
||||
if (chunk.choices[0]?.finish_reason) {
|
||||
finishReason = chunk.choices[0].finish_reason;
|
||||
}
|
||||
}
|
||||
|
||||
// Create final assistant message
|
||||
const assistantMessage: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: accumulatedContent,
|
||||
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
|
||||
};
|
||||
|
||||
// Clear streaming message and add final message
|
||||
setStreamingMessage(undefined);
|
||||
addMessage(assistantMessage);
|
||||
conversationMessages.push(assistantMessage);
|
||||
|
||||
// Check if we should stop (no tool calls or finish reason is "stop")
|
||||
if (finishReason === 'stop' || !accumulatedToolCalls || accumulatedToolCalls.length === 0) {
|
||||
console.log(`AI Chat completed after ${stepCount} steps. Finish reason: ${finishReason}`);
|
||||
break;
|
||||
}
|
||||
|
||||
// Handle tool calls if present
|
||||
if (accumulatedToolCalls && accumulatedToolCalls.length > 0) {
|
||||
console.log(`Processing ${accumulatedToolCalls.length} tool calls in step ${stepCount}`);
|
||||
|
||||
for (const toolCall of accumulatedToolCalls) {
|
||||
if (toolCall.type !== 'function') continue;
|
||||
|
||||
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||
const toolName = functionToolCall.function.name;
|
||||
const tool = customTools[toolName];
|
||||
|
||||
if (!tool) {
|
||||
// Tool not found
|
||||
const toolNotFoundMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content: `Tool ${toolName} not found`,
|
||||
tool_call_id: functionToolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolNotFoundMessage);
|
||||
conversationMessages.push(toolNotFoundMessage);
|
||||
continue;
|
||||
}
|
||||
|
||||
let toolArgs: unknown;
|
||||
try {
|
||||
const json = JSON.parse(functionToolCall.function.arguments);
|
||||
toolArgs = tool.inputSchema.parse(json);
|
||||
} catch (parseError) {
|
||||
console.error(`Failed to parse tool arguments for ${toolName}:`, parseError);
|
||||
|
||||
const toolErrorMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content: `Error parsing arguments for tool ${toolName}: ${parseError instanceof Error ? parseError.message : 'Unknown error'}`,
|
||||
tool_call_id: functionToolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolErrorMessage);
|
||||
conversationMessages.push(toolErrorMessage);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`Executing tool: ${toolName}`, toolArgs);
|
||||
|
||||
// Execute the custom tool
|
||||
const content = await tool.execute(toolArgs);
|
||||
|
||||
// Add tool result message
|
||||
const toolResultMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content,
|
||||
tool_call_id: functionToolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolResultMessage);
|
||||
conversationMessages.push(toolResultMessage);
|
||||
} catch (toolError) {
|
||||
console.error(`Tool execution error for ${toolName}:`, toolError);
|
||||
|
||||
const toolErrorMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content: `Error executing tool ${toolName}: ${toolError instanceof Error ? toolError.message : 'Unknown error'}`,
|
||||
tool_call_id: functionToolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolErrorMessage);
|
||||
conversationMessages.push(toolErrorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we reached maxSteps, log a warning
|
||||
if (stepCount >= maxSteps) {
|
||||
console.warn(`AI Chat reached maximum steps (${maxSteps}). Conversation may be incomplete.`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('AI chat error:', error);
|
||||
|
||||
// Clear any streaming message on error
|
||||
setStreamingMessage(undefined);
|
||||
|
||||
// Add error message
|
||||
const errorMessage: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.'
|
||||
};
|
||||
|
||||
addMessage(errorMessage);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
abortControllerRef.current = null;
|
||||
}
|
||||
}, [isConfigured, isLoading, addMessage, messages, settings.providers, tools, customTools, systemPrompt, onUpdateMetadata, projectName, maxSteps, addRecentlyUsedModel]);
|
||||
|
||||
// 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, providerModel: string) => {
|
||||
if (!isConfigured || isLoading) return;
|
||||
|
||||
// Add user message
|
||||
const userMessage: AIMessage = {
|
||||
role: 'user',
|
||||
content
|
||||
};
|
||||
|
||||
// Calculate the new messages array that will exist after the state update
|
||||
const newMessages = [...messages, userMessage];
|
||||
|
||||
// Add the message to state
|
||||
addMessage(userMessage);
|
||||
|
||||
// Start generation with the new messages array directly
|
||||
startGeneration(providerModel, newMessages);
|
||||
}, [isConfigured, isLoading, messages, addMessage, startGeneration]);
|
||||
|
||||
const stopGeneration = useCallback(() => {
|
||||
if (abortControllerRef.current) {
|
||||
abortControllerRef.current.abort();
|
||||
}
|
||||
setStreamingMessage(undefined);
|
||||
}, []);
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
setMessages([]);
|
||||
setStreamingMessage(undefined);
|
||||
// Start a new session when clearing messages
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}, []);
|
||||
|
||||
const startNewSession = useCallback(() => {
|
||||
setMessages([]);
|
||||
setStreamingMessage(undefined);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}, []);
|
||||
|
||||
return {
|
||||
messages,
|
||||
streamingMessage,
|
||||
isLoading,
|
||||
sendMessage,
|
||||
startGeneration,
|
||||
stopGeneration,
|
||||
clearMessages,
|
||||
startNewSession,
|
||||
addMessage,
|
||||
isConfigured
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
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 OpenAI from 'openai';
|
||||
@@ -89,92 +90,53 @@ export function useAIChatSession({
|
||||
initSession();
|
||||
}, [sessionManager, projectId, projectName, tools, customTools, systemPrompt, maxSteps, generatedSessionId]);
|
||||
|
||||
// Subscribe to session updates
|
||||
useEffect(() => {
|
||||
if (!sessionId) return;
|
||||
// Update session state efficiently
|
||||
const updateSessionState = useCallback((state: SessionState) => {
|
||||
setSessionState({
|
||||
...state,
|
||||
// Only create new arrays/objects when they actually change
|
||||
messages: state.messages.slice(),
|
||||
streamingMessage: state.streamingMessage ? { ...state.streamingMessage } : undefined
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleSessionUpdate = (updatedSessionId: string, state: SessionState) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
// Create a deep copy to ensure React detects the change
|
||||
const newState = {
|
||||
...state,
|
||||
messages: [...state.messages],
|
||||
streamingMessage: state.streamingMessage ? { ...state.streamingMessage } : undefined,
|
||||
abortController: state.abortController
|
||||
};
|
||||
setSessionState(newState);
|
||||
// Subscribe to session events using shared hook
|
||||
useSessionSubscription('sessionUpdated', (updatedSessionId: string, state: SessionState) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
updateSessionState(state);
|
||||
}
|
||||
}, [sessionId, updateSessionState]);
|
||||
|
||||
useSessionSubscription('messageAdded', (updatedSessionId: string, _message: AIMessage) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
updateSessionState(session);
|
||||
}
|
||||
};
|
||||
}
|
||||
}, [sessionId, updateSessionState]);
|
||||
|
||||
const handleMessageAdded = (updatedSessionId: string, _message: AIMessage) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
// Get fresh session state and force update by creating new object
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
// Create a deep copy to ensure React detects the change
|
||||
const newState = {
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined,
|
||||
abortController: session.abortController
|
||||
};
|
||||
setSessionState(newState);
|
||||
}
|
||||
useSessionSubscription('streamingUpdate', (updatedSessionId: string, _content: string, _toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
updateSessionState(session);
|
||||
}
|
||||
};
|
||||
}
|
||||
}, [sessionId, updateSessionState]);
|
||||
|
||||
const handleStreamingUpdate = (updatedSessionId: string, _content: string, _toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
// Get fresh session state and force update by creating new object
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
// Create a deep copy to ensure React detects the change
|
||||
const newState = {
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined,
|
||||
abortController: session.abortController
|
||||
};
|
||||
setSessionState(newState);
|
||||
}
|
||||
useSessionSubscription('loadingChanged', (updatedSessionId: string, isLoading: boolean) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
updateSessionState(session);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLoadingChanged = (updatedSessionId: string, isLoading: boolean) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
// Update session state immediately and force update by creating new object
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
// Create a deep copy to ensure React detects the change
|
||||
const newState = {
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined,
|
||||
abortController: session.abortController
|
||||
};
|
||||
setSessionState(newState);
|
||||
}
|
||||
|
||||
if (onUpdateMetadata) {
|
||||
if (isLoading) {
|
||||
onUpdateMetadata('Shakespeare', `Working on ${projectName}...`);
|
||||
}
|
||||
}
|
||||
if (onUpdateMetadata && 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]);
|
||||
}
|
||||
}, [sessionId, updateSessionState, onUpdateMetadata, projectName]);
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useSessionManager } from './useSessionManager';
|
||||
import type { SessionManagerEvents } from '@/lib/SessionManager';
|
||||
|
||||
/**
|
||||
* Custom hook for subscribing to SessionManager events with automatic cleanup
|
||||
*/
|
||||
export function useSessionSubscription<K extends keyof SessionManagerEvents>(
|
||||
event: K,
|
||||
handler: SessionManagerEvents[K],
|
||||
deps: React.DependencyList = []
|
||||
): void {
|
||||
const sessionManager = useSessionManager();
|
||||
|
||||
useEffect(() => {
|
||||
sessionManager.on(event, handler);
|
||||
|
||||
return () => {
|
||||
sessionManager.off(event, handler);
|
||||
};
|
||||
}, [sessionManager, event, handler, ...deps]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}
|
||||
@@ -4,6 +4,15 @@ import { DotAI } from './DotAI';
|
||||
import { parseProviderModel } from './parseProviderModel';
|
||||
import type { Tool } from './tools/Tool';
|
||||
|
||||
// Simple debounce utility
|
||||
function debounce<T extends (...args: unknown[]) => void>(func: T, wait: number): T {
|
||||
let timeout: NodeJS.Timeout;
|
||||
return ((...args: Parameters<T>) => {
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(() => func(...args), wait);
|
||||
}) as T;
|
||||
}
|
||||
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||
|
||||
export interface SessionConfig {
|
||||
@@ -56,6 +65,11 @@ export class SessionManager {
|
||||
providers: Record<string, { baseURL: string; apiKey?: string }>;
|
||||
};
|
||||
|
||||
// Performance and memory management
|
||||
private readonly MAX_SESSIONS = 50;
|
||||
private readonly MAX_SESSION_AGE = 7 * 24 * 60 * 60 * 1000; // 7 days
|
||||
private debouncedPersist = debounce(this.persistSessions.bind(this), 1000);
|
||||
|
||||
constructor(fs: JSRuntimeFS, aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string }> }) {
|
||||
this.fs = fs;
|
||||
this.aiSettings = aiSettings;
|
||||
@@ -165,10 +179,14 @@ export class SessionManager {
|
||||
// Save to history
|
||||
await this.saveSessionHistory(sessionId);
|
||||
|
||||
this.persistSessions();
|
||||
// Use debounced persistence for performance
|
||||
this.debouncedPersist();
|
||||
|
||||
this.emit('messageAdded', sessionId, message);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
|
||||
// Clean up old sessions periodically
|
||||
this.cleanupOldSessions();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -410,13 +428,32 @@ export class SessionManager {
|
||||
} catch (error) {
|
||||
console.error('AI generation error:', error);
|
||||
|
||||
// Add error message
|
||||
const errorMessage: AIMessage = {
|
||||
// Handle different types of errors appropriately
|
||||
let errorMessage: string;
|
||||
if (error && typeof error === 'object' && 'name' in error) {
|
||||
if (error.name === 'AbortError') {
|
||||
// User cancelled the request - don't add error message
|
||||
return;
|
||||
} else if (error.name === 'TypeError' && error.message.includes('fetch')) {
|
||||
errorMessage = 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.';
|
||||
} else if (error.message?.includes('API key')) {
|
||||
errorMessage = 'Authentication error: Please check your API key in AI settings.';
|
||||
} else if (error.message?.includes('rate limit')) {
|
||||
errorMessage = 'Rate limit exceeded. Please wait a moment before trying again.';
|
||||
} else {
|
||||
errorMessage = `AI service error: ${error.message || 'Unknown error occurred'}`;
|
||||
}
|
||||
} else {
|
||||
errorMessage = 'Sorry, I encountered an unexpected error. Please try again.';
|
||||
}
|
||||
|
||||
// Add user-friendly error message
|
||||
const errorAIMessage: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.'
|
||||
content: errorMessage
|
||||
};
|
||||
|
||||
await this.addMessage(sessionId, errorMessage);
|
||||
await this.addMessage(sessionId, errorAIMessage);
|
||||
} finally {
|
||||
session.isLoading = false;
|
||||
session.streamingMessage = undefined;
|
||||
@@ -446,6 +483,35 @@ export class SessionManager {
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up old sessions to prevent memory bloat
|
||||
*/
|
||||
private cleanupOldSessions(): void {
|
||||
const now = Date.now();
|
||||
const sessionIdsToDelete: string[] = [];
|
||||
|
||||
for (const [id, session] of this.sessions) {
|
||||
if (now - session.lastActivity.getTime() > this.MAX_SESSION_AGE) {
|
||||
sessionIdsToDelete.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
// Delete old sessions
|
||||
sessionIdsToDelete.forEach(id => this.deleteSession(id));
|
||||
|
||||
// If we still have too many sessions, delete the oldest ones
|
||||
if (this.sessions.size > this.MAX_SESSIONS) {
|
||||
const sortedSessions = Array.from(this.sessions.entries())
|
||||
.sort(([, a], [, b]) => a.lastActivity.getTime() - b.lastActivity.getTime());
|
||||
|
||||
const sessionsToDelete = sortedSessions
|
||||
.slice(0, this.sessions.size - this.MAX_SESSIONS)
|
||||
.map(([id]) => id);
|
||||
|
||||
sessionsToDelete.forEach(id => this.deleteSession(id));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a new session (clear messages but keep configuration)
|
||||
*/
|
||||
@@ -462,7 +528,7 @@ export class SessionManager {
|
||||
session.sessionName = DotAI.generateSessionName();
|
||||
session.lastActivity = new Date();
|
||||
|
||||
this.persistSessions();
|
||||
this.debouncedPersist();
|
||||
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import type { AIMessage } from '@/hooks/useAIChat';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
|
||||
Reference in new issue
Block a user