/** * AIChatSidePanel - Main AI chat interface side panel * * Zed-style agent panel with agent selector, scoped chat sessions, * message list, input area, and session history drawer. */ import { History, Plus, Trash2, X, } from 'lucide-react'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { streamText, stepCountIs } from 'ai'; import { cn } from '../lib/utils'; import { useWindowControls } from '../application/state/useWindowControls'; import { useImageUpload } from '../application/state/useImageUpload'; import type { AIPermissionMode, AISession, AISessionScope, ChatMessage, DiscoveredAgent, ExternalAgentConfig, ProviderConfig, } from '../infrastructure/ai/types'; import { getAgentModelPresets } from '../infrastructure/ai/types'; import { buildSystemPrompt } from '../infrastructure/ai/cattyAgent/systemPrompt'; import { createModelFromConfig } from '../infrastructure/ai/sdk/providers'; import { createCattyTools } from '../infrastructure/ai/sdk/tools'; import { exportAsMarkdown, exportAsJSON, exportAsPlainText, getExportFilename } from '../infrastructure/ai/conversationExport'; import { runExternalAgentTurn } from '../infrastructure/ai/externalAgentAdapter'; import { runAcpAgentTurn } from '../infrastructure/ai/acpAgentAdapter'; import { runClaudeAgentTurn } from '../infrastructure/ai/claudeAgentAdapter'; import { useAgentDiscovery } from '../application/state/useAgentDiscovery'; import { Button } from './ui/button'; import { ScrollArea } from './ui/scroll-area'; import AgentSelector from './ai/AgentSelector'; import ChatInput from './ai/ChatInput'; import ChatMessageList from './ai/ChatMessageList'; import ConversationExport from './ai/ConversationExport'; // ------------------------------------------------------------------- // Props // ------------------------------------------------------------------- interface AIChatSidePanelProps { // Session state sessions: AISession[]; activeSessionId: string | null; setActiveSessionId: (id: string | null) => void; createSession: (scope: AISessionScope, agentId?: string) => AISession; deleteSession: (sessionId: string) => void; updateSessionTitle: (sessionId: string, title: string) => void; addMessageToSession: (sessionId: string, message: ChatMessage) => void; updateLastMessage: ( sessionId: string, updater: (msg: ChatMessage) => ChatMessage, ) => void; // Provider config providers: ProviderConfig[]; activeProviderId: string; activeModelId: string; // Agent info defaultAgentId: string; externalAgents: ExternalAgentConfig[]; setExternalAgents?: (value: ExternalAgentConfig[] | ((prev: ExternalAgentConfig[]) => ExternalAgentConfig[])) => void; // Permission globalPermissionMode: AIPermissionMode; commandBlocklist?: string[]; // Context scopeType: 'terminal' | 'workspace'; scopeTargetId?: string; scopeHostIds?: string[]; scopeLabel?: string; // Terminal session context (from parent) terminalSessions?: Array<{ sessionId: string; hostId: string; hostname: string; label: string; os?: string; username?: string; connected: boolean; }>; // Visibility isVisible?: boolean; } // ------------------------------------------------------------------- // Helpers // ------------------------------------------------------------------- function generateId(): string { return `msg-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; } // ------------------------------------------------------------------- // Component // ------------------------------------------------------------------- const AIChatSidePanelInner: React.FC = ({ sessions, activeSessionId, setActiveSessionId, createSession, deleteSession, updateSessionTitle, addMessageToSession, updateLastMessage, providers, activeProviderId, activeModelId, defaultAgentId, externalAgents, setExternalAgents, globalPermissionMode, commandBlocklist, scopeType, scopeTargetId, scopeHostIds, scopeLabel, terminalSessions = [], isVisible = true, }) => { const [inputValue, setInputValue] = useState(''); const [isStreaming, setIsStreaming] = useState(false); const [showHistory, setShowHistory] = useState(false); const [currentAgentId, setCurrentAgentId] = useState(defaultAgentId); const [selectedAgentModel, setSelectedAgentModel] = useState(undefined); const abortControllerRef = useRef(null); const { images, addImages, removeImage, clearImages } = useImageUpload(); const { openSettingsWindow } = useWindowControls(); // Reset active session when switching terminal/workspace const prevScopeTargetIdRef = useRef(scopeTargetId); useEffect(() => { if (scopeTargetId !== prevScopeTargetIdRef.current) { prevScopeTargetIdRef.current = scopeTargetId; setActiveSessionId(null); } }, [scopeTargetId, setActiveSessionId]); // Agent discovery const { discoveredAgents, isDiscovering, rediscover, enableAgent, } = useAgentDiscovery(externalAgents, setExternalAgents); const handleEnableDiscoveredAgent = useCallback( (agent: DiscoveredAgent) => { const config = enableAgent(agent); setExternalAgents?.((prev) => [...prev, config]); }, [enableAgent, setExternalAgents], ); // Active session const activeSession = useMemo( () => sessions.find((s) => s.id === activeSessionId) ?? null, [sessions, activeSessionId], ); const messages = activeSession?.messages ?? []; // Active provider info const activeProvider = useMemo( () => providers.find((p) => p.id === activeProviderId), [providers, activeProviderId], ); const providerDisplayName = activeProvider?.name ?? ''; const modelDisplayName = activeModelId || activeProvider?.defaultModel || ''; // Agent model presets for the current external agent const currentAgentConfig = useMemo( () => currentAgentId !== 'catty' ? externalAgents.find(a => a.id === currentAgentId) : undefined, [currentAgentId, externalAgents], ); const agentModelPresets = useMemo( () => getAgentModelPresets(currentAgentConfig?.command), [currentAgentConfig?.command], ); // Filtered sessions for history (matching current scope type) const historySessions = useMemo( () => sessions .filter((s) => s.scope.type === scopeType && s.scope.targetId === scopeTargetId) .sort((a, b) => b.updatedAt - a.updatedAt), [sessions, scopeType, scopeTargetId], ); // ------------------------------------------------------------------- // Handlers // ------------------------------------------------------------------- const handleNewChat = useCallback(() => { const scope: AISessionScope = { type: scopeType, targetId: scopeTargetId, hostIds: scopeHostIds, }; const session = createSession(scope, currentAgentId); setActiveSessionId(session.id); setShowHistory(false); setInputValue(''); }, [ scopeType, scopeTargetId, scopeHostIds, currentAgentId, createSession, setActiveSessionId, ]); const handleOpenSettings = useCallback(() => { void openSettingsWindow(); }, [openSettingsWindow]); const handleSend = useCallback(async () => { const trimmed = inputValue.trim(); console.log('[AIChatPanel] handleSend called, trimmed:', JSON.stringify(trimmed?.slice(0, 50)), 'isStreaming:', isStreaming, 'currentAgentId:', currentAgentId); if (!trimmed || isStreaming) return; const isExternalAgent = currentAgentId !== 'catty'; console.log('[AIChatPanel] isExternalAgent:', isExternalAgent, 'activeProvider:', activeProvider?.id); // For built-in agent, we need a provider configured if (!isExternalAgent && !activeProvider) { console.warn('[AIChatPanel] No active provider configured for built-in agent, aborting'); return; } // Create session if needed let sessionId = activeSessionId; if (!sessionId) { const scope: AISessionScope = { type: scopeType, targetId: scopeTargetId, hostIds: scopeHostIds, }; const session = createSession(scope, currentAgentId); sessionId = session.id; setActiveSessionId(sessionId); } // Capture images before clearing const attachedImages = images.map(img => ({ base64Data: img.base64Data, mediaType: img.mediaType, filename: img.filename })); // Add user message (with images if any) const userMessage: ChatMessage = { id: generateId(), role: 'user', content: trimmed, ...(attachedImages.length > 0 ? { images: attachedImages } : {}), timestamp: Date.now(), }; addMessageToSession(sessionId, userMessage); setInputValue(''); clearImages(); setIsStreaming(true); // Create assistant message placeholder for streaming const agentConfig = isExternalAgent ? externalAgents.find(a => a.id === currentAgentId) : undefined; addMessageToSession(sessionId, { id: generateId(), role: 'assistant', content: '', timestamp: Date.now(), model: isExternalAgent ? (agentConfig?.name || 'external') : (activeModelId || activeProvider?.defaultModel || ''), providerId: isExternalAgent ? undefined : activeProvider?.providerId, }); // Abort controller for cancellation const abortController = new AbortController(); abortControllerRef.current = abortController; // Get current session for context const currentSession = sessions.find((s) => s.id === sessionId); console.log('[AIChatPanel] agentConfig:', agentConfig ? { id: agentConfig.id, name: agentConfig.name, sdkType: agentConfig.sdkType, acpCommand: agentConfig.acpCommand } : 'catty'); if (isExternalAgent) { if (!agentConfig) { updateLastMessage(sessionId, msg => ({ ...msg, content: 'External agent not found. Please check settings.', executionStatus: 'failed', })); setIsStreaming(false); return; } const bridge = (window as unknown as { netcatty?: Record }).netcatty as Record unknown> | undefined; console.log('[AIChatPanel] bridge available:', !!bridge, 'sdkType:', agentConfig.sdkType, 'acpCommand:', agentConfig.acpCommand); // Use Claude Agent SDK if the agent specifies it if (agentConfig.sdkType === 'claude-agent-sdk' && bridge) { const requestId = `claude_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`; console.log('[AIChatPanel] → Claude Agent SDK path, requestId:', requestId); let claudeNeedsNewAssistantMsg = false; const maybeCreateClaudeAssistantMsg = () => { if (claudeNeedsNewAssistantMsg) { claudeNeedsNewAssistantMsg = false; addMessageToSession(sessionId!, { id: generateId(), role: 'assistant', content: '', timestamp: Date.now(), model: agentConfig?.name || 'external', }); } }; try { await runClaudeAgentTurn( bridge, requestId, sessionId!, agentConfig, trimmed, { onTextDelta: (text: string) => { maybeCreateClaudeAssistantMsg(); updateLastMessage(sessionId!, msg => ({ ...msg, content: msg.content + text, thinkingDurationMs: msg.thinking && !msg.thinkingDurationMs ? Date.now() - msg.timestamp : msg.thinkingDurationMs, })); }, onThinkingDelta: (text: string) => { maybeCreateClaudeAssistantMsg(); updateLastMessage(sessionId!, msg => ({ ...msg, thinking: (msg.thinking || '') + text, })); }, onThinkingDone: () => { updateLastMessage(sessionId!, msg => ({ ...msg, thinkingDurationMs: msg.thinkingDurationMs || (Date.now() - msg.timestamp), })); }, onToolCall: (toolName: string, args: Record) => { maybeCreateClaudeAssistantMsg(); updateLastMessage(sessionId!, msg => ({ ...msg, toolCalls: [...(msg.toolCalls || []), { id: `tc_${Date.now()}`, name: toolName, arguments: args, }], executionStatus: 'running', })); }, onToolResult: (toolCallId: string, result: string) => { updateLastMessage(sessionId!, msg => { if (msg.role === 'assistant' && msg.executionStatus === 'running') { return { ...msg, executionStatus: 'completed' }; } return msg; }); addMessageToSession(sessionId!, { id: generateId(), role: 'tool', content: '', toolResults: [{ toolCallId, content: result, isError: false }], timestamp: Date.now(), executionStatus: 'completed', }); claudeNeedsNewAssistantMsg = true; }, onError: (error: string) => { maybeCreateClaudeAssistantMsg(); updateLastMessage(sessionId!, msg => ({ ...msg, content: msg.content + '\n\n**Error:** ' + error, executionStatus: 'failed', })); }, onDone: () => {}, }, abortController.signal, selectedAgentModel, ); } catch (err) { if (!abortController.signal.aborted) { updateLastMessage(sessionId!, msg => ({ ...msg, content: msg.content + '\n\n**Error:** ' + (err instanceof Error ? err.message : String(err)), })); } } } else if (agentConfig.acpCommand && bridge) { // Use ACP protocol if the agent supports it const requestId = `acp_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`; console.log('[AIChatPanel] → ACP path, requestId:', requestId, 'acpCommand:', agentConfig.acpCommand); // Push terminal session metadata to MCP bridge before streaming const mcpBridge = bridge as unknown as { aiMcpUpdateSessions?: (sessions: typeof terminalSessions) => Promise }; if (mcpBridge.aiMcpUpdateSessions && terminalSessions.length > 0) { await mcpBridge.aiMcpUpdateSessions(terminalSessions); } // Try to find an API key from configured providers for this agent const openaiProvider = providers.find(p => p.providerId === 'openai' && p.enabled && p.apiKey); const agentApiKey = openaiProvider?.apiKey; try { // Mutable flag: set after tool-result, cleared when new assistant msg is created let needsNewAssistantMsg = false; const maybeCreateAssistantMsg = () => { if (needsNewAssistantMsg) { needsNewAssistantMsg = false; addMessageToSession(sessionId!, { id: generateId(), role: 'assistant', content: '', timestamp: Date.now(), model: agentConfig?.name || 'external', }); } }; await runAcpAgentTurn( bridge, requestId, sessionId!, agentConfig, trimmed, { onTextDelta: (text: string) => { maybeCreateAssistantMsg(); updateLastMessage(sessionId!, msg => ({ ...msg, content: msg.content + text, thinkingDurationMs: msg.thinking && !msg.thinkingDurationMs ? Date.now() - msg.timestamp : msg.thinkingDurationMs, })); }, onThinkingDelta: (text: string) => { maybeCreateAssistantMsg(); updateLastMessage(sessionId!, msg => ({ ...msg, thinking: (msg.thinking || '') + text, })); }, onThinkingDone: () => { updateLastMessage(sessionId!, msg => ({ ...msg, thinkingDurationMs: msg.thinkingDurationMs || (Date.now() - msg.timestamp), })); }, onToolCall: (toolName: string, args: Record) => { maybeCreateAssistantMsg(); updateLastMessage(sessionId!, msg => ({ ...msg, toolCalls: [...(msg.toolCalls || []), { id: `tc_${Date.now()}`, name: toolName, arguments: args, }], executionStatus: 'running', })); }, onToolResult: (toolCallId: string, result: string) => { // Mark previous assistant message's tool calls as completed updateLastMessage(sessionId!, msg => { if (msg.role === 'assistant' && msg.executionStatus === 'running') { return { ...msg, executionStatus: 'completed' }; } return msg; }); addMessageToSession(sessionId!, { id: generateId(), role: 'tool', content: '', toolResults: [{ toolCallId, content: result, isError: false }], timestamp: Date.now(), executionStatus: 'completed', }); // Next text/thinking/toolCall should go into a new assistant message needsNewAssistantMsg = true; }, onError: (error: string) => { maybeCreateAssistantMsg(); updateLastMessage(sessionId!, msg => ({ ...msg, content: msg.content + '\n\n**Error:** ' + error, executionStatus: 'failed', })); }, onDone: () => {}, }, abortController.signal, agentApiKey, selectedAgentModel, attachedImages.length > 0 ? attachedImages : undefined, ); } catch (err) { if (!abortController.signal.aborted) { updateLastMessage(sessionId!, msg => ({ ...msg, content: msg.content + '\n\n**Error:** ' + (err instanceof Error ? err.message : String(err)), })); } } } else { // Fallback: spawn as raw process try { await runExternalAgentTurn( agentConfig, trimmed, { onTextDelta: (text: string) => { updateLastMessage(sessionId!, msg => ({ ...msg, content: msg.content + text })); }, onError: (error: string) => { updateLastMessage(sessionId!, msg => ({ ...msg, content: msg.content + '\n\n**Error:** ' + error, executionStatus: 'failed', })); }, onDone: () => {}, }, bridge as Parameters[3], abortController.signal, ); } catch (err) { if (!abortController.signal.aborted) { updateLastMessage(sessionId!, msg => ({ ...msg, content: msg.content + '\n\n**Error:** ' + (err instanceof Error ? err.message : String(err)), })); } } } setIsStreaming(false); abortControllerRef.current = null; if ( currentSession && (!currentSession.title || currentSession.title === 'New Chat') ) { const title = trimmed.length > 50 ? trimmed.slice(0, 50) + '...' : trimmed; updateSessionTitle(sessionId!, title); } return; } // --- Catty Agent: Vercel AI SDK streamText --- const bridge = (window as unknown as { netcatty?: Record }).netcatty; const tools = createCattyTools(bridge, { sessions: terminalSessions, workspaceId: scopeTargetId, workspaceName: scopeLabel, }, commandBlocklist); const systemPrompt = buildSystemPrompt({ scopeType, scopeLabel, hosts: terminalSessions.map(s => ({ sessionId: s.sessionId, hostname: s.hostname, label: s.label, os: s.os, username: s.username, connected: s.connected, })), permissionMode: globalPermissionMode, }); // Decrypt API key before passing to SDK let decryptedApiKey = activeProvider.apiKey; if (decryptedApiKey && bridge?.credentialsDecrypt) { try { decryptedApiKey = await (bridge as { credentialsDecrypt: (v: string) => Promise }).credentialsDecrypt(decryptedApiKey) ?? decryptedApiKey; } catch (e) { console.warn('[Catty] API key decryption failed:', e); } } console.log('[Catty] Creating model:', { providerId: activeProvider.providerId, baseURL: activeProvider.baseURL, hasApiKey: !!decryptedApiKey, model: activeModelId || activeProvider.defaultModel || '', }); const model = createModelFromConfig({ ...activeProvider, apiKey: decryptedApiKey, defaultModel: activeModelId || activeProvider.defaultModel || '', }); try { // Build message array for the SDK. // Only include user and assistant TEXT messages — tool call/result // history is managed internally by each streamText invocation. const sdkMessages: Array<{ role: 'user' | 'assistant'; content: string }> = []; for (const m of (currentSession?.messages ?? [])) { if (m.role === 'user') { sdkMessages.push({ role: 'user', content: m.content }); } else if (m.role === 'assistant' && m.content) { sdkMessages.push({ role: 'assistant', content: m.content }); } // Skip tool messages and empty assistant messages (tool-call-only) } sdkMessages.push({ role: 'user', content: trimmed }); console.log('[Catty] streamText request:', { modelId: model.modelId, messageCount: sdkMessages.length, hasTools: Object.keys(tools).length, systemPromptLength: systemPrompt.length, }); const result = streamText({ model, messages: sdkMessages, system: systemPrompt, tools, stopWhen: stepCountIs(20), abortSignal: abortController.signal, }); // Stream the response using getReader() to avoid Electron stream hanging issues let chunkIndex = 0; // Track last message role locally (React state is stale in async closures) let lastAddedRole: 'assistant' | 'tool' = 'assistant'; const reader = result.fullStream.getReader(); while (true) { const { done, value: chunk } = await reader.read(); if (done) break; if (chunkIndex < 10) { console.log(`[Catty] chunk[${chunkIndex}]:`, JSON.stringify(chunk).slice(0, 200)); } chunkIndex++; switch (chunk.type) { case 'text': case 'text-delta': { const text = (chunk as unknown as { text?: string; textDelta?: string }).text ?? (chunk as unknown as { textDelta?: string }).textDelta; if (text) { // If last message was a tool result, create a new assistant message first if (lastAddedRole === 'tool') { addMessageToSession(sessionId!, { id: generateId(), role: 'assistant', content: '', timestamp: Date.now(), }); lastAddedRole = 'assistant'; } updateLastMessage(sessionId!, msg => ({ ...msg, content: msg.content + text, })); } break; } case 'reasoning': case 'reasoning-start': case 'reasoning-delta': { const rText = (chunk as unknown as { text?: string }).text; if (rText) { if (lastAddedRole === 'tool') { addMessageToSession(sessionId!, { id: generateId(), role: 'assistant', content: '', timestamp: Date.now(), }); lastAddedRole = 'assistant'; } updateLastMessage(sessionId!, msg => ({ ...msg, thinking: (msg.thinking || '') + rText, })); } break; } case 'reasoning-end': case 'text-start': case 'text-end': case 'start': case 'finish': case 'start-step': case 'finish-step': // Lifecycle events, no action needed break; case 'tool-call': console.log(`[Catty] tool-call: ${chunk.toolName}`); updateLastMessage(sessionId!, msg => ({ ...msg, toolCalls: [...(msg.toolCalls || []), { id: chunk.toolCallId, name: chunk.toolName, arguments: (chunk as unknown as { input?: unknown; args?: unknown }).input ?? (chunk as unknown as { args?: unknown }).args, }], executionStatus: 'running', })); break; case 'tool-result': { const toolOutput = (chunk as unknown as { output?: unknown; result?: unknown }).output ?? (chunk as unknown as { result?: unknown }).result; console.log(`[Catty] tool-result: ${chunk.toolCallId}`); addMessageToSession(sessionId!, { id: generateId(), role: 'tool', content: '', toolResults: [{ toolCallId: chunk.toolCallId, content: typeof toolOutput === 'string' ? toolOutput : JSON.stringify(toolOutput), isError: false, }], timestamp: Date.now(), executionStatus: 'completed', }); lastAddedRole = 'tool'; break; } case 'error': updateLastMessage(sessionId!, msg => ({ ...msg, content: msg.content + '\n\n**Error:** ' + String(chunk.error), executionStatus: 'failed', })); break; default: // tool-input-start/delta/end and other unknown types break; } } console.log(`[Catty] stream finished, total chunks: ${chunkIndex}`); } catch (err) { console.error('[Catty] streamText error:', err); if (!abortController.signal.aborted) { updateLastMessage(sessionId!, msg => ({ ...msg, content: msg.content + '\n\n**Error:** ' + (err instanceof Error ? err.message : String(err)), })); } } finally { setIsStreaming(false); abortControllerRef.current = null; // Auto-title the session from first user message const finalSession = sessions.find(s => s.id === sessionId); if ( finalSession && (!finalSession.title || finalSession.title === 'New Chat') ) { const title = trimmed.length > 50 ? trimmed.slice(0, 50) + '...' : trimmed; updateSessionTitle(sessionId!, title); } } }, [ inputValue, isStreaming, activeProvider, activeSessionId, scopeType, scopeTargetId, scopeHostIds, scopeLabel, currentAgentId, activeModelId, globalPermissionMode, commandBlocklist, providers, sessions, externalAgents, terminalSessions, createSession, setActiveSessionId, addMessageToSession, updateLastMessage, updateSessionTitle, selectedAgentModel, images, clearImages, ]); const handleStop = useCallback(() => { abortControllerRef.current?.abort(); setIsStreaming(false); }, []); const handleSelectSession = useCallback( (sessionId: string) => { setActiveSessionId(sessionId); // Restore agent selector to match the session's bound agent const session = sessions.find((s) => s.id === sessionId); if (session) { setCurrentAgentId(session.agentId); } setShowHistory(false); }, [setActiveSessionId, sessions], ); const handleDeleteSession = useCallback( (e: React.MouseEvent, sessionId: string) => { e.stopPropagation(); const bridge = (window as unknown as { netcatty?: { aiAcpCleanup?: (chatSessionId: string) => Promise<{ ok: boolean }> } }).netcatty; void bridge?.aiAcpCleanup?.(sessionId).catch(() => {}); deleteSession(sessionId); if (activeSessionId === sessionId) { setActiveSessionId(null); } }, [deleteSession, activeSessionId, setActiveSessionId], ); const handleAgentChange = useCallback((agentId: string) => { setCurrentAgentId(agentId); // Switching agent deactivates current session; a new one is created on next send setActiveSessionId(null); }, [setActiveSessionId]); const handleExport = useCallback((format: 'md' | 'json' | 'txt') => { if (!activeSession) return; let content: string; switch (format) { case 'md': content = exportAsMarkdown(activeSession); break; case 'json': content = exportAsJSON(activeSession); break; case 'txt': content = exportAsPlainText(activeSession); break; } const filename = getExportFilename(activeSession, format); // Create a download blob const blob = new Blob([content], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }, [activeSession]); // ------------------------------------------------------------------- // Render // ------------------------------------------------------------------- if (!isVisible) return null; return (
{/* ── Header ── */}
{/* ── Main content ── */} {showHistory ? ( setShowHistory(false)} /> ) : ( <> {/* Chat messages */} {/* Recent sessions (Zed-style, shown when no messages) */} {messages.length === 0 && historySessions.length > 0 && (
Recent
{historySessions.slice(0, 3).map((session) => ( ))}
)} {/* Input area */} a.id === currentAgentId)?.name} modelPresets={agentModelPresets} selectedModelId={selectedAgentModel} onModelSelect={setSelectedAgentModel} images={images} onAddImages={addImages} onRemoveImage={removeImage} hosts={terminalSessions.map(s => ({ sessionId: s.sessionId, hostname: s.hostname, label: s.label, connected: s.connected }))} /> )}
); }; // ------------------------------------------------------------------- // Session History Drawer // ------------------------------------------------------------------- interface SessionHistoryDrawerProps { sessions: AISession[]; activeSessionId: string | null; onSelect: (sessionId: string) => void; onDelete: (e: React.MouseEvent, sessionId: string) => void; onClose: () => void; } const SessionHistoryDrawer: React.FC = ({ sessions, activeSessionId, onSelect, onDelete, onClose, }) => { return (
All Sessions
{sessions.length === 0 ? (

No previous sessions

) : ( sessions.map((session) => { const isActive = session.id === activeSessionId; const time = new Date(session.updatedAt); const timeStr = formatRelativeTime(time); return (
); }) )}
); }; // ------------------------------------------------------------------- // Helpers // ------------------------------------------------------------------- function formatRelativeTime(date: Date): string { const now = Date.now(); const diff = now - date.getTime(); const minutes = Math.floor(diff / 60_000); const hours = Math.floor(diff / 3_600_000); const days = Math.floor(diff / 86_400_000); if (minutes < 1) return 'Just now'; if (minutes < 60) return `${minutes}m ago`; if (hours < 24) return `${hours}h ago`; if (days < 7) return `${days}d ago`; return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); } // ------------------------------------------------------------------- // Export // ------------------------------------------------------------------- const AIChatSidePanel = React.memo(AIChatSidePanelInner); AIChatSidePanel.displayName = 'AIChatSidePanel'; export default AIChatSidePanel; export { AIChatSidePanel }; export type { AIChatSidePanelProps };