Skip to content

Modern Docker Management, Designed for Everyone

28.1 KB
Raw Blame
<script lang="ts">
	import { goto, refreshAll } from '$app/navigation';
	import { PersistedState } from 'runed';
	import { onDestroy, onMount, untrack } from 'svelte';
	import { toast } from 'svelte-sonner';

	import { type ActionButton } from '#lib/components/action-button-group/index.js';
	import { ArcaneButton } from '#lib/components/arcane-button/index.js';
	import * as ArcaneTooltip from '#lib/components/arcane-tooltip/index.js';
	import DockerInfoDialog, { type EngineInfo } from '#lib/components/dialogs/docker-info-dialog.svelte';
	import PruneConfirmationDialog from '#lib/components/dialogs/prune-confirmation-dialog.svelte';
	import * as StatStrip from '#lib/components/stat-strip/index.js';
	import {
		BoxIcon,
		ContainersIcon,
		EnvironmentsIcon,
		ImagesIcon,
		InfoIcon,
		InspectIcon,
		TrashIcon,
		UpdateIcon,
		VolumesIcon,
		LayoutGridIcon,
		LayoutListIcon
	} from '#lib/icons/index.js';
	import { m } from '#lib/paraglide/messages.js';
	import { podmanService } from '#lib/services/podman-service.js';
	import { settingsService } from '#lib/services/settings-service.js';
	import { systemService } from '#lib/services/system-service.js';
	import { activityStore } from '#lib/stores/activity.store.svelte.js';
	import { dashboardStore } from '#lib/stores/dashboard.store.svelte.js';
	import { environmentStore } from '#lib/stores/environment.store.svelte.js';
	import { featureStore } from '#lib/stores/features.store.svelte.js';
	import userStore from '#lib/stores/user-store.svelte.js';
	import type { Activity } from '#lib/types/activity.type.js';
	import type { PruneType, SystemPruneRequest } from '#lib/types/automation.js';
	import type { Environment } from '#lib/types/environment.js';
	import type { AppVersionInformation, Settings } from '#lib/types/settings.js';
	import type {
		DashboardActionItemKind,
		DashboardEnvironmentCardState,
		DashboardEnvironmentOverview,
		DashboardLiveStatsStatus,
		SystemStats
	} from '#lib/types/shared.js';
	import { cn } from '#lib/utils.js';
	import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
	import { extractApiErrorMessage, handleApiResultWithCallbacks } from '#lib/utils/api.js';
	import { hasAnyPermission, hasPermission } from '#lib/utils/auth.js';
	import { isEnvironmentOnline } from '#lib/utils/docker.js';
	import { tryCatch } from '#lib/utils/try-catch.js';
	import { createStatsWebSocket, type ReconnectingWebSocket } from '#lib/utils/ws.js';

	import {
		buildOverviewSummary,
		createBaseEnvironmentOverview,
		formatContainerOverviewLabel,
		formatImageOverviewLabel,
		formatVolumeOverviewLabel,
		getCpuMetric,
		getDiskMetric,
		getMemoryMetric,
		shouldLoadEnvironment
	} from '../overview.helpers';
	import EnvironmentCard from './environment-card.svelte';
	import EnvironmentsTable, { type EnvironmentTableRow } from './environments-table.svelte';

	let {
		heroGreeting,
		debugAllGood = false,
		debugUpgrade = false
	}: {
		heroGreeting: string;
		debugAllGood?: boolean;
		debugUpgrade?: boolean;
	} = $props();

	const DEBUG_VERSION_INFO: AppVersionInformation = {
		currentVersion: 'debug',
		displayVersion: 'debug',
		revision: 'debug',
		shortRevision: 'debug',
		goVersion: '',
		nodeVersion: '',
		svelteKitVersion: '',
		isSemverVersion: false,
		newestVersion: 'debug-v2',
		updateAvailable: true
	};

	type EnvironmentLiveStatsState = {
		stats: SystemStats | null;
		loading: boolean;
		failed: boolean;
		client: ReconnectingWebSocket<SystemStats> | null;
		deadline: ReturnType<typeof setTimeout> | null;
	};

	const LIVE_STATS_DEADLINE_MS = 10_000;

	let isRefreshing = $state(false);
	let isPruneDialogOpen = $state(false);
	let pruneEnvironment = $state<DashboardEnvironmentOverview | null>(null);
	let pruneDefaults = $state<Settings | null>(null);
	let pruneDefaultsLoadingId = $state<string | null>(null);
	let pruningEnvironmentId = $state<string | null>(null);
	let pendingPruneActivityId = $state<string | null>(null);
	let reloadVersion = $state(0);
	let liveStatsByEnvironmentId = $state<Record<string, EnvironmentLiveStatsState>>({});
	let upgradeDialogOpenById = $state<Record<string, boolean>>({});
	let upgradeDialogUpgradingById = $state<Record<string, boolean>>({});

	let engineInfoOpen = $state(false);
	let engineInfoEngine = $state<EngineInfo['engine']>('docker');
	let engineInfoData = $state<EngineInfo | null>(null);
	let engineInfoPromise = $state<Promise<EngineInfo> | null>(null);
	let engineInfoError = $state<string | null>(null);
	let engineInfoByEnvironmentId = $state<Record<string, EngineInfo | undefined>>({});
	let engineInfoPromiseByEnvironmentId = $state<Record<string, Promise<EngineInfo> | undefined>>({});

	const availableEnvironments = $derived.by(() => {
		if (!userStore.current) {
			return [];
		}

		return environmentStore.available.filter((environment) => hasPermission('dashboard:read', environment.id));
	});
	const currentEnvironmentId = $derived(environmentStore.selected?.id ?? null);

	function canPruneInEnvironment(envId: string): boolean {
		return hasAnyPermission(['images:prune', 'volumes:prune', 'networks:prune'], envId);
	}
	function canUpgradeEnvironment(): boolean {
		return hasPermission('environments:update');
	}

	function createEmptyLiveStatsState(): EnvironmentLiveStatsState {
		return {
			stats: null,
			loading: true,
			failed: false,
			client: null,
			deadline: null
		};
	}

	function canLoadLiveStats(environment: Environment): boolean {
		return shouldLoadEnvironment(environment) && hasPermission('system:read', environment.id);
	}

	function clearLiveStatsDeadline(liveStatsState: EnvironmentLiveStatsState) {
		if (liveStatsState.deadline) {
			clearTimeout(liveStatsState.deadline);
			liveStatsState.deadline = null;
		}
	}

	function markLiveStatsFailed(liveStatsState: EnvironmentLiveStatsState) {
		clearLiveStatsDeadline(liveStatsState);
		liveStatsState.loading = false;
		liveStatsState.failed = true;
	}

	function startLiveStatsAttempt(liveStatsState: EnvironmentLiveStatsState) {
		clearLiveStatsDeadline(liveStatsState);
		liveStatsState.loading = liveStatsState.stats === null;
		liveStatsState.failed = liveStatsState.stats !== null && liveStatsState.failed;
		liveStatsState.deadline = setTimeout(() => markLiveStatsFailed(liveStatsState), LIVE_STATS_DEADLINE_MS);
	}

	function ensureEnvironmentLiveStats(environment: Environment) {
		if (!canLoadLiveStats(environment)) {
			removeEnvironmentLiveStats(environment.id);
			return;
		}

		if (!liveStatsByEnvironmentId[environment.id]) {
			liveStatsByEnvironmentId[environment.id] = createEmptyLiveStatsState();
		}

		const liveStatsState = liveStatsByEnvironmentId[environment.id];
		if (!liveStatsState) {
			return;
		}

		if (liveStatsState.client) {
			return;
		}

		startLiveStatsAttempt(liveStatsState);
		liveStatsState.client = createStatsWebSocket({
			getEnvId: () => environment.id,
			onMessage: (stats) => {
				clearLiveStatsDeadline(liveStatsState);
				liveStatsState.stats = stats;
				liveStatsState.loading = false;
				liveStatsState.failed = false;
			},
			onError: (error) => {
				console.error(`Stats websocket error for environment ${environment.id}:`, error);
				markLiveStatsFailed(liveStatsState);
			},
			onClose: () => markLiveStatsFailed(liveStatsState)
		});
		liveStatsState.client.connect();
	}

	function retryFailedLiveStats() {
		for (const liveStatsState of Object.values(liveStatsByEnvironmentId)) {
			if (!liveStatsState.failed || !liveStatsState.client) {
				continue;
			}
			startLiveStatsAttempt(liveStatsState);
			void liveStatsState.client.connect();
		}
	}

	function removeEnvironmentLiveStats(environmentId: string) {
		const liveStatsState = liveStatsByEnvironmentId[environmentId];
		if (!liveStatsState) {
			return;
		}

		clearLiveStatsDeadline(liveStatsState);
		liveStatsState.client?.close();
		delete liveStatsByEnvironmentId[environmentId];
	}

	function cleanupEnvironmentLiveStats() {
		for (const environmentId of Object.keys(liveStatsByEnvironmentId)) {
			removeEnvironmentLiveStats(environmentId);
		}
	}

	async function fetchEngineInfo(environmentId: string, podCount: number | undefined): Promise<EngineInfo> {
		if (podCount === undefined) {
			return { engine: 'docker', docker: await systemService.getDockerInfoForEnvironment(environmentId) };
		}

		const [podman, status] = await Promise.all([podmanService.getInfo(environmentId), podmanService.getStatus(environmentId)]);
		return { engine: 'podman', podman, status, podCount };
	}

	async function loadEngineInfo(environmentId: string, podCount: number | undefined): Promise<EngineInfo> {
		try {
			const info = await fetchEngineInfo(environmentId, podCount);
			engineInfoByEnvironmentId[environmentId] = info;
			engineInfoData = info;
			return info;
		} finally {
			delete engineInfoPromiseByEnvironmentId[environmentId];
			engineInfoPromise = null;
		}
	}

	function openEngineInfo(item: DashboardEnvironmentOverview) {
		const environmentId = item.environment.id;
		const podCount = hasPermission('podman:read', environmentId) ? item.podCount : undefined;
		engineInfoError = null;
		engineInfoOpen = true;
		engineInfoEngine = podCount === undefined ? 'docker' : 'podman';
		engineInfoData = engineInfoByEnvironmentId[environmentId] ?? null;
		if (engineInfoData) {
			engineInfoPromise = null;
			return;
		}

		engineInfoPromise = engineInfoPromiseByEnvironmentId[environmentId] ?? null;
		if (engineInfoPromise) {
			return;
		}

		engineInfoPromise = tryCatch(loadEngineInfo(environmentId, podCount)).then((result) => {
			if (result.error) {
				const error: Error = result.error;

				engineInfoError = extractApiErrorMessage(error);
				throw error;
			}
			return result.data;
		});
		engineInfoPromiseByEnvironmentId[environmentId] = engineInfoPromise;
	}

	const environmentCards = $derived.by((): DashboardEnvironmentCardState[] => {
		return [...availableEnvironments]
			.sort((a, b) => {
				const currentOrder = Number(b.id === currentEnvironmentId) - Number(a.id === currentEnvironmentId);
				if (currentOrder !== 0) {
					return currentOrder;
				}

				return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }) || a.id.localeCompare(b.id);
			})
			.map((environment) => ({ environment }));
	});
	const loadableEnvironmentCards = $derived(environmentCards.filter(({ environment }) => shouldLoadEnvironment(environment)));
	const liveStatsEnvironmentIds = $derived.by(
		() =>
			new Set(
				loadableEnvironmentCards
					.filter(({ environment }) => canLoadLiveStats(environment))
					.map(({ environment }) => environment.id)
			)
	);

	function resolveSnapshotErrorMessage(state: NonNullable<ReturnType<typeof dashboardStore.getEnvironmentState>>): string {
		if (state.errorCode === 'agent_incompatible') {
			return m.dashboard_all_agent_incompatible();
		}
		return state.errorMessage || m.common_unknown();
	}

	const boardState = $derived.by(() => {
		void reloadVersion;

		const overviewById = new Map<string, DashboardEnvironmentOverview>();
		const items: DashboardEnvironmentOverview[] = [];

		for (const { environment } of environmentCards) {
			const state = dashboardStore.getEnvironmentState(environment.id);
			let item: DashboardEnvironmentOverview;

			if (state?.snapshot) {
				// Last-known data keeps rendering even while the environment is
				// erroring; the error banner is shown alongside it.
				const snapshot = state.snapshot;
				item = {
					environment,
					containers: snapshot.containers.counts ?? { runningContainers: 0, stoppedContainers: 0, totalContainers: 0 },
					imageUsageCounts: snapshot.imageUsageCounts,
					volumeUsageCounts: snapshot.volumeUsageCounts,
					actionItems: {
						...snapshot.actionItems,
						items: snapshot.actionItems.items.filter(
							(item) =>
								item.kind !== 'actionable_vulnerabilities' || featureStore.isEnabled('vulnerabilityManagement', environment.id)
						)
					},
					settings: snapshot.settings,
					versionInfo: snapshot.versionInfo,
					podCount: snapshot.podCount,
					snapshotState: 'ready',
					snapshotError: state.streamError ? resolveSnapshotErrorMessage(state) : undefined
				};
			} else if (state?.streamError) {
				item = {
					...createBaseEnvironmentOverview(environment),
					snapshotState: 'error',
					snapshotError: resolveSnapshotErrorMessage(state)
				};
			} else {
				item = createBaseEnvironmentOverview(environment);
			}

			overviewById.set(environment.id, item);
			items.push(item);
		}

		return {
			overviewById,
			summary: buildOverviewSummary(items)
		};
	});

	function isEnvironmentSnapshotLoading(environmentId: string): boolean {
		return dashboardStore.isSnapshotLoading(environmentId);
	}

	const boardSummaryLoading = $derived.by(() => {
		let hasReachable = false;
		for (const { environment } of environmentCards) {
			if (!shouldLoadEnvironment(environment)) {
				continue;
			}
			hasReachable = true;
			if (dashboardStore.getEnvironmentState(environment.id)?.hasLoaded) {
				return false;
			}
		}
		return hasReachable;
	});

	$effect(() => {
		const environmentsToLoad = loadableEnvironmentCards.map(({ environment }) => environment);

		untrack(() => {
			for (const environment of environmentsToLoad) {
				ensureEnvironmentLiveStats(environment);
				void featureStore.load(environment.id);
			}
		});
	});

	$effect(() => {
		const activeEnvironmentIds = liveStatsEnvironmentIds;

		untrack(() => {
			for (const environmentId of Object.keys(liveStatsByEnvironmentId)) {
				if (!activeEnvironmentIds.has(environmentId)) {
					removeEnvironmentLiveStats(environmentId);
				}
			}
		});
	});

	let refreshedPruneActivityId: string | null = null;
	function refreshCompletedPrune(activities: readonly Activity[] = activityStore.activities) {
		const id = pendingPruneActivityId;
		if (!id || id === refreshedPruneActivityId) return;
		const status = activities.find((activity) => activity.id === id)?.status;
		if (status !== 'success' && status !== 'failed' && status !== 'cancelled') return;
		refreshedPruneActivityId = id;
		void refreshOverview();
	}

	onMount(() => activityStore.subscribeActivities(refreshCompletedPrune));

	onMount(() => {
		void dashboardStore.start({ debugAllGood });
	});

	onDestroy(() => {
		cleanupEnvironmentLiveStats();
		dashboardStore.stop();
	});

	async function refreshOverview() {
		isRefreshing = true;
		try {
			retryFailedLiveStats();
			await refreshAll();
			await dashboardStore.refresh();
			reloadVersion += 1;
		} finally {
			isRefreshing = false;
		}
	}

	async function useEnvironment(environment: Environment) {
		if (!environment.enabled) {
			toast.error(m.environments_cannot_switch_disabled());
			return;
		}

		if (!isEnvironmentOnline(environment)) {
			toast.error(m.common_unavailable());
			return;
		}

		const operationResult = await tryCatch(
			(async () => {
				await environmentStore.setEnvironment(environment);
				toast.success(m.environments_switched_to({ name: environment.name }));
			})()
		);
		if (operationResult.error !== null) {
			const error = operationResult.error;

			console.error('Failed to switch environment:', error);
			toast.error(m.common_update_failed({ resource: m.resource_environment() }));
		}
	}

	function getLiveStatsState(environmentId: string): EnvironmentLiveStatsState | null {
		return liveStatsByEnvironmentId[environmentId] ?? null;
	}

	function getLiveStatsStatus(environment: Environment): DashboardLiveStatsStatus {
		if (!shouldLoadEnvironment(environment)) {
			return 'live';
		}
		if (!hasPermission('system:read', environment.id)) {
			return 'denied';
		}
		const liveStatsState = getLiveStatsState(environment.id);
		if (!liveStatsState) {
			return 'loading';
		}
		if (liveStatsState.failed) {
			return liveStatsState.stats ? 'stale' : 'unavailable';
		}
		return liveStatsState.loading ? 'loading' : 'live';
	}

	function canPruneEnvironment(item: DashboardEnvironmentOverview): boolean {
		return (
			canPruneInEnvironment(item.environment.id) &&
			item.environment.enabled &&
			item.snapshotState === 'ready' &&
			isEnvironmentOnline(item.environment)
		);
	}

	function getEnvironmentActionButtons(item: DashboardEnvironmentOverview, isCurrent: boolean): ActionButton[] {
		const buttons: ActionButton[] = [];

		buttons.push({
			id: `${item.environment.id}-use`,
			action: 'base',
			label: m.environments_use_environment(),
			disabled: !shouldLoadEnvironment(item.environment) || isCurrent,
			onclick: () => void useEnvironment(item.environment),
			icon: EnvironmentsIcon
		});

		buttons.push({
			id: `${item.environment.id}-details`,
			action: 'inspect',
			label: m.common_view_details(),
			onclick: () => void goto(`/environments/${item.environment.id}`),
			icon: InspectIcon
		});

		buttons.push({
			id: `${item.environment.id}-docker-info`,
			action: 'base',
			label: m.common_inspect(),
			disabled: !shouldLoadEnvironment(item.environment),
			onclick: () => openEngineInfo(item),
			icon: InfoIcon
		});

		if (canPruneInEnvironment(item.environment.id)) {
			buttons.push({
				id: `${item.environment.id}-prune`,
				action: 'prune',
				label: m.quick_actions_prune_system(),
				loading: pruningEnvironmentId === item.environment.id || pruneDefaultsLoadingId === item.environment.id,
				disabled: !canPruneEnvironment(item) || !!pruningEnvironmentId || !!pruneDefaultsLoadingId,
				onclick: () => void openPruneDialog(item),
				icon: TrashIcon
			});
		}

		return buttons;
	}

	// Board view mode: cards or table. 'auto' resolves to table once the board
	// grows past a handful of environments (tiles stop scaling — #2778).
	const boardViewPref = new PersistedState<'auto' | 'cards' | 'table'>('dashboard-environments-view', 'auto');
	const boardView = $derived.by((): 'cards' | 'table' => {
		if (boardViewPref.current !== 'auto') return boardViewPref.current;
		return environmentCards.length > 6 ? 'table' : 'cards';
	});

	const environmentTableRows = $derived.by((): EnvironmentTableRow[] => {
		return environmentCards.map(({ environment }) => {
			const baseItem = createBaseEnvironmentOverview(environment);
			const loadedItem = boardState.overviewById.get(environment.id) ?? baseItem;
			const stats = getLiveStatsState(environment.id)?.stats ?? null;
			const isCurrent = currentEnvironmentId === environment.id;
			const [useButton, ...menuButtons] = getEnvironmentActionButtons(loadedItem, isCurrent);
			const vInfo = loadedItem.versionInfo;
			const actionItemCount = (kind: DashboardActionItemKind) =>
				loadedItem.actionItems.items.find((item) => item.kind === kind)?.count ?? 0;
			return {
				environment,
				isCurrent,
				online: isEnvironmentOnline(environment),
				loading: isEnvironmentSnapshotLoading(environment.id),
				running: loadedItem.containers.runningContainers,
				total: loadedItem.containers.totalContainers,
				images: loadedItem.imageUsageCounts.totalImages,
				podCount: loadedItem.podCount ?? null,
				updates: actionItemCount('image_updates'),
				vulnerabilities: actionItemCount('actionable_vulnerabilities'),
				cpu: getCpuMetric(stats),
				memory: getMemoryMetric(stats),
				disk: getDiskMetric(stats),
				statsStatus: getLiveStatsStatus(environment),
				versionText: vInfo ? vInfo.displayVersion || vInfo.currentTag || vInfo.currentVersion || 'unknown' : null,
				updateAvailable: !!vInfo?.updateAvailable,
				useButton,
				menuButtons
			};
		});
	});

	// Updates hero: aggregate pending image updates across every environment,
	// mirroring the iOS Updates overview header.
	const updatesOverview = $derived.by(() => {
		let pending = 0;
		let checkedEnvironments = 0;

		for (const { environment } of environmentCards) {
			if (!shouldLoadEnvironment(environment)) {
				continue;
			}
			const state = dashboardStore.getEnvironmentState(environment.id);
			if (!state?.hasLoaded) {
				continue;
			}
			checkedEnvironments += 1;
			if (debugAllGood) {
				continue;
			}
			const updateItem = state.snapshot?.actionItems.items.find((item) => item.kind === 'image_updates');
			pending += updateItem?.count ?? 0;
		}

		const checking = checkedEnvironments < loadableEnvironmentCards.length;
		return { pending, checking };
	});

	const summaryTiles = $derived.by(() => {
		const summary = boardState.summary;
		let updatesContext: string;
		if (updatesOverview.pending === 0 && !updatesOverview.checking) {
			updatesContext = m.dashboard_updates_up_to_date();
		} else if (updatesOverview.checking) {
			updatesContext = m.dashboard_updates_checking();
		} else {
			updatesContext = m.dashboard_updates_available_label();
		}

		return [
			{
				key: 'updates',
				href: '/updates',
				icon: UpdateIcon,
				label: m.updates(),
				value: updatesOverview.pending,
				context: updatesContext
			},
			{
				key: 'containers',
				href: '/containers',
				icon: ContainersIcon,
				label: m.containers(),
				value: summary.totalContainers,
				context: formatContainerOverviewLabel(summary)
			},
			{
				key: 'images',
				href: '/images',
				icon: ImagesIcon,
				label: m.images(),
				value: summary.totalImages,
				context: formatImageOverviewLabel(summary)
			},
			{
				key: 'volumes',
				href: '/volumes',
				icon: VolumesIcon,
				label: m.resource_volumes_cap(),
				value: summary.totalVolumes,
				context: formatVolumeOverviewLabel(summary)
			},
			...(summary.podmanEnvironments > 0
				? [
						{
							key: 'pods',
							href: '/podman/pods',
							icon: BoxIcon,
							label: m.podman_pods_title(),
							value: summary.totalPods,
							context: m.dashboard_all_podman_environments({ count: summary.podmanEnvironments })
						}
					]
				: [])
		];
	});

	async function openPruneDialog(item: DashboardEnvironmentOverview) {
		if (!canPruneEnvironment(item) || pruneDefaultsLoadingId) {
			return;
		}

		const environmentId = item.environment.id;
		pruneEnvironment = item;
		pruneDefaultsLoadingId = environmentId;
		try {
			const operationResult = await tryCatch((async () => settingsService.getSettingsForEnvironment(environmentId))());
			if (operationResult.error !== null) {
				// Fall back to the dialog's built-in defaults if settings can't be loaded.
				pruneDefaults = null;
			} else {
				pruneDefaults = operationResult.data;
			}
		} finally {
			pruneDefaultsLoadingId = null;
		}

		// Guard against the selection changing while the fetch was in flight.
		if (pruneEnvironment?.environment.id === environmentId) {
			isPruneDialogOpen = true;
		}
	}

	function closePruneDialog() {
		if (pruningEnvironmentId) {
			return;
		}

		isPruneDialogOpen = false;
		pruneEnvironment = null;
		pruneDefaults = null;
	}

	async function confirmPrune(pruneRequest: SystemPruneRequest) {
		const selectedTypes = Object.keys(pruneRequest) as PruneType[];
		if (!pruneEnvironment || pruningEnvironmentId || selectedTypes.length === 0) {
			return;
		}

		const targetEnvironment = pruneEnvironment;
		const environmentId = targetEnvironment.environment.id;

		const typeLabels: Record<PruneType, string> = {
			containers: m.prune_stopped_containers(),
			images: m.prune_unused_images(),
			networks: m.unused_networks(),
			volumes: m.unused_volumes(),
			buildCache: m.build_cache()
		};
		const typesString = selectedTypes.map((type) => typeLabels[type]).join(', ');

		pruningEnvironmentId = environmentId;

		await handleApiResultWithCallbacks({
			result: await tryCatch(systemService.pruneAllForEnvironment(environmentId, pruneRequest)),
			message: m.dashboard_prune_failed({ types: typesString }),
			setLoadingState: (value) => {
				pruningEnvironmentId = value ? environmentId : null;
			},
			onSuccess: async (data) => {
				isPruneDialogOpen = false;
				pruneEnvironment = null;
				pruneDefaults = null;
				const activityId = extractActivityId(data);
				const toastOptions = {
					...(activityToastOptions(activityId) ?? {}),
					description: targetEnvironment.environment.name
				};
				if (selectedTypes.length === 1) {
					toast.success(m.dashboard_prune_success_one({ types: typesString }), toastOptions);
				} else {
					toast.success(m.dashboard_prune_success_many({ types: typesString }), toastOptions);
				}
				// The prune runs as a background activity, so refresh once it actually
				// completes — refreshing now would capture pre-prune state. Fall back to
				// an immediate refresh when no activity id is returned.
				if (activityId) {
					pendingPruneActivityId = activityId;
					refreshCompletedPrune();
				} else {
					await refreshOverview();
				}
			}
		});
	}
