Skip to content

Modern Docker Management, Designed for Everyone

28.0 KB
Raw Blame
<script lang="ts">
	import { goto } from '$app/navigation';
	import { createQuery } from '@tanstack/svelte-query';
	import { onDestroy } from 'svelte';
	import { toast } from 'svelte-sonner';
	import { Temporal } from 'temporal-polyfill';

	import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
	import UniversalMobileCard from '#lib/components/arcane-table/cards/universal-mobile-card.svelte';
	import InUseStatus from '#lib/components/arcane-table/cells/in-use-status.svelte';
	import UnixCreatedCell from '#lib/components/arcane-table/cells/unix-created-cell.svelte';
	import { environmentColumns } from '#lib/components/arcane-table/environment-column.js';
	import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '#lib/components/arcane-table/index.js';
	import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
	import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
	import ImageUpdateItem from '#lib/components/image-update-item.svelte';
	import { Badge } from '#lib/components/ui/badge/index.js';
	import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
	import { Spinner } from '#lib/components/ui/spinner/index.js';
	import * as Tooltip from '#lib/components/ui/tooltip/index.js';
	import VulnerabilityScanItem from '#lib/components/vulnerability/vulnerability-scan-item.svelte';
	import {
		DownloadIcon,
		TrashIcon,
		InspectIcon,
		ImagesIcon,
		VolumesIcon,
		ClockIcon,
		ScanIcon,
		ShieldCheckIcon,
		ProjectsIcon,
		ContainersIcon,
		TagIcon
	} from '#lib/icons/index.js';
	import { m } from '#lib/paraglide/messages.js';
	import { queryKeys } from '#lib/query/query-keys.js';
	import { imageService, type ImagesPaginatedResponse } from '#lib/services/image-service.js';
	import { vulnerabilityService } from '#lib/services/vulnerability-service.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 { ImageSummaryDto, ImageUpdateInfoDto } from '#lib/types/docker.js';
	import type { VulnerabilityScanSummary } from '#lib/types/environment.js';
	import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
	import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
	import { handleApiResultWithCallbacks, extractApiErrorMessage } from '#lib/utils/api.js';
	import { hasPermission } from '#lib/utils/auth.js';
	import { bulkConfirmAndRun } from '#lib/utils/bulk-actions.js';
	import { isLikelyStaleFailedSummary, isVulnerabilityScanInProgress } from '#lib/utils/docker.js';
	import {
		collectAcrossEnvironments,
		environmentHref,
		fetchAcrossEnvironments,
		hasShownPermission,
		rowKey,
		type EnvironmentPage,
		type EnvironmentRow
	} from '#lib/utils/environments.js';
	import { bytes, formatDateTimeShort, nowInstantString } from '#lib/utils/formatting.js';
	import { inUseBadge } from '#lib/utils/mobile-card-badges.js';
	import { tryCatch } from '#lib/utils/try-catch.js';

	import ImageTagDialog from './image-tag-dialog.svelte';

	type ImageRow = EnvironmentRow<ImageSummaryDto>;

	let {
		images = $bindable(),
		selectedIds = $bindable(),
		requestOptions = $bindable(),
		onImageUpdated,
		onRefreshData,
		loading = false
	}: {
		images: EnvironmentPage<ImagesPaginatedResponse>;
		selectedIds: string[];
		requestOptions: SearchPaginationSortRequest;
		onImageUpdated?: () => Promise<void>;
		onRefreshData?: (options: SearchPaginationSortRequest) => Promise<void>;
		loading?: boolean;
	} = $props();

	let isLoading = $state({
		removing: false,
		checking: false
	});

	const vulnerabilityManagementEnabled = $derived(
		environmentStore.shown.some((env) => featureStore.isEnabled('vulnerabilityManagement', env.id))
	);
	// Track the user store: hasPermission reads it non-reactively, so without
	// this the deriveds would cache pre-hydration falses forever.
	const canDeleteImage = $derived.by(() => {
		userStore.current;
		return hasShownPermission('images:delete');
	});
	const canPullImage = $derived.by(() => {
		userStore.current;
		return hasShownPermission('images:pull');
	});
	const canScanImage = $derived.by(() => {
		userStore.current;
		return vulnerabilityManagementEnabled && hasShownPermission('vulnerabilities:scan');
	});
	const canTagImage = $derived.by(() => {
		userStore.current;
		return hasShownPermission('images:tag');
	});
	const canPatchImage = $derived.by(() => {
		userStore.current;
		return hasShownPermission('images:patch');
	});
	const canReadImage = $derived.by(() => {
		userStore.current;
		return hasShownPermission('images:read');
	});

	let tagDialogImage = $state<ImageRow | null>(null);
	let scanRequestedAtByImage = $state<Record<string, string>>({});
	// Set once on destroy so late async results don't touch a dead component.
	let destroyed = false;
	const SCAN_POLL_INTERVAL_MS = 4000;

	async function refreshImages(options: SearchPaginationSortRequest = requestOptions) {
		if (onRefreshData) {
			await onRefreshData(options);
			return;
		}
		images = await fetchAcrossEnvironments(environmentStore.shown, options, (id, request, config) =>
			imageService.getImagesForEnvironment(id, request, config)
		);
	}

	function handleDeleteSelected(ids: string[]) {
		bulkConfirmAndRun({
			ids,
			title: m.images_remove_selected_title({ count: ids.length }),
			message: m.images_remove_selected_message({ count: ids.length }),
			confirmLabel: m.common_remove(),
			destructive: true,
			checkboxes: [{ id: 'force', label: m.images_remove_force_label(), initialState: false }],
			run: (id, environmentId, checkboxStates) =>
				imageService.deleteImage(id, { force: !!checkboxStates['force'] }, environmentId),
			messages: {
				success: (count) => (count === 1 ? m.image_removed_successfully() : m.images_remove_success_many({ count })),
				partial: (success, total, failed) => m.common_bulk_remove_partial({ success, total, failed, resource: m.images() }),
				failure: () => (ids.length === 1 ? m.failed_to_remove_image() : m.images_remove_failed_many({ count: ids.length }))
			},
			setLoading: (loading) => (isLoading.removing = loading),
			onComplete: async (result) => {
				if (result.success > 0) await refreshImages();
			},
			clearSelection: () => (selectedIds = []),
			sequential: true
		});
	}

	async function deleteImage(id: string, environmentId: string) {
		openConfirmDialog({
			title: m.common_remove_title({ resource: m.resource_image() }),
			message: m.images_remove_message(),
			checkboxes: [
				{
					id: 'force',
					label: m.images_remove_force_label(),
					initialState: false
				}
			],
			confirm: {
				label: m.common_remove(),
				destructive: true,
				action: async (checkboxStates) => {
					const force = !!checkboxStates['force'];
					isLoading.removing = true;

					const result = await tryCatch(imageService.deleteImage(id, { force }, environmentId));
					await handleApiResultWithCallbacks({
						result,
						message: m.failed_to_remove_image(),
						setLoadingState: () => {},
						onSuccess: async (data) => {
							toast.success(m.image_removed_successfully(), activityToastOptions(extractActivityId(data)));
							await refreshImages();
						}
					});

					isLoading.removing = false;
				}
			}
		});
	}
	async function handleInlineImagePull(repoTag: string, environmentId: string) {
		if (!repoTag || repoTag === '<none>:<none>') {
			toast.error(m.images_pull_no_tag());
			return;
		}

		const result = await tryCatch(imageService.pullImage(repoTag, undefined, undefined, environmentId));
		await handleApiResultWithCallbacks({
			result,
			message: m.images_pull_failed(),
			setLoadingState: () => {},
			onSuccess: async (data) => {
				toast.success(m.images_pull_success({ repoTag }), activityToastOptions(extractActivityId(data)));
				await refreshImages();
			}
		});
	}

	async function handleInlineVulnerabilityScan(image: ImageRow) {
		if (!canScanImage) return;
		const requestedScope = environmentStore.shownKey;
		const result = await tryCatch(vulnerabilityService.scanImage(image.id, image.environmentId));
		if (destroyed || !vulnerabilityManagementEnabled || requestedScope !== environmentStore.shownKey) return;
		await handleApiResultWithCallbacks({
			result,
			message: m.vuln_scan_failed(),
			setLoadingState: () => {},
			onSuccess: async (data) => {
				scanRequestedAtByImage[rowKey(image)] = data.scanTime || nowInstantString();
				const summary: VulnerabilityScanSummary = {
					imageId: data.imageId,
					scanTime: data.scanTime,
					status: data.status,
					activityId: data.activityId,
					scanPhase: data.scanPhase,
					summary: data.summary,
					error: data.error
				};
				await handleVulnerabilityScanChanged(rowKey(image), summary);

				if (data.status === 'completed') {
					toast.success(m.vuln_scan_completed(), activityToastOptions(data.activityId));
					return;
				}
				if (data.status === 'failed') {
					toast.error(data.error || m.vuln_scan_failed(), activityToastOptions(data.activityId));
					return;
				}

				toast.info(m.vuln_scan_started(), activityToastOptions(data.activityId));
			}
		});
	}

	async function handleExportImage(imageId: string, environmentId: string) {
		const url = await imageService.getImageExportUrl(imageId, environmentId);
		window.open(url, '_blank', 'noopener,noreferrer');
	}

	async function handleInlineImagePatch(imageId: string, environmentId: string) {
		const result = await tryCatch(imageService.patchImage(imageId, undefined, environmentId));
		await handleApiResultWithCallbacks({
			result,
			message: m.images_patch_failed(),
			setLoadingState: () => {},
			onSuccess: async (data) => {
				toast.info(m.images_patch_started({ patchedRef: data.patchedRef }), activityToastOptions(data.activityId));
			}
		});
	}

	async function handleUpdateInfoChanged(key: string, newUpdateInfo: ImageUpdateInfoDto) {
		if (destroyed) return;
		images = {
			...images,
			data: images.data.map((image) => {
				if (rowKey(image) === key) return { ...image, updateInfo: newUpdateInfo };
				return image;
			})
		};
		await onImageUpdated?.();
	}

	async function handleVulnerabilityScanChanged(key: string, newScanSummary: VulnerabilityScanSummary) {
		if (destroyed) return;
		images = {
			...images,
			data: images.data.map((image) => {
				if (rowKey(image) === key) return { ...image, vulnerabilityScan: newScanSummary };
				return image;
			})
		};
		if (newScanSummary.status === 'completed' || newScanSummary.status === 'failed') {
			if (scanRequestedAtByImage[key]) {
				delete scanRequestedAtByImage[key];
				scanRequestedAtByImage = { ...scanRequestedAtByImage };
			}
		}
		if (newScanSummary.status === 'completed' || newScanSummary.status === 'failed') {
			await onImageUpdated?.();
		}
	}

	const scanningImages = $derived.by(() => {
		if (!vulnerabilityManagementEnabled) return [];
		return (images.data ?? []).filter((item) => isVulnerabilityScanInProgress(item.vulnerabilityScan?.status));
	});

	// Polls only while rows are scanning; TanStack pauses it while the tab is hidden.
	const scanSummariesQuery = createQuery(() => {
		const scanning = scanningImages;
		const scope = environmentStore.shownKey;
		return {
			queryKey: queryKeys.vulnerabilities.scanSummaries(scope, scanning.map(rowKey)),
			queryFn: async () => {
				const environments = environmentStore.shown.filter((env) => scanning.some((image) => image.environmentId === env.id));
				// A failing environment is reported; the others' summaries still apply.
				const { values, failures } = await collectAcrossEnvironments(environments, async (environmentId) => {
					const ids = scanning.filter((image) => image.environmentId === environmentId).map((image) => image.id);
					const response = await vulnerabilityService.getScanSummaries(ids, environmentId);
					return scanning
						.filter((image) => image.environmentId === environmentId && response?.summaries?.[image.id])
						.map((image) => [rowKey(image), response.summaries[image.id]!] as const);
				});
				const summaries = Object.fromEntries(values.flatMap(({ value }) => value));
				// Rows update from the fetch itself; a scope switch mid-request discards the result.
				if (scope === environmentStore.shownKey) await applyScanSummaries(summaries);
				return { summaries, failures };
			},
			enabled: scanning.length > 0,
			refetchInterval: SCAN_POLL_INTERVAL_MS,
			staleTime: 0,
			gcTime: 0
		};
	});

	const scanPollError = $derived.by(() => {
		if (scanSummariesQuery.error) return extractApiErrorMessage(scanSummariesQuery.error);
		return (
			scanSummariesQuery.data?.failures.map(({ environment, message }) => `${environment.name}: ${message}`).join('\n') || null
		);
	});

	async function applyScanSummaries(summaries: Record<string, VulnerabilityScanSummary>) {
		if (destroyed || Object.keys(summaries).length === 0 || !images.data?.length) return;
		let changed = false;
		let completed = false;
		const nextScanRequestedAtByImage = { ...scanRequestedAtByImage };
		const nextData = images.data.map((img) => {
			const key = rowKey(img);
			const summary = summaries[key];
			if (!summary) return img;

			if (
				summary.status === 'failed' &&
				isLikelyStaleFailedSummary(summary, nextScanRequestedAtByImage[key]) &&
				isVulnerabilityScanInProgress(img.vulnerabilityScan?.status)
			) {
				return img;
			}

			changed = true;
			if (summary.status === 'completed' || summary.status === 'failed') {
				completed = true;
				delete nextScanRequestedAtByImage[key];
			}
			return { ...img, vulnerabilityScan: summary };
		});
		if (changed) {
			images = { ...images, data: nextData };
			scanRequestedAtByImage = nextScanRequestedAtByImage;
		}
		if (completed) {
			await onImageUpdated?.();
		}
	}

	onDestroy(() => {
		destroyed = true;
	});

	const allColumns = $derived([
		...environmentColumns<ImageRow>(),
		{ accessorKey: 'id', title: m.common_id(), hidden: true },
		{ accessorKey: 'repo', title: m.resource_repository_cap(), sortable: true, cell: RepoCell },
		{ accessorKey: 'repoTags', title: m.common_tags(), cell: TagCell },
		{
			accessorKey: 'inUse',
			title: m.common_status(),
			sortable: true,
			cell: StatusCell
		},
		{
			id: 'usedBy',
			title: m.images_used_by(),
			cell: UsedByCell
		},
		{
			id: 'updates',
			accessorFn: (row) => {
				if (!row.repoDigests || row.repoDigests.length === 0) return 'local';
				if (row.updateInfo?.hasUpdate) return 'has_update';
				if (row.updateInfo?.updateType === 'local') return 'local';
				if (row.updateInfo?.error) return 'error';
				if (row.updateInfo) return 'up_to_date';
				return 'unknown';
			},
			title: m.updates(),
			cell: UpdatesCell,
			align: 'center',
			class: 'text-center'
		},
		{
			id: 'vulnerabilities',
			accessorFn: (row) => {
				if (!row.vulnerabilityScan) return 'not_scanned';
				if (row.vulnerabilityScan.status === 'failed') return 'error';
				if (row.vulnerabilityScan.status === 'completed') {
					const total = row.vulnerabilityScan.summary?.total ?? 0;
					const critical = row.vulnerabilityScan.summary?.critical ?? 0;
					const high = row.vulnerabilityScan.summary?.high ?? 0;
					if (critical > 0) return 'critical';
					if (high > 0) return 'high';
					if (total > 0) return 'has_vulnerabilities';
					return 'clean';
				}
				return 'scanning';
			},
			title: m.vuln_title(),
			sortable: true,
			cell: VulnerabilitiesCell,
			align: 'center',
			class: 'text-center'
		},
		{ accessorKey: 'size', title: m.common_size(), sortable: true, cell: SizeCell },
		{ accessorKey: 'created', title: m.common_created(), sortable: true, cellComponent: UnixCreatedCell }
	] satisfies ColumnSpec<ImageRow>[]);

	const columns = $derived(allColumns.filter((column) => vulnerabilityManagementEnabled || column.id !== 'vulnerabilities'));

	const allMobileFields = [
		{ id: 'id', label: m.common_id(), defaultVisible: false },
		{ id: 'repoTags', label: m.common_tags(), defaultVisible: true },
		{ id: 'inUse', label: m.common_status(), defaultVisible: true },
		{ id: 'usedBy', label: m.images_used_by(), defaultVisible: false },
		{ id: 'updates', label: m.updates(), defaultVisible: false },
		{ id: 'vulnerabilities', label: m.vuln_title(), defaultVisible: false },
		{ id: 'size', label: m.common_size(), defaultVisible: true },
		{ id: 'created', label: m.common_created(), defaultVisible: true }
	];

	const mobileFields = $derived(
		allMobileFields.filter((field) => vulnerabilityManagementEnabled || field.id !== 'vulnerabilities')
	);

	const bulkActions = $derived.by<BulkAction[]>(() => [
		{
			id: 'remove',
			label: m.common_remove_selected_count({ count: selectedIds?.length ?? 0 }),
			action: 'remove',
			onClick: handleDeleteSelected,
			loading: isLoading.removing,
			disabled: !canDeleteImage || isLoading.removing,
			icon: TrashIcon
		}
	]);

	let mobileFieldVisibility = $state<Record<string, boolean>>({});
