import { Box, FileText, Play, RotateCcw, Square, Terminal } from 'lucide-react'; import React, { memo, useCallback, useMemo, useRef, useState } from 'react'; import { useI18n } from '../../application/i18n/I18nProvider'; import type { useSystemManagerBackend } from '../../application/state/useSystemManagerBackend'; import type { TerminalSession } from '../../types'; import type { DockerContainerAction, DockerContainerInfo } from '../../domain/systemManager/types'; import { dockerContainerInfoEqual } from '../../domain/systemManager/pollEquals'; import { getContainerFlags, getContainerTone } from '../../domain/systemManager/containerState'; import { buildDockerExecShellCommand, buildDockerLogsCommand } from '../../domain/systemManager/dockerShell'; import { DockerContainerDetail } from './DockerContainerDetail'; import { DockerImageIcon } from './DockerImageIcon'; import { useStableListOrder, mergePollListByKey } from './listStable'; import { SystemPanelCollapsible, SystemPanelEmpty, SystemPanelError, SystemPanelList, SystemPanelMetaBar, SystemPanelRefreshButton, SystemPanelRoundButton, SystemPanelRow, SystemPanelSearch, SystemPanelSegmented, SystemPanelStatusBadge, SystemPanelToolbar, } from './SystemPanelUi'; import { usePolling, useStableTranslate } from './hooks/useSystemManager'; import { openInteractiveTerminal } from './openInteractiveTerminal'; import { showSystemManagerError } from './systemManagerToast'; type Backend = ReturnType; type ContainerFilter = 'all' | 'running' | 'stopped' | 'paused'; interface DockerContainersPanelProps { sessionId: string; parentSession: TerminalSession; isVisible: boolean; backend: Backend; listRefreshIntervalSec: number; statsRefreshIntervalSec: number; } const DockerContainerRow = memo(function DockerContainerRow({ container, selected, pendingAction, onSelectContainer, onShellContainer, onLogsContainer, onContainerAction, }: { container: DockerContainerInfo; selected: boolean; pendingAction: DockerContainerAction | null; onSelectContainer: (container: DockerContainerInfo) => void; onShellContainer: (container: DockerContainerInfo) => void; onLogsContainer: (container: DockerContainerInfo) => void; onContainerAction: (container: DockerContainerInfo, action: DockerContainerAction) => void; }) { const { t } = useI18n(); const shortId = container.id.slice(0, 12); const { isRunning, isPaused } = getContainerFlags(container); const actionBusy = pendingAction !== null; return ( onSelectContainer(container)} leading={} title={container.name || shortId} subtitle={container.image} trailing={(
{isRunning ? t('systemManager.docker.filter.running') : isPaused ? t('systemManager.docker.filter.paused') : t('systemManager.docker.filter.stopped')} {isRunning && ( onShellContainer(container)}> )} onLogsContainer(container)}> {isRunning && ( <> onContainerAction(container, 'restart')} > onContainerAction(container, 'stop')} > )} {isPaused && ( onContainerAction(container, 'unpause')} > )} {!isRunning && !isPaused && ( onContainerAction(container, 'start')} > )}
)} /> ); }); export const DockerContainersPanel = memo(function DockerContainersPanel({ sessionId, parentSession, isVisible, backend, listRefreshIntervalSec, statsRefreshIntervalSec, }: DockerContainersPanelProps) { const { t } = useI18n(); const stableT = useStableTranslate(); const [query, setQuery] = useState(''); const [filter, setFilter] = useState('all'); const [selectedId, setSelectedId] = useState(null); const [inspect, setInspect] = useState | null>(null); // Invalidates in-flight inspect fetches when the selection changes — // a slow response for container A must not render under container B. const inspectSeqRef = useRef(0); // Spinner feedback while a container action (stop/restart/…) runs; // cleared only after the follow-up list refresh lands. const [pendingAction, setPendingAction] = useState<{ id: string; action: DockerContainerAction } | null>(null); const containersFetcher = useCallback(async () => { const result = await backend.listDockerContainers(sessionId); if (!result.success || !result.containers) { throw new Error(result.error || stableT('systemManager.errors.loadDocker')); } return result.containers; }, [backend, sessionId, stableT]); const listIntervalMs = Math.max(3, listRefreshIntervalSec) * 1000; const { data: containers, error, loading, refresh } = usePolling( containersFetcher, listIntervalMs, isVisible, (prev, next) => mergePollListByKey(prev, next, (c) => c.id, dockerContainerInfoEqual), ); const matched = useMemo(() => { const q = query.trim().toLowerCase(); return (containers ?? []).filter((container) => { const { isRunning, isPaused } = getContainerFlags(container); if (filter === 'running' && !isRunning) return false; if (filter === 'stopped' && (isRunning || isPaused)) return false; if (filter === 'paused' && !isPaused) return false; if (!q) return true; const shortId = container.id.slice(0, 12); return container.name.toLowerCase().includes(q) || container.image.toLowerCase().includes(q) || shortId.toLowerCase().includes(q); }); }, [containers, filter, query]); const compareContainers = useCallback( (a: DockerContainerInfo, b: DockerContainerInfo) => a.name.localeCompare(b.name), [], ); const displayList = useStableListOrder( matched, (c) => c.id, `${filter}|${query}`, compareContainers, ); const selectedContainer = useMemo( () => displayList.find((c) => c.id === selectedId) ?? null, [displayList, selectedId], ); const runAction = useCallback(async ( containerId: string, action: DockerContainerAction, newName?: string, ) => { if (action === 'rm') { const ok = globalThis.confirm(t('systemManager.docker.confirmRemove')); if (!ok) return; } if (action === 'kill') { const ok = globalThis.confirm(t('systemManager.docker.confirmKill')); if (!ok) return; } setPendingAction({ id: containerId, action }); try { const result = await backend.dockerAction({ sessionId, containerId, action, newName }); if (!result.success) { showSystemManagerError(result.error || t('systemManager.errors.actionFailed'), t('common.error')); return; } if (action === 'rm') { setSelectedId(null); setInspect(null); inspectSeqRef.current += 1; } await refresh(); } finally { setPendingAction(null); } }, [backend, refresh, sessionId, t]); const handleRowAction = useCallback((container: DockerContainerInfo, action: DockerContainerAction) => { void runAction(container.id.slice(0, 12), action); }, [runAction]); const selectContainer = useCallback(async (container: DockerContainerInfo) => { const next = selectedId === container.id ? null : container.id; setSelectedId(next); setInspect(null); const seq = ++inspectSeqRef.current; if (!next) return; const result = await backend.dockerInspect({ sessionId, containerId: container.id.slice(0, 12), }); if (inspectSeqRef.current !== seq) return; setInspect(result.success ? (result.inspect ?? null) : null); }, [backend, selectedId, sessionId]); const openShell = useCallback(async (container: DockerContainerInfo) => { const id = container.id.slice(0, 12); const result = await openInteractiveTerminal( backend, parentSession, `docker: ${container.name || id}`, buildDockerExecShellCommand(id), ); if (!result.success) { showSystemManagerError(result.error || t('systemManager.errors.actionFailed'), t('common.error')); } }, [backend, parentSession, t]); const openLogs = useCallback(async (container: DockerContainerInfo) => { const id = container.id.slice(0, 12); const result = await openInteractiveTerminal( backend, parentSession, `logs: ${container.name || id}`, buildDockerLogsCommand(id), ); if (!result.success) { showSystemManagerError(result.error || t('systemManager.errors.actionFailed'), t('common.error')); } }, [backend, parentSession, t]); return (
void refresh()} /> )} > {t('systemManager.docker.meta', { count: String(displayList.length) })} {error && ( void refresh()} retryLabel={t('history.action.retry')} /> )} {!error && displayList.length === 0 && !loading && ( )} {displayList.map((container) => { const selected = selectedId === container.id; const rowPending = pendingAction && pendingAction.id === container.id.slice(0, 12) ? pendingAction.action : null; return ( {selectedContainer && ( { setSelectedId(null); setInspect(null); }} onRunAction={runAction} /> )} ); })}
); });