</script>

<div class="flex h-full min-h-0 flex-col gap-4 overflow-hidden pt-3 md:gap-5 md:pt-5">
	<header class="flex shrink-0 items-start justify-between gap-4">
		<div class="min-w-0 space-y-1">
			<p class="text-2xs font-semibold tracking-widest text-muted-foreground uppercase">{m.dashboard_title()}</p>
			<h1 class="text-xl font-semibold tracking-tight sm:text-2xl">{heroGreeting}</h1>
		</div>

		<div class="flex shrink-0 items-center gap-2">
			<div class="inline-flex items-center gap-0.5 rounded-lg border border-border/60 bg-muted/40 p-0.5">
				{#each [{ view: 'cards' as const, icon: LayoutGridIcon, label: m.dashboard_view_cards() }, { view: 'table' as const, icon: LayoutListIcon, label: m.dashboard_view_table() }] as option (option.view)}
					<button
						type="button"
						title={option.label}
						aria-label={option.label}
						aria-pressed={boardView === option.view}
						class={cn(
							'inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none',
							boardView === option.view && 'bg-primary/15 text-primary ring-1 ring-primary/30 dark:text-primary-tint'
						)}
						onclick={() => (boardViewPref.current = option.view)}
					>
						<option.icon class="size-4" />
					</button>
				{/each}
			</div>

			<ArcaneTooltip.Root>
				<ArcaneTooltip.Trigger>
					{#snippet child({ props })}
						<ArcaneButton
							{...props}
							action="refresh"
							size="icon"
							class="size-8"
							customLabel={m.common_refresh()}
							loading={isRefreshing}
							onclick={refreshOverview}
						/>
					{/snippet}
				</ArcaneTooltip.Trigger>
				<ArcaneTooltip.Content>{m.common_refresh()}</ArcaneTooltip.Content>
			</ArcaneTooltip.Root>
		</div>
	</header>

	<section class="shrink-0">
		<StatStrip.Root class={summaryTiles.length > 4 ? 'lg:grid-cols-5' : 'lg:grid-cols-4'}>
			{#each summaryTiles as tile (tile.key)}
				<StatStrip.Item label={tile.label} value={tile.value} icon={tile.icon} href={tile.href} loading={boardSummaryLoading}>
					{tile.context}
				</StatStrip.Item>
			{/each}
		</StatStrip.Root>
	</section>

	<section class="flex min-h-0 flex-1 flex-col overflow-hidden pt-3">
		{#if environmentCards.length === 0}
			<div class="rounded-xl border border-dashed border-border/60 px-4 py-8 text-center">
				<p class="text-sm text-muted-foreground">{m.dashboard_all_no_visible_environments()}</p>
			</div>
		{:else if boardView === 'table'}
			<div class="min-h-0 flex-1 overflow-y-auto pb-2">
				<EnvironmentsTable rows={environmentTableRows} />
			</div>
		{:else}
			<div class="min-h-0 flex-1 overflow-y-auto pb-2">
				<div class="grid grid-cols-1 gap-4 xl:grid-cols-2">
					{#each environmentCards as item (item.environment.id)}
						{@const baseItem = createBaseEnvironmentOverview(item.environment)}
						{@const environment = baseItem.environment}
						{@const overview = boardState.overviewById.get(environment.id) ?? baseItem}
						{@const isCurrent = currentEnvironmentId === environment.id}
						{@const systemStats = getLiveStatsState(environment.id)?.stats ?? null}
						{@const liveStatsStatus = getLiveStatsStatus(environment)}
						{@const [useButton, ...menuButtons] = getEnvironmentActionButtons(overview, isCurrent)}
						<EnvironmentCard
							{overview}
							{isCurrent}
							{systemStats}
							{liveStatsStatus}
							snapshotLoading={isEnvironmentSnapshotLoading(environment.id)}
							{useButton}
							{menuButtons}
							{debugUpgrade}
							debugVersionInfo={DEBUG_VERSION_INFO}
							canUpgrade={canUpgradeEnvironment()}
							onRefreshRequested={refreshOverview}
							bind:upgradeOpen={upgradeDialogOpenById[environment.id]}
							bind:upgradeLoading={upgradeDialogUpgradingById[environment.id]}
						/>
					{/each}
				</div>
			</div>
		{/if}
	</section>
</div>

<PruneConfirmationDialog
	open={isPruneDialogOpen}
	isPruning={!!pruningEnvironmentId}
	defaults={pruneDefaults}
	onConfirm={confirmPrune}
	onCancel={closePruneDialog}
/>

<DockerInfoDialog
	bind:open={engineInfoOpen}
	engine={engineInfoEngine}
	info={engineInfoData}
	infoPromise={engineInfoPromise}
	errorMessage={engineInfoError}
/>