import React, { useEffect, useMemo, useRef, useState } from 'react'; import { Download, FolderInput, MoreHorizontal, Pencil, Search, Trash2, X } from 'lucide-react'; import type { AISession, ExternalAgentConfig } from '../../infrastructure/ai/types'; import { useI18n } from '../../application/i18n/I18nProvider'; import { cn } from '../../lib/utils'; import { Dropdown, DropdownContent, DropdownTrigger } from '../ui/dropdown'; import { Input } from '../ui/input'; import { ScrollArea } from '../ui/scroll-area'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '../ui/select'; import { ConfirmDialog } from '../ui/confirm-dialog'; import { SESSION_HISTORY_ROW_CLASSNAMES } from './sessionHistoryLayout'; import { formatRelativeTime } from '../AIChatSessionHistoryDrawer'; import { buildGlobalManagerRows, collectGlobalManagerAgentIds, filterGlobalManagerRows, type GlobalManagerHostInfo, type GlobalManagerScopeTarget, type GlobalManagerTerminalInfo, } from './globalSessionManagerRows'; // ------------------------------------------------------------------- // Global AI Session Manager // ------------------------------------------------------------------- // Scope-agnostic view over all saved AI chats. Clicking any chat opens // it directly in the viewing panel (automatically attaching past chats // to the current panel). Secondary management actions (rename, export, // move to another open terminal/workspace, confirm-gated delete) live // inside a single overflow menu so rows stay calm and scannable. // ------------------------------------------------------------------- interface GlobalAIChatSessionManagerProps { sessions: AISession[]; activeSessionIdMap: Readonly>; currentScopeType: 'terminal' | 'workspace'; currentScopeTargetId?: string; /** * Host ids of the viewing panel's own scope; carried onto chats moved to * "This panel" so the destination's host association survives. */ currentScopeHostIds?: ReadonlyArray; workspaces: ReadonlyArray<{ id: string; title: string }>; terminalInfos: ReadonlyArray; hosts?: ReadonlyArray; externalAgents: ExternalAgentConfig[]; rebindTargets: GlobalManagerScopeTarget[]; onSelect: (sessionId: string) => void; onRebind: (sessionId: string, target: GlobalManagerScopeTarget) => void; onRename?: (sessionId: string, title: string) => void; onDelete: (sessionId: string) => void; onExport: (sessionId: string) => void; } const MANAGER_RENDER_BATCH = 80; const MANAGER_RENDER_STEP = 60; export const GlobalAIChatSessionManager: React.FC = ({ sessions, activeSessionIdMap, currentScopeType, currentScopeTargetId, currentScopeHostIds, workspaces, terminalInfos, hosts, externalAgents, rebindTargets, onSelect, onRebind, onRename, onDelete, onExport, }) => { const { t } = useI18n(); const [searchQuery, setSearchQuery] = useState(''); const [agentFilter, setAgentFilter] = useState('all'); const [renderCount, setRenderCount] = useState(MANAGER_RENDER_BATCH); const [deleteTarget, setDeleteTarget] = useState(null); const [moveSession, setMoveSession] = useState(null); const [openMenuSessionId, setOpenMenuSessionId] = useState(null); const [renamingSessionId, setRenamingSessionId] = useState(null); const [renameDraft, setRenameDraft] = useState(''); const renameInputRef = useRef(null); const rows = useMemo( () => buildGlobalManagerRows({ sessions, activeSessionIdMap, currentScopeType, currentScopeTargetId, workspaces, terminalInfos, hosts, externalAgents, t, }), [sessions, activeSessionIdMap, currentScopeType, currentScopeTargetId, workspaces, terminalInfos, hosts, externalAgents, t], ); const agentIds = useMemo(() => collectGlobalManagerAgentIds(rows), [rows]); const showAgentMeta = agentIds.length > 1; const effectiveAgentFilter = agentFilter !== 'all' && agentIds.includes(agentFilter) ? agentFilter : 'all'; const filteredRows = useMemo( () => filterGlobalManagerRows(rows, { query: searchQuery, agentId: effectiveAgentFilter }), [rows, searchQuery, effectiveAgentFilter], ); useEffect(() => { setRenderCount(MANAGER_RENDER_BATCH); }, [searchQuery, agentFilter]); useEffect(() => { if (agentFilter !== 'all' && !agentIds.includes(agentFilter)) { setAgentFilter('all'); } }, [agentFilter, agentIds]); useEffect(() => { if (renamingSessionId) renameInputRef.current?.focus(); }, [renamingSessionId]); const displayedRows = filteredRows.slice(0, renderCount); const hiddenRowCount = Math.max(0, filteredRows.length - renderCount); const commitDelete = () => { if (!deleteTarget) return; onDelete(deleteTarget.id); setDeleteTarget(null); }; const beginRename = (session: AISession) => { setOpenMenuSessionId(null); setRenamingSessionId(session.id); setRenameDraft(session.title || ''); }; const commitRename = () => { if (renamingSessionId && renameDraft.trim()) { onRename?.(renamingSessionId, renameDraft.trim()); } setRenamingSessionId(null); setRenameDraft(''); }; const getOtherMoveTargets = (session: AISession) => rebindTargets.filter( (target) => session.scopeDangling || target.type !== session.scope.type || target.targetId !== session.scope.targetId, ); const chooseMoveTarget = (value: string) => { if (!moveSession || !value) return; if (value === 'here') { if (!currentScopeTargetId) return; onRebind(moveSession.id, { type: currentScopeType, targetId: currentScopeTargetId, label: '', hostIds: currentScopeHostIds && currentScopeHostIds.length > 0 ? [...currentScopeHostIds] : undefined, }); } else { const target = rebindTargets.find((candidate) => `${candidate.type}:${candidate.targetId}` === value); if (target) onRebind(moveSession.id, target); } setMoveSession(null); }; return (
setSearchQuery(event.target.value)} className="h-8 pl-8 pr-7 text-[12px]" /> {searchQuery && ( )}
{showAgentMeta && ( )}
{filteredRows.length === 0 ? (

{rows.length === 0 ? t('ai.chat.noSessions') : t('ai.chat.noMatchingSessions')}

) : ( <> {hiddenRowCount > 0 && ( )} {displayedRows.map((row) => { const otherMoveTargets = getOtherMoveTargets(row.session); const canMoveElsewhere = otherMoveTargets.length > 0; const isRenaming = renamingSessionId === row.session.id; const isMenuOpen = openMenuSessionId === row.session.id; const subtitleParts: string[] = []; if (row.scopeLabel) subtitleParts.push(row.scopeLabel); if (showAgentMeta) subtitleParts.push(row.agentLabel); if (row.messageCount > 0) { subtitleParts.push( t('ai.chat.managerMessagesCount').replace('{n}', String(row.messageCount)), ); } return (
{ if (!isRenaming && row.canActivate) onSelect(row.session.id); }} onKeyDown={(e) => { if (e.target !== e.currentTarget) return; if (!isRenaming && row.canActivate && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); onSelect(row.session.id); } }} className={cn( SESSION_HISTORY_ROW_CLASSNAMES.row, row.isCurrentActive ? 'text-foreground' : 'text-foreground/75 hover:text-foreground', !row.canActivate && 'cursor-default', )} data-session-id={row.session.id} data-scope-state={row.scopeState} >
{row.isCurrentActive && ( )} {isRenaming ? ( e.stopPropagation()} onKeyDown={(e) => { e.stopPropagation(); if (e.key === 'Enter') { e.preventDefault(); commitRename(); } else if (e.key === 'Escape') { e.preventDefault(); setRenamingSessionId(null); setRenameDraft(''); } }} onChange={(e) => setRenameDraft(e.target.value)} onBlur={commitRename} className="h-6 text-[12px]" /> ) : ( row.title )} {row.isActiveElsewhere && ( {t('ai.chat.managerBadgeActive')} )}
{subtitleParts.length > 0 && (
{subtitleParts.map((part, index) => ( {index > 0 && ยท} {part} ))}
)}
{formatRelativeTime(new Date(row.session.updatedAt), t)} setOpenMenuSessionId(open ? row.session.id : null)} > {onRename && ( )} {canMoveElsewhere && ( )}
{moveSession?.id === row.session.id && (
)} ); })} )}
{ if (!open) setDeleteTarget(null); }} onConfirm={commitDelete} />
); };