Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(operations): add shell state provider

Juan Denis5a29dd5a6dc4
diff --git a/frontend/src/contexts/OperationsContext.jsx b/frontend/src/contexts/OperationsContext.jsx
new file mode 100644
index 00000000..becd86a5
--- /dev/null
+++ b/frontend/src/contexts/OperationsContext.jsx
@@ -0,0 +1,181 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+
+import { usePolling } from '../hooks/usePolling';
+import useRunStream from '../hooks/useRunStream';
+import { SOCKET_EVENTS } from '../constants/events';
+import api from '../services/api';
+import {
+ boundOperationHistory,
+ isActiveOperation,
+ normalizeOperations,
+ operationKey,
+ operationNeedsAttention,
+ reconcileOperationStatus,
+} from '../services/operations';
+import socketService from '../services/socket';
+import { useAuth } from './AuthContext';
+
+const OperationsContext = createContext(null);
+const REFRESH_MS = 6000;
+const HISTORY_LIMIT = 25;
+
+export function OperationsProvider({ children }) {
+ const { user } = useAuth();
+ const canReadJobs = user?.role === 'admin';
+ const [operations, setOperations] = useState([]);
+ const [selectedKey, setSelectedKey] = useState(null);
+ const [collapsed, setCollapsed] = useState(true);
+ const [unreadKeys, setUnreadKeys] = useState(() => new Set());
+ const [loading, setLoading] = useState(true);
+ const selectedKeyRef = useRef(selectedKey);
+ const operationsRef = useRef(operations);
+ selectedKeyRef.current = selectedKey;
+ operationsRef.current = operations;
+
+ const refresh = useCallback(async () => {
+ const [deploymentsResult, jobsResult] = await Promise.allSettled([
+ api.getDeploymentJobs({ limit: 30 }),
+ canReadJobs ? api.getJobs({ limit: 50 }) : Promise.resolve({ jobs: [] }),
+ ]);
+ if (deploymentsResult.status === 'rejected' && jobsResult.status === 'rejected') {
+ setLoading(false);
+ return;
+ }
+ const deployments = deploymentsResult.status === 'fulfilled'
+ ? deploymentsResult.value?.jobs || []
+ : [];
+ const jobs = jobsResult.status === 'fulfilled' ? jobsResult.value?.jobs || [] : [];
+ const normalized = normalizeOperations({ deployments, jobs });
+ const bounded = boundOperationHistory(normalized, HISTORY_LIMIT, selectedKeyRef.current);
+ operationsRef.current = bounded;
+ setOperations(bounded);
+ setLoading(false);
+ }, [canReadJobs]);
+
+ usePolling(refresh, REFRESH_MS);
+
+ useEffect(() => {
+ socketService.connect();
+ const offStatus = socketService.on(SOCKET_EVENTS.RUN_STATUS, (payload) => {
+ const reconciled = reconcileOperationStatus(operationsRef.current, payload);
+ if (!reconciled.matched) {
+ refresh();
+ return;
+ }
+ operationsRef.current = reconciled.operations;
+ setOperations(reconciled.operations);
+ if (reconciled.attentionKey) {
+ setUnreadKeys((keys) => new Set(keys).add(reconciled.attentionKey));
+ }
+ });
+ const offConnect = socketService.on(SOCKET_EVENTS.CONNECTED, refresh);
+ return () => {
+ offStatus();
+ offConnect();
+ };
+ }, [refresh]);
+
+ useEffect(() => {
+ operationsRef.current = [];
+ setOperations([]);
+ setUnreadKeys(new Set());
+ setSelectedKey(null);
+ setCollapsed(true);
+ setLoading(true);
+ }, [user?.id]);
+
+ const activeOperations = useMemo(
+ () => operations.filter(isActiveOperation),
+ [operations],
+ );
+ const history = useMemo(
+ () => operations.filter((operation) => !isActiveOperation(operation)),
+ [operations],
+ );
+ const attentionOperations = useMemo(
+ () => operations.filter(operationNeedsAttention),
+ [operations],
+ );
+ const selectedOperation = useMemo(
+ () => operations.find((operation) => operationKey(operation) === selectedKey) || null,
+ [operations, selectedKey],
+ );
+ const selectedRunKind = selectedOperation?.runKind;
+ const selectedRunId = selectedOperation?.id;
+ const selectedStream = useRunStream(selectedRunKind, selectedRunId, {
+ enabled: !collapsed && !!selectedRunKind && selectedRunId != null,
+ });
+
+ const markRead = useCallback((key) => {
+ setUnreadKeys((current) => {
+ if (!current.has(key)) return current;
+ const next = new Set(current);
+ next.delete(key);
+ return next;
+ });
+ }, []);
+
+ const openOperation = useCallback((operation) => {
+ const key = typeof operation === 'string' ? operation : operationKey(operation);
+ setSelectedKey(key);
+ setCollapsed(false);
+ markRead(key);
+ }, [markRead]);
+
+ const value = useMemo(() => ({
+ operations,
+ activeOperations,
+ history,
+ attentionOperations,
+ selectedOperation,
+ selectedLines: selectedStream.lines,
+ selectedTransport: selectedStream.transport,
+ selectedStreamError: selectedStream.error,
+ refreshSelected: selectedStream.refetch,
+ selectedKey,
+ collapsed,
+ unreadKeys,
+ unreadCount: unreadKeys.size,
+ loading,
+ refresh,
+ openOperation,
+ selectOperation: setSelectedKey,
+ setCollapsed,
+ markRead,
+ }), [
+ operations,
+ activeOperations,
+ history,
+ attentionOperations,
+ selectedOperation,
+ selectedStream.lines,
+ selectedStream.transport,
+ selectedStream.error,
+ selectedStream.refetch,
+ selectedKey,
+ collapsed,
+ unreadKeys,
+ loading,
+ refresh,
+ openOperation,
+ markRead,
+ ]);
+
+ return <OperationsContext.Provider value={value}>{children}</OperationsContext.Provider>;
+}
+
+// Context modules intentionally export their hook beside the provider.
+// eslint-disable-next-line react-refresh/only-export-components
+export function useOperations() {
+ const context = useContext(OperationsContext);
+ if (!context) throw new Error('useOperations must be used within OperationsProvider');
+ return context;
+}
diff --git a/frontend/src/layouts/DashboardLayout.jsx b/frontend/src/layouts/DashboardLayout.jsx
index 2e331779..b7784b26 100644
--- a/frontend/src/layouts/DashboardLayout.jsx
+++ b/frontend/src/layouts/DashboardLayout.jsx
@@ -19,6 +19,7 @@ import DeployPill from '../components/DeployPill';
import ErrorBoundary from '../components/ErrorBoundary';
import { useShortcut } from '../hooks/useShortcut';
import { useTranslation } from 'react-i18next';
+import { OperationsProvider } from '../contexts/OperationsContext';
// The Automations extension (tramo) contributes /automations/edit/:slug with
// layout:'full', so it's picked up dynamically via fullPagePaths below.
@@ -98,6 +99,7 @@ const DashboardLayout = () => {
}, []);
return (
+ <OperationsProvider>
<LogsDrawerProvider>
<AIProvider>
<ConfirmProvider>
@@ -131,6 +133,7 @@ const DashboardLayout = () => {
</ConfirmProvider>
</AIProvider>
</LogsDrawerProvider>
+ </OperationsProvider>
);
};
diff --git a/frontend/src/services/__tests__/operations.test.mjs b/frontend/src/services/__tests__/operations.test.mjs
new file mode 100644
index 00000000..5d957514
--- /dev/null
+++ b/frontend/src/services/__tests__/operations.test.mjs
@@ -0,0 +1,89 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import {
+ boundOperationHistory,
+ normalizeDeploymentOperation,
+ normalizeJobOperation,
+ normalizeOperations,
+ operationKey,
+ reconcileOperationStatus,
+} from '../operations.js';
+
+test('normalizes deployment progress, resource, and detail route', () => {
+ const operation = normalizeDeploymentOperation({
+ id: 'dep-1',
+ kind: 'app_deploy',
+ status: 'running',
+ app_id: 8,
+ app_name: 'api-production',
+ current_step: 2,
+ total_steps: 5,
+ started_at: '2026-08-19T14:22:00Z',
+ });
+
+ assert.equal(operationKey(operation), 'deploy:dep-1');
+ assert.equal(operation.title, 'Deploy api-production');
+ assert.deepEqual(operation.progress, { completed: 2, total: 5, percent: 40 });
+ assert.equal(operation.resource.type, 'app');
+ assert.equal(operation.detailPath, '/deployments/dep-1');
+});
+
+test('normalizes proof job kinds and keeps deploy queue mirrors out', () => {
+ const backup = normalizeJobOperation({
+ id: 'job-1',
+ kind: 'backup.policy.run',
+ status: 'pending',
+ owner_type: 'backup_policy',
+ owner_id: 12,
+ });
+ assert.equal(backup.title, 'Backup policy run');
+ assert.equal(backup.detailPath, '/monitoring/jobs?focus=job-1');
+
+ const operations = normalizeOperations({
+ deployments: [{ id: 'dep-1', status: 'running' }],
+ jobs: [{ id: 'mirror', kind: 'deploy.app', status: 'running' }, { id: 'job-1', kind: 'doctor.run' }],
+ });
+ assert.deepEqual(operations.map(operationKey).sort(), ['deploy:dep-1', 'job:job-1']);
+});
+
+test('bounds terminal history without dropping active or selected work', () => {
+ const operations = [
+ normalizeJobOperation({ id: 'active', status: 'running', updated_at: '2026-08-21T03:00:00Z' }),
+ normalizeJobOperation({ id: 'recent', status: 'succeeded', updated_at: '2026-08-21T02:00:00Z' }),
+ normalizeJobOperation({ id: 'selected', status: 'succeeded', updated_at: '2026-08-21T01:00:00Z' }),
+ ];
+ const bounded = boundOperationHistory(operations, 1, 'job:selected');
+ assert.deepEqual(bounded.map(operationKey), ['job:active', 'job:recent', 'job:selected']);
+});
+
+test('reconciles one run and marks a newly failed terminal operation unread', () => {
+ const current = [normalizeJobOperation({ id: 'job-1', kind: 'doctor.run', status: 'running' })];
+ const result = reconcileOperationStatus(current, {
+ run_kind: 'job',
+ run_id: 'job-1',
+ status: { status: 'failed', error_message: 'repair failed' },
+ });
+ assert.equal(result.matched, true);
+ assert.equal(result.attentionKey, 'job:job-1');
+ assert.equal(result.operations[0].status, 'failed');
+ assert.equal(result.operations[0].error, 'repair failed');
+});
+
+test('preserves operation identity while accepting and clearing server capabilities', () => {
+ const current = [normalizeJobOperation({
+ id: 'job-2',
+ kind: 'security.lynis_scan',
+ status: 'running',
+ can_retry: true,
+ })];
+ const result = reconcileOperationStatus(current, {
+ run_kind: 'job',
+ run_id: 'job-2',
+ status: { status: 'running', requires_action: true, can_retry: false },
+ });
+ assert.equal(result.attentionKey, 'job:job-2');
+ assert.equal(result.operations[0].title, 'Security scan');
+ assert.equal(result.operations[0].canRetry, false);
+ assert.equal(result.operations[0].requiresAction, true);
+});
diff --git a/frontend/src/services/operations.js b/frontend/src/services/operations.js
new file mode 100644
index 00000000..51ec6fc4
--- /dev/null
+++ b/frontend/src/services/operations.js
@@ -0,0 +1,175 @@
+import { isTerminalRunStatus } from '../hooks/runStream.js';
+
+const ACTIVE_STATUSES = new Set(['pending', 'running']);
+const SECURITY_KIND = /^security[.]/;
+
+const stringId = (value) => (value == null ? null : String(value));
+const permissionFlag = (source, snakeKey, camelKey) => (
+ source?.[snakeKey] == null ? source?.[camelKey] === true : source[snakeKey] === true
+);
+
+export function operationKey(operation) {
+ return operation ? `${operation.runKind}:${operation.id}` : null;
+}
+
+export function isActiveOperation(operation) {
+ return ACTIVE_STATUSES.has(operation?.status);
+}
+
+export function operationNeedsAttention(operation) {
+ return operation?.status === 'failed'
+ || operation?.requiresAction === true
+ || operation?.needsAttention === true;
+}
+
+function normalizeProgress(source) {
+ const candidate = source?.progress;
+ const total = Number(candidate?.total ?? source?.total_steps ?? 0);
+ const completed = Number(candidate?.completed ?? source?.current_step ?? 0);
+ const explicitPercent = Number(candidate?.percent ?? source?.progress_percent);
+ const percent = Number.isFinite(explicitPercent)
+ ? explicitPercent
+ : (total > 0 ? Math.round((completed / total) * 100) : 0);
+ return {
+ completed: Number.isFinite(completed) ? completed : 0,
+ total: Number.isFinite(total) ? total : 0,
+ percent: Math.max(0, Math.min(100, Number.isFinite(percent) ? percent : 0)),
+ };
+}
+
+function jobTitle(job) {
+ if (job.kind === 'backup.policy.run') return 'Backup policy run';
+ if (job.kind === 'doctor.run' || job.kind === 'doctor.fleet.run') return 'Server doctor';
+ if (SECURITY_KIND.test(job.kind || '')) return 'Security scan';
+ return (job.kind || 'Background job').replaceAll('.', ' ');
+}
+
+function jobResource(job) {
+ if (job.resource) return job.resource;
+ if (!job.owner_type || job.owner_id == null) return null;
+ return {
+ type: job.owner_type,
+ id: stringId(job.owner_id),
+ label: `${String(job.owner_type).replaceAll('_', ' ')} ${job.owner_id}`,
+ status: null,
+ capabilities: [],
+ scope: {},
+ };
+}
+
+function deploymentResource(job) {
+ if (job.resource) return job.resource;
+ if (job.app_id != null) {
+ return {
+ type: 'app',
+ id: stringId(job.app_id),
+ label: job.app_name || `App ${job.app_id}`,
+ status: null,
+ capabilities: [],
+ scope: {},
+ };
+ }
+ if (job.target_server_id != null) {
+ return {
+ type: 'server',
+ id: stringId(job.target_server_id),
+ label: job.target_server_name || `Server ${job.target_server_id}`,
+ status: null,
+ capabilities: [],
+ scope: {},
+ };
+ }
+ return null;
+}
+
+export function normalizeDeploymentOperation(job) {
+ if (!job?.id) return null;
+ const target = job.app_name || job.target_server_name;
+ return {
+ id: stringId(job.id),
+ runKind: 'deploy',
+ kind: job.kind || 'deploy',
+ status: job.status || 'pending',
+ title: job.title || (target ? `Deploy ${target}` : 'Application deployment'),
+ resource: deploymentResource(job),
+ progress: normalizeProgress(job),
+ startedAt: job.started_at || job.startedAt || job.created_at || null,
+ finishedAt: job.completed_at || job.finishedAt || null,
+ updatedAt: job.updated_at || job.updatedAt || job.completed_at || job.started_at || job.created_at || null,
+ error: job.error_message || job.error || null,
+ canCancel: permissionFlag(job, 'can_cancel', 'canCancel'),
+ canRetry: permissionFlag(job, 'can_retry', 'canRetry'),
+ requiresAction: permissionFlag(job, 'requires_action', 'requiresAction') || job.handoff === true,
+ needsAttention: permissionFlag(job, 'needs_attention', 'needsAttention'),
+ detailPath: job.detailPath || `/deployments/${encodeURIComponent(String(job.id))}`,
+ };
+}
+
+export function normalizeJobOperation(job) {
+ if (!job?.id) return null;
+ return {
+ id: stringId(job.id),
+ runKind: 'job',
+ kind: job.kind || 'job',
+ status: job.status || 'pending',
+ title: job.title || jobTitle(job),
+ resource: jobResource(job),
+ progress: normalizeProgress(job.result || job),
+ startedAt: job.started_at || job.startedAt || job.created_at || null,
+ finishedAt: job.completed_at || job.finishedAt || null,
+ updatedAt: job.updated_at || job.updatedAt || job.completed_at || job.started_at || job.created_at || null,
+ error: job.error_message || job.error || null,
+ canCancel: permissionFlag(job, 'can_cancel', 'canCancel'),
+ canRetry: permissionFlag(job, 'can_retry', 'canRetry'),
+ requiresAction: permissionFlag(job, 'requires_action', 'requiresAction') || job.handoff === true,
+ needsAttention: permissionFlag(job, 'needs_attention', 'needsAttention'),
+ detailPath: job.detailPath || `/monitoring/jobs?focus=${encodeURIComponent(String(job.id))}`,
+ };
+}
+
+export function normalizeOperations({ deployments = [], jobs = [] } = {}) {
+ const normalized = [
+ ...deployments.map(normalizeDeploymentOperation),
+ ...jobs
+ .filter((job) => !String(job?.kind || '').startsWith('deploy.'))
+ .map(normalizeJobOperation),
+ ].filter(Boolean);
+
+ return normalized.sort((left, right) => (
+ new Date(right.updatedAt || 0).getTime() - new Date(left.updatedAt || 0).getTime()
+ ));
+}
+
+export function boundOperationHistory(operations, historyLimit = 25, retainedKey = null) {
+ const active = operations.filter(isActiveOperation);
+ const history = operations.filter((operation) => !isActiveOperation(operation)).slice(0, historyLimit);
+ const retained = retainedKey
+ ? operations.find((operation) => operationKey(operation) === retainedKey)
+ : null;
+ const combined = [...active, ...history, ...(retained ? [retained] : [])];
+ return [...new Map(combined.map((operation) => [operationKey(operation), operation])).values()];
+}
+
+export function reconcileOperationStatus(operations, payload) {
+ const runKind = payload?.run_kind;
+ const runId = payload?.run_id;
+ const status = payload?.status;
+ if (!runKind || runId == null || !status) return { operations, attentionKey: null, matched: false };
+
+ let attentionKey = null;
+ let matched = false;
+ const next = operations.map((operation) => {
+ if (operation.runKind !== runKind || String(operation.id) !== String(runId)) return operation;
+ matched = true;
+ const merged = runKind === 'deploy'
+ ? { ...operation, ...normalizeDeploymentOperation({ ...operation, ...status, id: runId }) }
+ : { ...operation, ...normalizeJobOperation({ ...operation, ...status, id: runId }) };
+ const becameFailure = operation.status !== 'failed' && merged.status === 'failed';
+ const becameHandoff = !operationNeedsAttention(operation) && operationNeedsAttention(merged);
+ if ((becameFailure && isTerminalRunStatus(merged.status)) || becameHandoff) {
+ attentionKey = operationKey(merged);
+ }
+ return merged;
+ });
+ return { operations: next, attentionKey, matched };
+}