</script>

{#snippet RepoCell({ item }: { item: ImageRow })}
	{#if item.repo && item.repo !== '<none>'}
		<a class="font-medium hover:underline" href={environmentHref(`/images/${item.id}`, item.environmentId)}>{item.repo}</a>
	{:else}
		<span class="text-muted-foreground italic">{m.images_untagged()}</span>
	{/if}
{/snippet}

{#snippet TagCell({ item }: { item: ImageRow })}
	{#if item.repoTags && item.repoTags.length > 0 && item.repoTags[0] !== '<none>:<none>'}
		<div class="flex flex-wrap gap-1.5">
			{#each item.repoTags.slice(0, 2) as repoTag, tagIndex (`${repoTag}-${tagIndex}`)}
				{@const tag = repoTag.split(':').pop() || repoTag}
				<Badge variant="outline" mono>{tag}</Badge>
			{/each}
			{#if item.repoTags.length > 2}
				<Badge variant="outline">+{item.repoTags.length - 2}</Badge>
			{/if}
		</div>
	{:else if item.pinnedReferences && item.pinnedReferences.length > 0 && item.pinnedReferences[0]}
		{@const firstPin = item.pinnedReferences[0]}
		{@const overflowPins = item.pinnedReferences.slice(1)}
		<div class="flex max-w-md flex-wrap items-center gap-1.5">
			<Badge
				variant="outline"
				mono
				class="h-auto max-w-full break-all whitespace-normal select-all"
				title={m.common_click_to_select()}
			>
				{firstPin}
			</Badge>
			{#if overflowPins.length > 0}
				<Tooltip.Provider>
					<Tooltip.Root>
						<Tooltip.Trigger>
							<Badge variant="outline">+{overflowPins.length}</Badge>
						</Tooltip.Trigger>
						<Tooltip.Content class="pointer-events-auto max-w-sm">
							<div class="flex flex-col gap-1.5">
								{#each overflowPins as pin (pin)}
									<span class="font-mono text-xs break-all select-all">{pin}</span>
								{/each}
							</div>
						</Tooltip.Content>
					</Tooltip.Root>
				</Tooltip.Provider>
			{/if}
		</div>
	{:else if item.tag && item.tag !== '<none>'}
		<Badge variant="outline" mono>{item.tag}</Badge>
	{:else}
		<span class="text-muted-foreground italic">{m.images_untagged()}</span>
	{/if}
{/snippet}

{#snippet SizeCell({ value }: { value: unknown })}
	{bytes.format(Number(value ?? 0))}
{/snippet}

{#snippet StatusCell({ item }: { item: ImageRow })}
	<InUseStatus inUse={item.inUse} />
{/snippet}

{#snippet UsageBadgeList(usages: NonNullable<ImageSummaryDto['usedBy']>, environmentId: string)}
	{#each usages as usage, usageIndex (`${usage.type}-${usage.id ?? usage.name}-${usageIndex}`)}
		{#if usage.type === 'project'}
			{#if usage.id}
				<Badge variant="outline" href={environmentHref(`/projects/${encodeURIComponent(usage.id)}`, environmentId)}>
					<ProjectsIcon class="size-3" />
					<span>{usage.name}</span>
				</Badge>
			{:else}
				<Badge variant="outline">
					<ProjectsIcon class="size-3" />
					<span>{usage.name}</span>
				</Badge>
			{/if}
		{:else if usage.id}
			<Badge variant="outline" href={environmentHref(`/containers/${encodeURIComponent(usage.id)}`, environmentId)}>
				<ContainersIcon class="size-3" />
				<span>{usage.name}</span>
			</Badge>
		{:else}
			<Badge variant="outline">
				<ContainersIcon class="size-3" />
				<span>{usage.name}</span>
			</Badge>
		{/if}
	{/each}
{/snippet}

{#snippet UsedByCell({ item }: { item: ImageRow })}
	{#if item.usedBy && item.usedBy.length > 0}
		{@const maxVisible = 3}
		{@const hasOverflow = item.usedBy.length > maxVisible}
		{@const visibleUsage = hasOverflow ? item.usedBy.slice(0, maxVisible) : item.usedBy}
		{@const overflowUsage = hasOverflow ? item.usedBy.slice(maxVisible) : []}
		<div class="flex flex-wrap gap-1.5">
			{@render UsageBadgeList(visibleUsage, item.environmentId)}
			{#if hasOverflow}
				<Tooltip.Provider>
					<Tooltip.Root>
						<Tooltip.Trigger>
							<Badge variant="outline">
								+{overflowUsage.length}
							</Badge>
						</Tooltip.Trigger>
						<Tooltip.Content class="pointer-events-auto">
							<div class="flex max-w-xs flex-wrap gap-1.5">
								{@render UsageBadgeList(overflowUsage, item.environmentId)}
							</div>
						</Tooltip.Content>
					</Tooltip.Root>
				</Tooltip.Provider>
			{/if}
		</div>
	{:else}
		<span class="text-muted-foreground">—</span>
	{/if}
{/snippet}

{#snippet UpdatesCell({ item }: { item: ImageRow })}
	<div class="flex items-center justify-center">
		<ImageUpdateItem
			updateInfo={item.updateInfo}
			imageId={item.id}
			environmentId={item.environmentId}
			repo={item.repo}
			tag={item.tag}
			isLocal={!item.repoDigests || item.repoDigests.length === 0}
			onUpdated={(newInfo) => handleUpdateInfoChanged(rowKey(item), newInfo)}
		/>
	</div>
{/snippet}

{#snippet VulnerabilitiesCell({ item }: { item: ImageRow })}
	<!-- The column shows when any environment scans; each row needs its own environment to. -->
	{#if featureStore.isEnabled('vulnerabilityManagement', item.environmentId)}
		<div class="flex items-center justify-center">
			<VulnerabilityScanItem
				scanSummary={item.vulnerabilityScan}
				imageId={item.id}
				environmentId={item.environmentId}
				pollError={scanPollError}
				onScanned={(newSummary) => handleVulnerabilityScanChanged(rowKey(item), newSummary)}
			/>
		</div>
	{/if}
{/snippet}

{#snippet MobileTagsValue(item: ImageRow)}
	{#if item.repoTags && item.repoTags.length > 0 && item.repoTags[0] !== '<none>:<none>'}
		<span class="font-mono text-xs">{item.repoTags.map((rt) => rt.split(':').pop() || rt).join(', ')}</span>
	{:else if item.pinnedReferences && item.pinnedReferences.length > 0}
		<span class="font-mono text-xs break-all whitespace-normal select-all">
			{item.pinnedReferences[0]}
			{#if item.pinnedReferences.length > 1}
				<span class="ml-1 font-sans text-muted-foreground">+{item.pinnedReferences.length - 1}</span>
			{/if}
		</span>
	{:else if item.tag && item.tag !== '<none>'}
		<span class="font-mono text-xs">{item.tag}</span>
	{:else}
		<span class="text-muted-foreground italic">{m.images_untagged()}</span>
	{/if}
{/snippet}

{#snippet ImageMobileCardSnippet({
	item,
	mobileFieldVisibility
}: {
	item: ImageRow;
	mobileFieldVisibility: MobileFieldVisibility;
})}
	<UniversalMobileCard
		{item}
		icon={(item) => ({
			component: ImagesIcon,
			variant: item.inUse ? 'emerald' : 'amber'
		})}
		title={(item) => {
			if (item.repo && item.repo !== '<none>') return item.repo;
			if (item.pinnedReferences && item.pinnedReferences.length > 0 && item.pinnedReferences[0]) {
				return item.pinnedReferences[0];
			}
			return m.images_untagged();
		}}
		subtitle={(item) => ((mobileFieldVisibility['id'] ?? false) ? item.id : null)}
		badges={[
			inUseBadge(mobileFieldVisibility['inUse'] ?? true),
			(item: ImageRow) => {
				if (!(mobileFieldVisibility['updates'] ?? false)) return null;
				if (!item.repoDigests || item.repoDigests.length === 0) {
					return { variant: 'gray' as const, text: m.image_update_local_title() };
				}
				if (item.updateInfo?.hasUpdate) return { variant: 'blue' as const, text: m.images_has_updates() };
				if (item.updateInfo?.updateType === 'local') return { variant: 'gray' as const, text: m.image_update_local_title() };
				if (item.updateInfo?.error) return { variant: 'red' as const, text: m.common_error() };
				if (item.updateInfo) return { variant: 'green' as const, text: m.images_no_updates() };
				return { variant: 'gray' as const, text: m.common_unknown() };
			}
		]}
		fields={[
			{
				label: m.common_size(),
				getValue: (item: ImageRow) => bytes.format(Number(item.size ?? 0)),
				icon: VolumesIcon,
				iconVariant: 'blue' as const,
				show: mobileFieldVisibility['size'] ?? true
			},
			{
				label: m.common_tags(),
				getValue: (item: ImageRow) => item,
				type: 'component',
				component: MobileTagsValue,
				icon: ImagesIcon,
				iconVariant: 'purple' as const,
				show: mobileFieldVisibility['repoTags'] ?? true
			},
			{
				label: m.images_used_by(),
				getValue: (item: ImageRow) => item.usedBy?.map((usage) => usage.name).join(', ') || '—',
				icon: ImagesIcon,
				iconVariant: 'purple' as const,
				show: mobileFieldVisibility['usedBy'] ?? false
			}
		]}
		footer={(mobileFieldVisibility['created'] ?? true)
			? {
					label: m.common_created(),
					getValue: (item) => formatDateTimeShort(Temporal.Instant.fromEpochMilliseconds(Number(item.created || 0) * 1000)),
					icon: ClockIcon
				}
			: undefined}
		rowActions={RowActions}
		onclick={(item: ImageRow) => goto(environmentHref(`/images/${item.id}`, item.environmentId))}
	/>
{/snippet}

{#snippet RowActions({ item }: { item: ImageRow })}
	{@const envId = item.environmentId}
	<RowActionsMenu>
		<DropdownMenu.Item onclick={() => goto(environmentHref(`/images/${item.id}`, envId))}>
			<InspectIcon class="size-4" />
			{m.common_inspect()}
		</DropdownMenu.Item>

		{#if canPullImage || canScanImage || canTagImage || canReadImage}
			<DropdownMenu.Separator />
		{/if}

		{#if canTagImage && hasPermission('images:tag', envId)}
			<DropdownMenu.Item onclick={() => (tagDialogImage = item)}>
				<TagIcon class="size-4" />
				{m.images_tag_image()}
			</DropdownMenu.Item>
		{/if}

		{#if canReadImage && hasPermission('images:read', envId)}
			<DropdownMenu.Item onclick={() => handleExportImage(item.id, envId)}>
				<DownloadIcon class="size-4" />
				{m.images_export()}
			</DropdownMenu.Item>
		{/if}

		{@const usableTags = item.repoTags?.filter((tag) => tag !== '<none>:<none>') ?? []}
		<!-- Prefer a real tag: a digest name kept beside it would pull the old pinned image. -->
		{@const usableTag = usableTags.find((tag) => !tag.includes('@')) ?? usableTags[0]}
		{#if canPullImage && hasPermission('images:pull', envId)}
			<DropdownMenu.Item onclick={() => handleInlineImagePull(usableTag || '', envId)} disabled={!usableTag}>
				<DownloadIcon class="size-4" />
				{m.pull()}
			</DropdownMenu.Item>
		{/if}

		{#if canScanImage && featureStore.isEnabled('vulnerabilityManagement', envId) && hasPermission('vulnerabilities:scan', envId)}
			<DropdownMenu.Item onclick={() => handleInlineVulnerabilityScan(item)}>
				<ScanIcon class="size-4" />
				{m.vuln_scan()}
			</DropdownMenu.Item>
		{/if}

		{#if canPatchImage && hasPermission('images:patch', envId)}
			{@const imageIsLocal = !item.repoDigests || item.repoDigests.length === 0}
			<DropdownMenu.Item onclick={() => handleInlineImagePatch(item.id, envId)} disabled={imageIsLocal || !usableTag}>
				<ShieldCheckIcon class="size-4" />
				<div class="flex flex-col items-start">
					<span>{m.images_patch()}</span>
					{#if imageIsLocal}
						<span class="text-xs text-muted-foreground">{m.security_local_image_unpatchable()}</span>
					{/if}
				</div>
			</DropdownMenu.Item>
		{/if}

		{#if canDeleteImage && hasPermission('images:delete', envId)}
			<DropdownMenu.Separator />

			<DropdownMenu.Item variant="destructive" onclick={() => deleteImage(item.id, envId)} disabled={isLoading.removing}>
				{#if isLoading.removing}
					<Spinner class="size-4" />
				{:else}
					<TrashIcon class="size-4" />
				{/if}
				{m.common_remove()}
			</DropdownMenu.Item>
		{/if}
	</RowActionsMenu>
{/snippet}

<ArcaneTable
	persistKey="arcane-image-table"
	items={images}
	{loading}
	bind:requestOptions
	bind:selectedIds
	bind:mobileFieldVisibility
	{bulkActions}
	onRefresh={async (options) => {
		requestOptions = options;
		await refreshImages(options);
		return images;
	}}
	{columns}
	{mobileFields}
	rowActions={RowActions}
	mobileCard={ImageMobileCardSnippet}
/>

{#if tagDialogImage}
	<ImageTagDialog
		open={!!tagDialogImage}
		imageId={tagDialogImage.id}
		environmentId={tagDialogImage.environmentId}
		defaultRepository={tagDialogImage.repo !== '<none>' ? tagDialogImage.repo : ''}
		onOpenChange={(open) => {
			if (!open) tagDialogImage = null;
		}}
		onTagged={async () => refreshImages()}
	/>
{/if}