import { Loader2, MonitorPlay, Pencil, Plus, Trash2, Unplug, } from 'lucide-react'; import React, { memo, useCallback, useEffect, useState } from 'react'; import { useI18n } from '../../application/i18n/I18nProvider'; import type { useSystemManagerBackend } from '../../application/state/useSystemManagerBackend'; import { buildTmuxAttachCommand } from '../../domain/systemManager/tmuxShell'; import type { TmuxClientInfo, TmuxManageAction, TmuxSessionInfo, TmuxWindowInfo, } from '../../domain/systemManager/types'; import type { TerminalSession } from '../../types'; import { SystemPanelCollapsible, SystemPanelDetailStrip, SystemPanelInlineError, SystemPanelRoundButton, SystemPanelRow, SystemPanelSectionHeader, SystemPanelStatusBadge, } from './SystemPanelUi'; import { SystemPanelPromptDialog } from './SystemPanelPromptDialog'; import { openInteractiveTerminal } from './openInteractiveTerminal'; type Backend = ReturnType; type RenamePromptTarget = | { kind: 'session' } | { kind: 'window'; windowIndex: number; currentName: string }; interface PendingTarget { action: TmuxManageAction['action']; windowIndex?: number; } interface TmuxSessionCardProps { session: TmuxSessionInfo; sessionId: string; parentSession: TerminalSession; backend: Backend; onSessionsChanged: () => Promise; } export const TmuxSessionCard = memo(function TmuxSessionCard({ session, sessionId, parentSession, backend, onSessionsChanged, }: TmuxSessionCardProps) { const { t } = useI18n(); const [expanded, setExpanded] = useState(false); const [loadingDetails, setLoadingDetails] = useState(false); const [windows, setWindows] = useState([]); const [clients, setClients] = useState([]); const [renamePrompt, setRenamePrompt] = useState(null); const [newWindowOpen, setNewWindowOpen] = useState(false); const [actionError, setActionError] = useState(null); const [windowsLoadDetail, setWindowsLoadDetail] = useState(null); const [busy, setBusy] = useState(false); const [pending, setPending] = useState(null); const formatTmuxLoadError = useCallback(( message: string, debug?: { lastOutput?: string; tried?: string[] }, ) => { const parts = [message]; if (debug?.lastOutput) parts.push(debug.lastOutput); if (debug?.tried?.length) { parts.push(t('systemManager.tmux.lastCommand', { command: debug.tried[debug.tried.length - 1] ?? '' })); } return parts.filter(Boolean).join(' · '); }, [t]); const loadDetails = useCallback(async (): Promise => { setLoadingDetails(true); setActionError(null); setWindowsLoadDetail(null); try { const [windowsResult, clientsResult] = await Promise.all([ backend.listTmuxWindows({ sessionId, sessionName: session.name }), backend.listTmuxClients({ sessionId, sessionName: session.name }), ]); if (!windowsResult.success) { const detail = formatTmuxLoadError( windowsResult.error || t('systemManager.errors.loadTmuxWindows'), windowsResult.debug, ); setWindowsLoadDetail(detail); throw new Error(detail); } if (!clientsResult.success) throw new Error(clientsResult.error || t('systemManager.errors.loadTmuxClients')); const freshWindows = windowsResult.windows ?? []; if (freshWindows.length === 0 && session.windows > 0) { const detail = formatTmuxLoadError( t('systemManager.tmux.windowsMismatch', { count: String(session.windows) }), windowsResult.debug, ); setWindowsLoadDetail(detail); throw new Error(detail); } setWindows(freshWindows); setClients(clientsResult.clients ?? []); return freshWindows; } catch (err) { setActionError(err instanceof Error ? err.message : t('systemManager.errors.actionFailed')); setWindows([]); return null; } finally { setLoadingDetails(false); } }, [backend, formatTmuxLoadError, session.name, session.windows, sessionId, t]); useEffect(() => { if (expanded) void loadDetails(); }, [expanded, loadDetails]); const runAction = async (action: TmuxManageAction) => { setBusy(true); setPending({ action: action.action, windowIndex: 'windowIndex' in action ? action.windowIndex : undefined, }); setActionError(null); try { const result = await backend.tmuxAction({ sessionId, ...action }); if (!result.success) throw new Error(result.error || t('systemManager.errors.actionFailed')); const cardWillRemount = action.action === 'killSession' || action.action === 'renameSession'; if (!cardWillRemount && expanded) { await loadDetails(); } await onSessionsChanged(); } catch (err) { setActionError(err instanceof Error ? err.message : t('systemManager.errors.actionFailed')); } finally { setBusy(false); setPending(null); } }; const isPending = (action: TmuxManageAction['action'], windowIndex?: number) => pending !== null && pending.action === action && pending.windowIndex === windowIndex; const handleAttach = (windowIndex?: number) => { void openInteractiveTerminal( backend, parentSession, windowIndex !== undefined ? `tmux: ${session.name}:${windowIndex}` : `tmux: ${session.name}`, buildTmuxAttachCommand(session.name, windowIndex), ); }; return ( <> setExpanded((v) => !v)} title={session.name} subtitle={t('systemManager.tmux.windows', { count: String(session.windows) })} trailing={(
{session.attached ? t('systemManager.tmux.attached') : t('systemManager.tmux.detached')} handleAttach()}> setRenamePrompt({ kind: 'session' })} > {session.attached && ( { if (globalThis.confirm(t('systemManager.tmux.confirmDetachSession', { name: session.name }))) { void runAction({ action: 'detachSession', sessionName: session.name }); } }} > )} { if (globalThis.confirm(t('systemManager.tmux.confirmKillSession', { name: session.name }))) { void runAction({ action: 'killSession', sessionName: session.name }); } }} >
)} /> {actionError && } {loadingDetails && windows.length === 0 && (
{t('systemManager.tmux.loadingDetails')}
)} {clients.length > 0 && (
{t('systemManager.tmux.clients')}: {clients.map((c) => c.tty || c.name).join(', ')}
)} setNewWindowOpen(true)} className="shrink-0 h-5 px-1.5 rounded text-[10px] text-muted-foreground hover:text-foreground hover:bg-muted/60 inline-flex items-center gap-1 disabled:opacity-40" > {isPending('createWindow') ? : } {t('systemManager.tmux.newWindow')} )} > {t('systemManager.tmux.windowList')}{windows.length > 0 ? ` · ${windows.length}` : ''} {windows.map((tmuxWindow) => ( handleAttach(tmuxWindow.index)} > setRenamePrompt({ kind: 'window', windowIndex: tmuxWindow.index, currentName: tmuxWindow.name, })} > { if (globalThis.confirm(t('systemManager.tmux.confirmKillWindow', { name: tmuxWindow.name || String(tmuxWindow.index), }))) { void runAction({ action: 'killWindow', sessionName: session.name, windowIndex: tmuxWindow.index, }); } }} > )} /> ))} {!loadingDetails && windows.length === 0 && (
{windowsLoadDetail || actionError || t('systemManager.tmux.noWindows')}
)}
{ if (!open) setRenamePrompt(null); }} onSubmit={(values) => { const target = renamePrompt; setRenamePrompt(null); if (!target) return; if (target.kind === 'session') { if (values.name !== session.name) { void runAction({ action: 'renameSession', sessionName: session.name, newName: values.name }); } } else if (values.name !== target.currentName) { void runAction({ action: 'renameWindow', sessionName: session.name, windowIndex: target.windowIndex, newName: values.name, }); } }} /> { setNewWindowOpen(false); void runAction({ action: 'createWindow', sessionName: session.name, windowName: values.name || undefined, }); }} /> ); });