import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import {
Activity,
AlertTriangle,
ArrowUpRight,
Clock3,
KeyRound,
ListRestart,
RotateCcw,
Square,
SquareTerminal,
X,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useOperations } from '../contexts/OperationsContext';
import { useShellDock } from '../contexts/ShellDockContext';
import { useToast } from '../contexts/ToastContext';
import { useConfirm } from '../hooks/useConfirm';
import { usePolling } from '../hooks/usePolling';
import { useShortcut } from '../hooks/useShortcut';
import api from '../services/api';
import { operationKey } from '../services/operations';
import { formatDuration } from '../utils/time';
import IconButton from './IconButton';
import FormField from './FormField';
import ShellDockTabs from './ShellDockTabs';
import Pill from './ds/Pill';
import { statusKind, statusLabel } from './ds/status';
const VIEWS = ['active', 'attention', 'history'];
function resourcePath(resource) {
if (!resource) return null;
if (resource.type === 'app' || resource.type === 'application') return `/services/${resource.id}`;
if (resource.type === 'server') return `/servers/${resource.id}`;
if (resource.type === 'backup_policy') return `/backups?focus=policy:${resource.id}`;
return null;
}
function lineText(line) {
if (typeof line === 'string') return line;
return line?.message || line?.line || JSON.stringify(line);
}
function OperationProgress({ operation, t }) {
const progress = operation.progress || {};
const total = Math.max(0, Number(progress.total) || 0);
const completed = Math.max(0, Number(progress.completed) || 0);
const percent = Math.max(0, Math.min(100, Number(progress.percent) || 0));
const railSize = Math.min(total, 8);
if (!total && !percent) return null;
return (
{operation.currentStepName || t('app.operationsDock.progress', 'Progress')}
{total ? `${completed}/${total}` : `${percent}%`}
{railSize > 1 && (
{Array.from({ length: railSize }, (_, index) => (
))}
)}
);
}
function RecipeHandoffCard({ operation, onSubmitted, t }) {
const handoff = operation.handoff;
const input = handoff?.input || {};
const [value, setValue] = useState('');
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState(null);
const fieldId = `recipe-handoff-${operation.id}-${handoff?.step_id || 'input'}`;
useEffect(() => {
setValue('');
setError(null);
setSubmitting(false);
}, [operation.id, handoff?.step_id]);
if (!handoff || !operation.requiresAction) return null;
const submit = async (event) => {
event.preventDefault();
if (!value.trim() || submitting) return;
setSubmitting(true);
setError(null);
try {
await api.submitRecipeHandoff(operation.id, handoff.step_id, value);
setValue('');
await onSubmitted();
} catch (submitError) {
setError(submitError?.message || t(
'app.operationsDock.handoffFailed',
'Could not submit this handoff',
));
} finally {
setSubmitting(false);
}
};
const ttlMinutes = handoff.ttl_seconds
? Math.max(1, Math.ceil(handoff.ttl_seconds / 60))
: null;
return (
);
}
function ServiceLogDetail({ session, lines, error, onClear, onClose, logRef, t }) {
const source = session.logPath
|| (session.containerId != null ? `docker · ${String(session.containerId).slice(0, 12)}` : null)
|| session.appType;
return (
{t('app.operationsDock.serviceLogs', 'Service log session')}
{session.name}
{t('app.operationsDock.live', 'Live')}
{source}
{t('app.operationsDock.lineCount', '{{count}} lines', { count: lines.length })}
{error && (
)}
{lines.length === 0 ? (
{t('app.logsDrawer.waitingForLogs', 'Waiting for logs…')}
) : lines.slice(-250).map((line, index) => (
{line}
))}
);
}
export default function OperationsDock({ hideLauncher = false, statusbarMode = false }) {
const { t } = useTranslation();
const toast = useToast();
const { confirm } = useConfirm();
const {
activeOperations,
history,
attentionOperations,
selectedOperation,
selectedLines,
selectedTransport,
selectedStreamError,
logSession,
serviceLines,
serviceStreamError,
clearServiceLines,
closeLogSession,
unreadKeys,
unreadCount,
collapsed,
loading,
refresh,
openOperation,
setCollapsed,
} = useOperations();
const { activeTab, expanded } = useShellDock();
const [view, setView] = useState('active');
const [now, setNow] = useState(Date.now());
const logRef = useRef(null);
usePolling(() => setNow(Date.now()), 1000, { enabled: !collapsed, immediate: false });
const toggle = useCallback(() => {
if (!collapsed) {
setCollapsed(true);
return;
}
if (logSession) setCollapsed(false);
else if (!selectedOperation && activeOperations[0]) openOperation(activeOperations[0]);
else setCollapsed(false);
}, [collapsed, logSession, selectedOperation, activeOperations, openOperation, setCollapsed]);
useShortcut({
id: 'operations-dock-toggle',
label: t('app.operationsDock.shortcutLabel', 'Toggle Operations dock'),
group: 'shell',
keys: [{ key: 'o', ctrlOrMeta: true, shift: true }],
handler: toggle,
});
useShortcut({
id: 'operations-dock-close',
label: t('app.operationsDock.collapse', 'Collapse Operations dock'),
group: 'overlays',
keys: [{ key: 'Escape' }],
enabled: !collapsed,
priority: 50,
allowInInput: true,
handler: () => setCollapsed(true),
});
useEffect(() => {
if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;
}, [selectedLines, serviceLines]);
const rows = useMemo(() => {
if (view === 'attention') return attentionOperations;
if (view === 'history') return history;
return activeOperations;
}, [view, activeOperations, attentionOperations, history]);
const elapsed = useMemo(() => {
if (!selectedOperation?.startedAt) return null;
const start = new Date(selectedOperation.startedAt).getTime();
const finish = selectedOperation.finishedAt
? new Date(selectedOperation.finishedAt).getTime()
: now;
if (!Number.isFinite(start) || !Number.isFinite(finish)) return null;
return formatDuration(Math.max(0, (finish - start) / 1000));
}, [selectedOperation, now]);
const cancelSelected = async () => {
if (!selectedOperation?.canCancel) return;
const accepted = await confirm({
title: t('app.operationsDock.cancelTitle', 'Cancel operation?'),
message: t('app.operationsDock.cancelMessage', 'The current step may finish before cancellation takes effect.'),
confirmText: t('app.operationsDock.cancelOperation', 'Cancel operation'),
variant: 'danger',
});
if (!accepted) return;
try {
if (selectedOperation.runKind === 'job') await api.cancelJob(selectedOperation.id);
await refresh();
toast.success(t('app.operationsDock.cancelQueued', 'Cancellation requested'));
} catch (error) {
toast.error(error?.message || t('app.operationsDock.actionFailed', 'Operation action failed'));
}
};
const retrySelected = async () => {
if (!selectedOperation?.canRetry) return;
try {
if (selectedOperation.runKind === 'deploy') await api.retryDeploymentJob(selectedOperation.id);
else await api.retryJob(selectedOperation.id);
await refresh();
toast.success(t('app.operationsDock.retryQueued', 'Retry queued'));
} catch (error) {
toast.error(error?.message || t('app.operationsDock.actionFailed', 'Operation action failed'));
}
};
const activeLabel = t('app.operationsDock.activeCount', '{{count}} active', {
count: activeOperations.length,
});
// In statusbar mode the shell dock decides which console tab is visible;
// outside it the legacy collapsed/launcher behaviour is untouched.
const visible = statusbarMode ? activeTab === 'ops' : !collapsed;
if (statusbarMode && !visible) return null;
return (
{!visible ? (
hideLauncher ? null :
) : (
{statusbarMode ? (
}
label={t('common.actions.refresh', 'Refresh')}
onClick={refresh}
/>
)}
/>
) : (
<>
{t('app.operationsDock.title', 'Operations')}
{activeLabel}
}
label={t('common.actions.refresh', 'Refresh')}
onClick={refresh}
/>
}
label={t('app.operationsDock.collapse', 'Collapse Operations dock')}
onClick={() => setCollapsed(true)}
/>
>
)}
{VIEWS.map((item) => {
const count = item === 'active'
? activeOperations.length
: item === 'attention' ? attentionOperations.length : history.length;
const label = item === 'active'
? t('app.operationsDock.active', 'Active')
: item === 'attention'
? t('app.operationsDock.needsAttention', 'Needs attention')
: t('app.operationsDock.history', 'History');
return (
);
})}
{loading && rows.length === 0 ? (
{t('common.state.loading', 'Loading')}
) : rows.length === 0 ? (
{view === 'active'
? t('app.operationsDock.noActive', 'No operations are running')
: view === 'attention'
? t('app.operationsDock.noAttention', 'Nothing needs attention')
: t('app.operationsDock.noHistory', 'No recent operations')}
) : rows.map((operation) => {
const key = operationKey(operation);
const unread = unreadKeys.has(key);
return (
);
})}
{logSession ? (
) : selectedOperation ? (
{selectedOperation.kind}
{selectedOperation.title}
{statusLabel(selectedOperation.status)}
{elapsed && {elapsed}}
{selectedTransport === 'socket' ? t('app.operationsDock.live', 'Live') : t('app.operationsDock.polling', 'Polling')}
{
await refresh();
toast.success(t(
'app.operationsDock.recipeResumed',
'Recipe resumed',
));
}}
t={t}
/>
{(selectedOperation.error || selectedStreamError) && (
{selectedOperation.error || selectedStreamError}
)}
{selectedLines.length === 0 ? (
{t('app.operationsDock.waitingForLogs', 'Waiting for run logs…')}
) : selectedLines.slice(-250).map((line, index) => (
{lineText(line)}
))}
) : (
{t('app.operationsDock.selectOperation', 'Select an operation to inspect progress and logs')}
)}
)}
);
}