This commit is contained in:
jarek committed 2026-07-25 08:41:01 +02:00
1 parent 9f09d60a83
commit 64b6dcd744
177 files changed
+21182 -1042

No files matched your search

+35 -4
View File
@@ -13,7 +13,7 @@
import * as Tooltip from '$lib/components/ui/tooltip';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import { formatPorts, formatExposedPorts } from '$lib/utils/port-format';
import { formatBytes } from '$lib/utils/format';
import { formatBytes, formatBytesCompact } from '$lib/utils/format';
import MultiSelectFilter from '$lib/components/MultiSelectFilter.svelte';
import PageHeader from '$lib/components/PageHeader.svelte';
import { Badge } from '$lib/components/ui/badge';
@@ -306,6 +306,10 @@
// Set of container IDs with updates available (for O(1) lookup)
const containersWithUpdatesSet = $derived(new Set(batchUpdateContainerIds));
// Container IDs whose last update check failed (e.g. registry rate-limited) — #1255
const containersWithFailedCheckSet = $derived(new Set($containerStore.failedUpdateIds));
const failedUpdateErrors = $derived($containerStore.failedUpdateErrors);
// Filter dropdown entries: real statuses plus the synthetic
// "update-available" entry, only offered once we know about a pending
// update — picking it on an empty set would just empty the list (#1063).
@@ -460,6 +464,7 @@
function handleUpdateCheckComplete(result: {
withUpdates: Array<{ containerId: string; containerName: string }>;
failed?: Array<{ containerId: string; error: string }>;
}) {
if (result.withUpdates.length === 0) {
containerStore.setPendingUpdates([], new Map());
@@ -470,6 +475,13 @@
new Map(result.withUpdates.map((r) => [r.containerId, r.containerName]))
);
}
// Record failed checks so their containers show a "check failed" state
// instead of masquerading as up to date (#1255).
const failed = result.failed ?? [];
containerStore.setFailedUpdates(
failed.map((f) => f.containerId),
new Map(failed.map((f) => [f.containerId, f.error]))
);
}
// Load pending updates from database (persisted from check-updates or scheduled jobs)
@@ -505,6 +517,9 @@
const response = await fetch(`/api/containers/pending-updates?env=${envId}`, { method: 'DELETE' });
if (response.ok) {
containerStore.setPendingUpdates([], new Map());
// Failed-check state is session-only — clear it here too so "Clear"
// dismisses the red "check failed" icons alongside the amber ones.
containerStore.setFailedUpdates([], new Map());
}
} catch {
toast.error('Failed to clear update indicators');
@@ -1746,6 +1761,22 @@
</a>
{/if}
{/if}
{:else if containersWithFailedCheckSet.has(container.id)}
<Tooltip.Root>
<Tooltip.Trigger>
<AlertTriangle class="w-3 h-3 text-red-500 shrink-0 cursor-help" />
</Tooltip.Trigger>
<Tooltip.Content side="right" class="w-72 p-3">
<div class="space-y-1.5">
<p class="font-medium text-sm flex items-center gap-1.5 whitespace-nowrap">
<AlertTriangle class="w-4 h-4 text-red-500 shrink-0" />
Update check failed
</p>
<p class="text-muted-foreground text-xs break-words">{failedUpdateErrors.get(container.id) ?? 'Could not query registry'}</p>
<p class="text-muted-foreground text-xs">Update status unknown — often a Docker Hub rate limit. Try again later.</p>
</div>
</Tooltip.Content>
</Tooltip.Root>
{/if}
<span class="text-xs text-muted-foreground truncate" title={container.image}>{container.image}</span>
</div>
@@ -1797,7 +1828,7 @@
{@const memoryTooltip = stats.memoryCache > 0
? `${formatBytes(stats.memoryUsage)} / ${formatBytes(stats.memoryLimit)} (Total: ${formatBytes(stats.memoryRaw)} | Cache: ${formatBytes(stats.memoryCache)})`
: `${formatBytes(stats.memoryUsage)} / ${formatBytes(stats.memoryLimit)}`}
<span class="text-xs font-mono {stats.memoryPercent > 80 ? 'text-red-500' : stats.memoryPercent > 50 ? 'text-yellow-500' : 'text-muted-foreground'}" title={memoryTooltip}>{formatBytes(stats.memoryUsage)}<span class="text-muted-foreground/50">/{formatBytes(stats.memoryLimit, 0)}</span></span>
<span class="text-xs font-mono {stats.memoryPercent > 80 ? 'text-red-500' : stats.memoryPercent > 50 ? 'text-yellow-500' : 'text-muted-foreground'}" title={memoryTooltip}>{formatBytesCompact(stats.memoryUsage)}<span class="text-muted-foreground/50">/{formatBytesCompact(stats.memoryLimit, 0)}</span></span>
{:else if container.state === 'running'}
<span class="text-xs text-muted-foreground/50">...</span>
{:else}
@@ -1809,7 +1840,7 @@
{#if containerStats.get(container.id)}
{@const stats = containerStats.get(container.id)}
<span class="text-xs font-mono text-muted-foreground" title="↓{formatBytes(stats.networkRx)} received / ↑{formatBytes(stats.networkTx)} sent">
<span class="text-2xs text-blue-400">↓</span>{formatBytes(stats.networkRx, 0)} <span class="text-2xs text-orange-400">↑</span>{formatBytes(stats.networkTx, 0)}
<span class="text-2xs text-blue-400">↓</span>{formatBytesCompact(stats.networkRx, 0)} <span class="text-2xs text-orange-400">↑</span>{formatBytesCompact(stats.networkTx, 0)}
</span>
{:else if container.state === 'running'}
<span class="text-xs text-muted-foreground/50">...</span>
@@ -1822,7 +1853,7 @@
{#if containerStats.get(container.id)}
{@const stats = containerStats.get(container.id)}
<span class="text-xs font-mono text-muted-foreground" title="↓{formatBytes(stats.blockRead)} read / ↑{formatBytes(stats.blockWrite)} written">
<span class="text-2xs text-green-400">r</span>{formatBytes(stats.blockRead, 0)} <span class="text-2xs text-yellow-400">w</span>{formatBytes(stats.blockWrite, 0)}
<span class="text-2xs text-green-400">r</span>{formatBytesCompact(stats.blockRead, 0)} <span class="text-2xs text-yellow-400">w</span>{formatBytesCompact(stats.blockWrite, 0)}
</span>
{:else if container.state === 'running'}
<span class="text-xs text-muted-foreground/50">...</span>
+824
View File
@@ -0,0 +1,824 @@
<script lang="ts">
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label';
import { Badge } from '$lib/components/ui/badge';
import { TogglePill } from '$lib/components/ui/toggle-pill';
import CronEditor from '$lib/components/cron-editor.svelte';
import { Save, Play, Pause, RefreshCw, CheckCircle, XCircle, ChevronDown, Loader2, Plus, Trash2, Pencil, X, Check, HardDrive, Box, Layers, FileText } from 'lucide-svelte';
import RotateCwFadingClock from '$lib/components/icons/RotateCwFadingClock.svelte';
import VolumePicker from '$lib/components/backup/VolumePicker.svelte';
import DestinationPicker from '$lib/components/backup/DestinationPicker.svelte';
import LogConsole from '$lib/components/LogConsole.svelte';
import SnapshotsPanel from './SnapshotsPanel.svelte';
import ExecutionHistoryList from '$lib/components/ExecutionHistoryList.svelte';
import ExecutionLogViewer from '$lib/components/ExecutionLogViewer.svelte';
import EnvironmentIcon from '$lib/components/EnvironmentIcon.svelte';
import * as Dialog from '$lib/components/ui/dialog';
import * as Select from '$lib/components/ui/select';
import { currentEnvironment, appendEnvParam, environments } from '$lib/stores/environment';
import { formatDateTime } from '$lib/stores/settings';
import { watchJob } from '$lib/utils/sse-fetch';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import { getRepoTypeIcon, isLocalRepo, isRemoteEnvironment, parseRetention, parseOptions, retentionSummary as getRetentionSummary, formatCron, runBackupAction, classifyJobResult, tagLogLine, fetchBackupExecutions, type BackupAction, type BackupFormState } from '$lib/utils/backup';
interface Props {
containerName: string;
volumes: { name: string; mountPoint: string; mountType?: 'volume' | 'bind' }[];
type?: 'container' | 'stack';
environmentId?: number;
onConfigSaved?: () => void;
autoShowRunForm?: boolean;
/** Reports the ok/fail run tally so the parent modal can badge its Backups tab. */
onTally?: (tally: { ok: number; failed: number }) => void;
}
let { containerName, volumes, type = 'container', environmentId, onConfigSaved, autoShowRunForm = false, onTally }: Props = $props();
interface Destination { id: number; name: string; repository: string; }
interface BackupConfig {
id: number; destinationId: number; enabled: boolean; schedule: string;
retention: string | null; options?: string | null; stopBeforeBackup: boolean; selectedVolumes: string[] | null;
lastBackupStatus?: string | null; lastBackupAt?: string | null;
}
const getTypeIcon = getRepoTypeIcon;
// Sub-tabs: Schedules (this panel) and Snapshots (lazily mounted — its snapshot
// listing hits every repo over the network, so it must NOT run until the user
// actually opens the tab, to keep the container/stack modal responsive).
let subTab = $state<'schedules' | 'snapshots' | 'history'>('schedules');
// Snapshot count + loading state, reported by SnapshotsPanel (which loads in the
// background as soon as the Backups view opens). null count = not loaded yet.
let snapshotCount = $state<number | null>(null);
let snapshotsLoading = $state(false);
// Execution history + ok/fail tally, loaded from the executions API for this
// target's configs. Powers the History sub-tab and the parent modal's tab badge.
let executions = $state<import('$lib/utils/execution-tally').Execution[]>([]);
let tally = $state<{ ok: number; failed: number }>({ ok: 0, failed: 0 });
let historyLoading = $state(false);
// Backup-run log viewer (opened from the History table's log button).
let logDialogOpen = $state(false);
let logDialogContent = $state<string | null>(null);
let logDialogLoading = $state(false);
// The list query omits the (potentially large) logs column, so fetch the single
// execution's logs on demand from the detail endpoint — otherwise the dialog
// always showed "No log output".
async function viewExecutionLog(id: number) {
logDialogContent = null;
logDialogLoading = true;
logDialogOpen = true;
try {
const res = await fetch(`/api/schedules/executions/${id}`);
if (res.ok) {
const detail = await res.json();
logDialogContent = detail?.logs ?? null;
}
} catch { /* leave null → "No log output" */ }
finally { logDialogLoading = false; }
}
// Ref to the (always-mounted) snapshots panel so a manual backup can force it to
// reload — a new snapshot won't show up otherwise (the panel loads once on mount).
let snapshotsPanel = $state<{ refresh: () => Promise<void> } | null>(null);
let destinations = $state<Destination[]>([]);
let configs = $state<BackupConfig[]>([]);
let loading = $state(true);
let runningBackup = $state<number | null>(null);
let confirmDeleteId = $state<number | null>(null);
// Edit form state
let editingConfig = $state<BackupConfig | null>(null);
let isNew = $state(false);
let editDestinationId = $state(0);
let editEnabled = $state(true);
let editSchedule = $state('0 2 * * *');
let editScheduleInvalid = $state(false);
let editKeepLast = $state(7);
let editKeepDaily = $state(0);
let editKeepWeekly = $state(0);
let editKeepMonthly = $state(0);
let editKeepYearly = $state(0);
let editExclude = $state('');
let editExcludeCaches = $state(true);
let editCompression = $state('auto');
let editLimitUpload = $state('');
let editLimitDownload = $state('');
let editWebhookSuccess = $state('');
let editWebhookFailure = $state('');
let editStopBefore = $state(false);
let editAllVolumes = $state(true);
let editSelectedVolumes = $state<string[]>([]);
let saving = $state(false);
// Tracks which submit action is in-flight so we can disable the right
// button and show the right spinner. The form itself is unified — only
// the post-submit behavior differs.
let submitAction = $state<'save' | 'save-run' | 'run-once' | null>(null);
let showAdvanced = $state(false);
// Live restic progress for a manual backup run (Run once / Save & run now, and
// the per-config Run-now button). Streamed into a modal so the user sees the
// same restic output the CreateBackupModal wizard shows.
let progressOpen = $state(false);
let progressLogs = $state<string[]>([]);
let progressStatus = $state<'running' | 'success' | 'error'>('running');
let progressError = $state('');
// Which repo the in-flight run targets, for the progress-modal header.
let progressDestId = $state<number>(0);
// The config id of the running backup, so the modal's Cancel can stop it.
let progressConfigId = $state<number | null>(null);
let cancelling = $state(false);
async function cancelRunningBackup() {
if (progressConfigId == null || cancelling) return;
cancelling = true;
try {
const res = await fetch(`/api/backup/configs/${progressConfigId}/stop`, { method: 'POST' });
if (res.ok) {
progressLogs = [...progressLogs, '[dockhand] Cancelling backup…'];
} else {
const d = await res.json().catch(() => ({}));
toast.error(d.error || 'Failed to cancel backup');
}
} catch {
toast.error('Failed to cancel backup');
} finally {
cancelling = false;
}
}
// Header bits: the type icon, the target repo (with its type icon), and the env.
const TypeIcon = $derived(type === 'stack' ? Layers : Box);
const progressDest = $derived(destinations.find((d) => d.id === progressDestId));
const progressEnv = $derived($environments.find((e) => e.id === envId));
const envId = $derived(environmentId ?? $currentEnvironment?.id ?? null);
const isCurrentEnvRemote = $derived(() => isRemoteEnvironment($currentEnvironment));
async function fetchDestinations() {
try {
const res = await fetch('/api/backup/destinations');
if (res.ok) destinations = await res.json();
} catch {}
}
async function fetchConfigs() {
loading = true;
try {
const params = new URLSearchParams({ target: containerName, type });
if (envId) params.set('env', String(envId));
const res = await fetch(`/api/backup/configs?${params}`);
if (res.ok) {
const results = await res.json();
configs = Array.isArray(results) ? results : results?.id ? [results] : [];
// Auto-open the unified create form when there are no configs
// (used by the backup wizard entry point so the user doesn't
// have to click "Add schedule" first on an empty list).
if (configs.length === 0 && !isNew && !editingConfig && autoShowRunForm) startNewConfig();
void loadHistory();
}
} catch {} finally { loading = false; }
}
// Load run history + tally as soon as the configs are known — the parent modal's
// tab badge needs the ok/fail counts without the user opening the History tab.
async function loadHistory() {
const ids = configs.map((c) => c.id);
if (ids.length === 0) { executions = []; tally = { ok: 0, failed: 0 }; onTally?.(tally); return; }
historyLoading = true;
try {
// Map each config to its destination so the History table can show a Repo
// column — a target can back up to more than one repo.
const repoByConfig = new Map(configs.map((c) => {
const d = destinations.find((x) => x.id === c.destinationId);
return [c.id, { repository: d?.repository, name: d?.name }] as const;
}));
const r = await fetchBackupExecutions(ids, 50, repoByConfig);
executions = r.executions;
tally = { ok: r.ok, failed: r.failed };
onTally?.(tally);
} finally { historyLoading = false; }
}
function startNewConfig() {
editingConfig = null;
isNew = true;
editDestinationId = destinations[0]?.id || 0;
editEnabled = true;
editSchedule = '0 2 * * *';
editKeepLast = 7; editKeepDaily = 0; editKeepWeekly = 0; editKeepMonthly = 0; editKeepYearly = 0;
editExclude = ''; editExcludeCaches = true; editCompression = 'auto'; editLimitUpload = ''; editLimitDownload = '';
editWebhookSuccess = ''; editWebhookFailure = '';
editStopBefore = false;
editAllVolumes = true;
editSelectedVolumes = [];
showAdvanced = false;
}
function startEditConfig(cfg: BackupConfig) {
editingConfig = cfg;
isNew = false;
editDestinationId = cfg.destinationId;
editEnabled = cfg.enabled;
editSchedule = cfg.schedule || '0 2 * * *';
const ret = parseRetention(cfg.retention);
editKeepLast = ret.keepLast || 0;
editKeepDaily = ret.keepDaily || 0;
editKeepWeekly = ret.keepWeekly || 0;
editKeepMonthly = ret.keepMonthly || 0;
editKeepYearly = ret.keepYearly || 0;
const opts = parseOptions(cfg.options);
editExclude = opts.excludePatterns || '';
editExcludeCaches = opts.excludeCaches !== false;
editCompression = opts.compression || 'auto';
editLimitUpload = opts.limitUpload || '';
editLimitDownload = opts.limitDownload || '';
editWebhookSuccess = opts.webhookSuccess || '';
editWebhookFailure = opts.webhookFailure || '';
editStopBefore = cfg.stopBeforeBackup;
editAllVolumes = cfg.selectedVolumes === null;
editSelectedVolumes = cfg.selectedVolumes ? (typeof cfg.selectedVolumes === 'string' ? JSON.parse(cfg.selectedVolumes) : cfg.selectedVolumes) : [];
showAdvanced = false;
}
function cancelEdit() {
editingConfig = null;
isNew = false;
}
/**
* Does the inline backup edit-form hold unsaved changes? Called by the parent
* modal (EditContainerModal / StackModal) before it closes, so a half-edited
* schedule (cron / keep-last / options) doesn't vanish silently.
*
* - A NEW config form open = dirty (the user started creating one, unsaved).
* - An EDIT form = dirty only if some field differs from the pristine config.
* The comparison mirrors startEditConfig() exactly, in reverse, so it matches
* what a save would persist (via parseRetention/parseOptions on editingConfig).
* - No form open (editingConfig null, not new) = not dirty.
*/
export function isDirty(): boolean {
if (isNew) return true;
if (!editingConfig) return false;
const cfg = editingConfig;
if (editDestinationId !== cfg.destinationId) return true;
if (editEnabled !== cfg.enabled) return true;
if (editSchedule !== (cfg.schedule || '0 2 * * *')) return true;
const ret = parseRetention(cfg.retention);
if (editKeepLast !== (ret.keepLast || 0)) return true;
if (editKeepDaily !== (ret.keepDaily || 0)) return true;
if (editKeepWeekly !== (ret.keepWeekly || 0)) return true;
if (editKeepMonthly !== (ret.keepMonthly || 0)) return true;
if (editKeepYearly !== (ret.keepYearly || 0)) return true;
const opts = parseOptions(cfg.options);
if (editExclude !== (opts.excludePatterns || '')) return true;
if (editExcludeCaches !== (opts.excludeCaches !== false)) return true;
if (editCompression !== (opts.compression || 'auto')) return true;
if (editLimitUpload !== (opts.limitUpload || '')) return true;
if (editLimitDownload !== (opts.limitDownload || '')) return true;
if (editWebhookSuccess !== (opts.webhookSuccess || '')) return true;
if (editWebhookFailure !== (opts.webhookFailure || '')) return true;
if (editStopBefore !== cfg.stopBeforeBackup) return true;
if (editAllVolumes !== (cfg.selectedVolumes === null)) return true;
const origVolumes = cfg.selectedVolumes
? (typeof cfg.selectedVolumes === 'string' ? JSON.parse(cfg.selectedVolumes) : cfg.selectedVolumes)
: [];
if (JSON.stringify([...editSelectedVolumes].sort()) !== JSON.stringify([...origVolumes].sort())) return true;
return false;
}
/** Snapshot the current form fields into the shared BackupFormState shape. */
function currentForm(): BackupFormState {
return {
targetName: containerName,
type,
environmentId: envId,
destinationId: editDestinationId,
stopBeforeBackup: editStopBefore,
allVolumes: editAllVolumes,
selectedVolumes: editSelectedVolumes,
retention: {
keepLast: editKeepLast || undefined,
keepDaily: editKeepDaily || undefined,
keepWeekly: editKeepWeekly || undefined,
keepMonthly: editKeepMonthly || undefined,
keepYearly: editKeepYearly || undefined
},
options: {
excludePatterns: editExclude || undefined,
excludeCaches: editExcludeCaches,
compression: editCompression !== 'auto' ? editCompression : undefined,
limitUpload: editLimitUpload || undefined,
limitDownload: editLimitDownload || undefined,
webhookSuccess: editWebhookSuccess || undefined,
webhookFailure: editWebhookFailure || undefined
}
};
}
/**
* Pre-flight validation + delegation to runBackupAction. The shared helper
* does the heavy lifting (POST/PUT, optional /run, optional cleanup). All
* three submit buttons land here, then runBackupAction branches on action.
*
* Edit mode (editingConfig != null) only renders the 'save' button — the
* other actions don't apply to in-place edits.
*/
async function submitForm(action: BackupAction) {
if (!editDestinationId) { toast.error('Select a backup repository'); return; }
const selectedDest = destinations.find(d => d.id === editDestinationId);
if (selectedDest && isCurrentEnvRemote() && isLocalRepo(selectedDest.repository)) {
toast.error('Local repositories cannot be used with remote environments');
return;
}
// Cron only matters when the schedule will be persisted. run-once
// clears it server-side so the field value is irrelevant.
if ((action === 'save' || action === 'save-run') && editScheduleInvalid) {
toast.error('Schedule is invalid');
return;
}
submitAction = action;
saving = true;
// A run action (run-once / save-run) streams restic output into the progress
// modal. A plain save persists silently — no restic runs, so no log view.
const runsBackup = action === 'run-once' || action === 'save-run';
if (runsBackup) {
progressLogs = [];
progressError = '';
progressStatus = 'running';
progressDestId = editDestinationId;
progressConfigId = editingConfig?.id ?? null; // set precisely via onStarted
progressOpen = true;
}
try {
const result = await runBackupAction({
form: currentForm(),
action,
editingConfigId: editingConfig?.id ?? null,
schedule: editSchedule,
enabled: editEnabled,
onStarted: runsBackup ? (id) => (progressConfigId = id) : undefined,
onProgress: runsBackup ? (line) => {
const msg = (line.data as { message?: string } | null)?.message;
if (msg) progressLogs = [...progressLogs, tagLogLine(msg)];
} : undefined
});
if (!result.ok) {
if (runsBackup) { progressStatus = 'error'; progressError = result.error || 'Backup failed'; }
else toast.error(result.error || 'Backup failed');
return;
}
if (runsBackup) progressStatus = 'success';
if (action === 'save') toast.success(isNew ? 'Backup schedule added' : 'Backup schedule updated');
else toast.success(`Backup completed for ${containerName}`);
editingConfig = null; isNew = false;
fetchConfigs();
// 'save-run'/'run-once' just wrote a snapshot — reload the list so it appears
// without a manual refresh. A plain 'save' writes none, so skip it.
if (runsBackup) { void snapshotsPanel?.refresh(); void loadHistory(); }
onConfigSaved?.();
} finally {
saving = false;
submitAction = null;
}
}
async function deleteConfig(id: number) {
try {
const res = await fetch(`/api/backup/configs/${id}`, { method: 'DELETE' });
if (res.ok) {
toast.success('Backup schedule removed');
fetchConfigs();
onConfigSaved?.();
} else {
toast.error('Failed to delete');
}
} catch { toast.error('Failed to delete'); }
confirmDeleteId = null;
}
// Pause/resume a scheduled backup. A minimal PUT with only `enabled` is a
// partial update (updateBackupConfig skips undefined fields) and the endpoint
// re-registers or unregisters the croner job accordingly.
let togglingId = $state<number | null>(null);
async function togglePause(cfg: BackupConfig) {
togglingId = cfg.id;
try {
const res = await fetch(`/api/backup/configs/${cfg.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ enabled: !cfg.enabled })
});
if (res.ok) {
toast.success(cfg.enabled ? 'Schedule paused' : 'Schedule resumed');
fetchConfigs();
onConfigSaved?.();
} else {
toast.error('Failed to update schedule');
}
} catch { toast.error('Failed to update schedule'); }
togglingId = null;
}
async function runBackupNow(cfg: BackupConfig) {
runningBackup = cfg.id;
progressLogs = [];
progressError = '';
progressStatus = 'running';
progressDestId = cfg.destinationId;
progressConfigId = cfg.id;
progressOpen = true;
try {
const res = await fetch(`/api/backup/configs/${cfg.id}/run`, { method: 'POST' });
const data = await res.json();
if (data.jobId) {
const result = await watchJob(data.jobId, (line) => {
const msg = (line.data as { message?: string } | null)?.message;
if (msg) progressLogs = [...progressLogs, tagLogLine(msg)];
}) as any;
const { outcome, message } = classifyJobResult(result);
// 'skipped' (a concurrent op holds the lock, or a prune guard) is NOT a
// success — surface it as an error in the modal, matching the main
// backups page. Only 'success'/'warning' get the green result.
if (outcome === 'error' || outcome === 'skipped') {
progressStatus = 'error';
progressError = message || (outcome === 'skipped' ? 'Backup skipped' : 'Backup failed');
} else {
progressStatus = 'success';
}
if (outcome === 'skipped') toast.info(message || 'Backup skipped');
else if (outcome === 'warning') toast.warning(message || 'Backup completed with warnings');
fetchConfigs();
// A new snapshot was written (success/warning) — reload the list so it
// shows up without a manual refresh. Skipped = no snapshot, nothing to do.
if (outcome !== 'skipped') void snapshotsPanel?.refresh();
void loadHistory(); // a run (even failed/skipped) is a new history entry
} else { progressStatus = 'error'; progressError = data.error || 'Failed to start backup'; }
} catch { progressStatus = 'error'; progressError = 'Failed to start backup'; } finally { runningBackup = null; }
}
function cfgRetentionSummary(cfg: BackupConfig): string {
return getRetentionSummary(cfg.retention);
}
function volumeSummary(cfg: BackupConfig): string {
if (cfg.selectedVolumes === null) return `All volumes (${volumes.length})`;
const sel = typeof cfg.selectedVolumes === 'string' ? JSON.parse(cfg.selectedVolumes) : cfg.selectedVolumes;
return `${sel.length} of ${volumes.length} volumes`;
}
onMount(() => { fetchDestinations(); fetchConfigs(); });
</script>
<!-- Sub-tabs: Schedules (cheap) vs Snapshots. SnapshotsPanel is mounted as soon as
the Backups view opens (its per-repo listing loads IN THE BACKGROUND with a
spinner on the tab) and kept mounted when switching tabs, so re-opening the
Snapshots tab is instant (cached, no re-fetch — use the tab's refresh to reload). -->
<div class="mb-3 flex items-center gap-1 border-b">
<button
type="button"
class="relative -mb-px border-b-2 px-3 py-1.5 text-sm font-medium transition-colors {subTab === 'schedules' ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'}"
onclick={() => (subTab = 'schedules')}
>
Schedules{#if configs.length > 0}<span class="ml-1.5 rounded-full bg-primary/15 px-1.5 text-xs text-primary">{configs.length}</span>{/if}
</button>
<button
type="button"
class="relative -mb-px flex items-center border-b-2 px-3 py-1.5 text-sm font-medium transition-colors {subTab === 'snapshots' ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'}"
onclick={() => (subTab = 'snapshots')}
>
Snapshots{#if snapshotsLoading}<Loader2 class="ml-1.5 h-3.5 w-3.5 animate-spin text-primary" />{:else if snapshotCount !== null}<span class="ml-1.5 rounded-full bg-primary/15 px-1.5 text-xs text-primary">{snapshotCount}</span>{/if}
</button>
<button
type="button"
class="relative -mb-px flex items-center gap-1.5 border-b-2 px-3 py-1.5 text-sm font-medium transition-colors {subTab === 'history' ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'}"
onclick={() => (subTab = 'history')}
>
History
{#if historyLoading}<Loader2 class="h-3.5 w-3.5 animate-spin text-primary" />{:else if tally.ok > 0 || tally.failed > 0}
{#if tally.ok > 0}<span class="inline-flex items-center gap-0.5 rounded-full bg-emerald-500/15 px-1.5 text-xs font-medium text-emerald-500"><Check class="h-3 w-3" />{tally.ok}</span>{/if}
{#if tally.failed > 0}<span class="inline-flex items-center gap-0.5 rounded-full bg-red-500/15 px-1.5 text-xs font-semibold text-red-500"><X class="h-3 w-3" />{tally.failed}</span>{/if}
{/if}
</button>
</div>
<!-- Snapshots: always mounted (loads in background on open, cached across tab
switches), shown only when its tab is active. -->
<div class:hidden={subTab !== 'snapshots'}>
<SnapshotsPanel
bind:this={snapshotsPanel}
targetName={containerName} {type} {environmentId}
hasBackups={configs.length > 0}
configIds={configs.map((c) => c.id)}
onCount={(n) => (snapshotCount = n)}
onLoadingChange={(l) => (snapshotsLoading = l)}
/>
</div>
{#if subTab === 'snapshots'}
<!-- content rendered above (kept mounted) -->
{:else if subTab === 'history'}
<ExecutionHistoryList {executions} loading={historyLoading} onViewLog={viewExecutionLog} />
{:else if loading}
<div class="flex items-center justify-center py-8">
<Loader2 class="w-5 h-5 animate-spin text-muted-foreground" />
</div>
{:else}
<div class="space-y-3">
<!-- Existing schedules list -->
{#each configs as cfg}
{@const dest = destinations.find(d => d.id === cfg.destinationId)}
{@const Icon = dest ? getTypeIcon(dest.repository) : HardDrive}
<div class="border rounded-md px-3 py-1.5 flex items-center gap-3 {!cfg.enabled ? 'opacity-60' : ''}">
<div class="flex-1 min-w-0">
<div class="flex items-center gap-2">
<Icon class="w-3.5 h-3.5 text-primary/70 flex-shrink-0" />
<span class="text-sm font-medium truncate">{dest?.name || 'Unknown'}</span>
{#if !cfg.enabled}<Badge variant="secondary" class="text-xs">Paused</Badge>{/if}
</div>
<div class="text-xs text-muted-foreground flex items-center gap-1 mt-0.5">
<span>{cfg.schedule ? formatCron(cfg.schedule) : 'Manual'} · {volumeSummary(cfg)}{cfgRetentionSummary(cfg) ? ` · ${cfgRetentionSummary(cfg)}` : ''}</span>
{#if cfg.lastBackupAt}
<span>·</span>
{#if cfg.lastBackupStatus === 'success'}<CheckCircle class="w-2.5 h-2.5 text-green-500" />{:else if cfg.lastBackupStatus === 'failed' || cfg.lastBackupStatus === 'error'}<XCircle class="w-2.5 h-2.5 text-destructive" />{/if}
<span>{formatDateTime(cfg.lastBackupAt)}</span>
{/if}
</div>
</div>
<div class="flex items-center gap-0.5 flex-shrink-0">
{#if cfg.schedule}
<button type="button" class="p-1 rounded hover:bg-muted" onclick={() => togglePause(cfg)} disabled={togglingId === cfg.id} title={cfg.enabled ? 'Pause schedule' : 'Resume schedule'}>
{#if togglingId === cfg.id}<Loader2 class="w-3 h-3 animate-spin text-muted-foreground" />{:else if cfg.enabled}<Pause class="w-3 h-3 text-muted-foreground" />{:else}<RotateCwFadingClock class="w-3 h-3 text-muted-foreground" />{/if}
</button>
{/if}
<button type="button" class="p-1 rounded hover:bg-muted" onclick={() => runBackupNow(cfg)} disabled={runningBackup === cfg.id} title="Run now">
{#if runningBackup === cfg.id}<Loader2 class="w-3 h-3 animate-spin text-muted-foreground" />{:else}<Play class="w-3 h-3 text-muted-foreground" />{/if}
</button>
<button type="button" class="p-1 rounded hover:bg-muted" onclick={() => startEditConfig(cfg)} title="Edit">
<Pencil class="w-3 h-3 text-muted-foreground" />
</button>
<ConfirmPopover
open={confirmDeleteId === cfg.id}
action="Delete"
itemType="backup schedule"
itemName={dest?.name || ''}
title="Remove schedule"
position="left"
onConfirm={() => deleteConfig(cfg.id)}
onOpenChange={(open) => confirmDeleteId = open ? cfg.id : null}
>
{#snippet children({ open })}
<Trash2 class="w-3 h-3 {open ? 'text-destructive' : 'text-muted-foreground hover:text-destructive'}" />
{/snippet}
</ConfirmPopover>
</div>
</div>
{/each}
{#if configs.length === 0 && !isNew && !editingConfig}
<p class="text-xs text-muted-foreground py-4 text-center">No backup schedules configured for this {type}.</p>
{/if}
<!-- Edit/New form -->
{#if isNew || editingConfig}
<div class="border border-primary/30 rounded-md p-4 space-y-4 bg-muted/10">
<div class="flex items-center justify-between">
<span class="text-xs font-medium uppercase tracking-wide text-muted-foreground">{isNew ? 'New backup schedule' : 'Edit schedule'}</span>
<button type="button" class="p-1 rounded hover:bg-muted" onclick={cancelEdit}>
<X class="w-3.5 h-3.5 text-muted-foreground" />
</button>
</div>
<!-- Repository + Schedule -->
<div class="flex items-center gap-2">
<DestinationPicker
destinations={destinations}
bind:value={editDestinationId}
disableLocalForRemoteEnv={isCurrentEnvRemote()}
triggerClass="h-9 w-[220px] flex-shrink-0"
/>
<CronEditor bind:value={editSchedule} bind:invalid={editScheduleInvalid} />
</div>
<!-- Toggles -->
<div class="flex items-center gap-3 max-w-md">
<TogglePill bind:checked={editEnabled} />
<Label class="text-xs">Enabled</Label>
</div>
<div class="flex items-center gap-3 max-w-md">
<TogglePill bind:checked={editStopBefore} />
<Label class="text-xs">Stop {type} during backup</Label>
</div>
<!-- Volume picker (all-or-subset toggle + per-volume checkboxes) -->
<VolumePicker
volumes={volumes}
bind:allVolumes={editAllVolumes}
bind:selectedVolumes={editSelectedVolumes}
emptyLabel="No volumes detected on this {type}"
/>
<!-- Advanced -->
<button type="button" class="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground w-full" onclick={() => showAdvanced = !showAdvanced}>
<ChevronDown class="w-3.5 h-3.5 transition-transform {showAdvanced ? 'rotate-0' : '-rotate-90'}" />
Advanced
</button>
{#if showAdvanced}
<div class="space-y-3 pl-1">
<!-- Retention policy -->
<div class="space-y-1.5">
<Label class="text-xs font-medium">Retention policy</Label>
<p class="text-xs text-muted-foreground">Older snapshots are pruned after each backup. Set 0 to disable.</p>
<div class="grid grid-cols-5 gap-2">
<div class="space-y-0.5">
<label class="text-xs text-muted-foreground">Last</label>
<Input bind:value={editKeepLast} type="number" min="0" max="999" class="h-7 text-xs" />
</div>
<div class="space-y-0.5">
<label class="text-xs text-muted-foreground">Daily</label>
<Input bind:value={editKeepDaily} type="number" min="0" max="365" class="h-7 text-xs" />
</div>
<div class="space-y-0.5">
<label class="text-xs text-muted-foreground">Weekly</label>
<Input bind:value={editKeepWeekly} type="number" min="0" max="52" class="h-7 text-xs" />
</div>
<div class="space-y-0.5">
<label class="text-xs text-muted-foreground">Monthly</label>
<Input bind:value={editKeepMonthly} type="number" min="0" max="120" class="h-7 text-xs" />
</div>
<div class="space-y-0.5">
<label class="text-xs text-muted-foreground">Yearly</label>
<Input bind:value={editKeepYearly} type="number" min="0" max="100" class="h-7 text-xs" />
</div>
</div>
</div>
<!-- Exclude patterns -->
<div class="space-y-1">
<Label class="text-xs font-medium">Exclude patterns</Label>
<Input bind:value={editExclude} class="h-7 text-xs font-mono" placeholder="*.log, *.tmp, cache/" />
<p class="text-xs text-muted-foreground">Comma-separated glob patterns to exclude from backup.</p>
</div>
<!-- Exclude cache directories -->
<div class="space-y-1">
<div class="flex items-center gap-3">
<TogglePill bind:checked={editExcludeCaches} onLabel="Yes" offLabel="No" />
<Label class="text-xs font-medium">Skip cache directories</Label>
</div>
<p class="text-xs text-muted-foreground leading-snug">
Skips folders containing a <code class="font-mono text-xs">CACHEDIR.TAG</code> marker file
— used by npm, pip, Cargo, browsers, and many other tools to tag
regenerable cache content. Saves significant backup space; the contents
can always be rebuilt from source. Turn off only if you have a specific
reason to back up cache data.
</p>
</div>
<!-- Compression & bandwidth -->
<div class="grid grid-cols-3 gap-2">
<div class="space-y-1">
<Label class="text-xs font-medium">Compression</Label>
<Select.Root type="single" value={editCompression} onValueChange={(v) => { editCompression = v; }}>
<Select.Trigger class="h-9 w-full text-xs">{editCompression}</Select.Trigger>
<Select.Content>
<Select.Item value="auto">Auto</Select.Item>
<Select.Item value="off">Off</Select.Item>
<Select.Item value="max">Max</Select.Item>
</Select.Content>
</Select.Root>
</div>
<div class="space-y-1">
<Label class="text-xs font-medium">Upload limit</Label>
<Input bind:value={editLimitUpload} type="number" min="0" class="h-9 text-xs font-mono" placeholder="KiB/s" />
</div>
<div class="space-y-1">
<Label class="text-xs font-medium">Download limit</Label>
<Input bind:value={editLimitDownload} type="number" min="0" class="h-9 text-xs font-mono" placeholder="KiB/s" />
</div>
</div>
<!-- Webhook hooks -->
<div class="space-y-1.5">
<Label class="text-xs font-medium">Webhook hooks</Label>
<div class="space-y-1">
<label class="text-xs text-muted-foreground">On success</label>
<Input bind:value={editWebhookSuccess} class="h-7 text-xs font-mono" placeholder="https://healthchecks.io/ping/..." />
</div>
<div class="space-y-1">
<label class="text-xs text-muted-foreground">On failure</label>
<Input bind:value={editWebhookFailure} class="h-7 text-xs font-mono" placeholder="https://hooks.slack.com/..." />
</div>
<p class="text-xs text-muted-foreground">POST with a JSON payload sent after backup completes (falls back to GET for simple receivers). Use for healthchecks, Slack, etc.</p>
</div>
</div>
{/if}
<!-- Submit actions. Editing existing config: just "Save".
Creating a new config: three actions, all use the same form
state (destination, schedule, volumes, retention, options) —
they only differ in what happens after persistence. -->
<div class="flex justify-end gap-2 pt-2 border-t">
<Button size="sm" variant="outline" onclick={cancelEdit}>Cancel</Button>
{#if editingConfig}
<Button size="sm" onclick={() => submitForm('save')} disabled={saving || editScheduleInvalid}>
{#if saving}<Loader2 class="w-3.5 h-3.5 mr-1 animate-spin" />{:else}<Save class="w-3.5 h-3.5 mr-1" />{/if}
Save
</Button>
{:else}
<Button size="sm" variant="outline" onclick={() => submitForm('run-once')} disabled={saving || !editDestinationId} title="Run a backup now, don't save a schedule">
{#if saving && submitAction === 'run-once'}<Loader2 class="w-3.5 h-3.5 mr-1 animate-spin" />{:else}<Play class="w-3.5 h-3.5 mr-1" />{/if}
Run once
</Button>
<Button size="sm" variant="outline" onclick={() => submitForm('save')} disabled={saving || editScheduleInvalid || !editDestinationId}>
{#if saving && submitAction === 'save'}<Loader2 class="w-3.5 h-3.5 mr-1 animate-spin" />{:else}<Save class="w-3.5 h-3.5 mr-1" />{/if}
Save schedule
</Button>
<Button size="sm" onclick={() => submitForm('save-run')} disabled={saving || editScheduleInvalid || !editDestinationId} title="Save the schedule and run a backup immediately">
{#if saving && submitAction === 'save-run'}<Loader2 class="w-3.5 h-3.5 mr-1 animate-spin" />{:else}<Play class="w-3.5 h-3.5 mr-1" />{/if}
Save & run now
</Button>
{/if}
</div>
</div>
{/if}
<!-- "Add schedule" trigger when there's already at least one config -->
{#if configs.length > 0 && !isNew && !editingConfig}
<Button size="sm" variant="ghost" class="w-full text-muted-foreground" onclick={startNewConfig}>
<Plus class="w-3.5 h-3.5 mr-1" />
Add another schedule
</Button>
{/if}
<!-- Empty-state trigger when there are no configs yet -->
{#if configs.length === 0 && !isNew && !editingConfig}
<Button size="sm" variant="outline" class="w-full" onclick={startNewConfig}>
<Plus class="w-3.5 h-3.5 mr-1" />
Configure a backup
</Button>
{/if}
</div>
{/if}
<!-- Manual-backup progress: restic output streamed live. Not dismissible mid-run;
the user closes it once the backup finishes (or fails). -->
<Dialog.Root bind:open={progressOpen}>
<Dialog.Content class="max-w-5xl flex flex-col overflow-hidden top-[6vh] translate-y-0 h-[85vh]" interactOutsideBehavior={progressStatus === 'running' ? 'ignore' : 'close'} escapeKeydownBehavior={progressStatus === 'running' ? 'ignore' : 'close'}>
<Dialog.Header>
<Dialog.Title class="flex flex-wrap items-center gap-x-2 gap-y-1 text-base">
<TypeIcon class="h-4 w-4 text-muted-foreground" />
<span>{containerName}</span>
{#if progressEnv}
<span class="text-sm font-normal text-muted-foreground">on</span>
<span class="flex items-center gap-1 text-sm font-medium text-amber-500"><EnvironmentIcon icon={progressEnv.icon || 'globe'} envId={progressEnv.id} class="h-3.5 w-3.5" />{progressEnv.name}</span>
{/if}
{#if progressDest}
<span class="text-sm font-normal text-muted-foreground">→</span>
{@const RepoIcon = getRepoTypeIcon(progressDest.repository)}
<span class="flex items-center gap-1.5 rounded-md border bg-muted/40 px-2 py-0.5 text-xs font-normal"><RepoIcon class="h-3.5 w-3.5 text-primary/70" />{progressDest.name}</span>
{/if}
</Dialog.Title>
<Dialog.Description class="sr-only">Live backup progress for {containerName}.</Dialog.Description>
</Dialog.Header>
<!-- flex-1 + fixed dialog height: the log fills the space and SCROLLS internally,
so the dialog never grows/jumps as lines stream in. -->
<LogConsole lines={progressLogs} class="flex-1 min-h-0" />
<div class="flex shrink-0 items-center gap-1.5 text-sm">
{#if progressStatus === 'running'}
<Loader2 class="h-4 w-4 animate-spin text-muted-foreground" /><span class="text-muted-foreground">Backing up…</span>
{:else if progressStatus === 'success'}
<CheckCircle class="h-4 w-4 text-green-500" /><span class="text-green-500">Backup completed</span>
{:else}
<XCircle class="h-4 w-4 text-destructive" /><span class="text-destructive">{progressError || 'Backup failed'}</span>
{/if}
</div>
<Dialog.Footer>
{#if progressStatus === 'running'}
<Button size="sm" variant="destructive" disabled={cancelling || progressConfigId == null} onclick={cancelRunningBackup}>
{#if cancelling}<Loader2 class="mr-1 h-3.5 w-3.5 animate-spin" />Cancelling…{:else}<X class="mr-1 h-3.5 w-3.5" />Cancel backup{/if}
</Button>
{:else}
<Button size="sm" onclick={() => (progressOpen = false)}>OK</Button>
{/if}
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>
<!-- Backup-run log viewer, opened from the History table's log button -->
<Dialog.Root bind:open={logDialogOpen}>
<Dialog.Content class="max-w-4xl h-[80vh] overflow-hidden flex flex-col">
<Dialog.Header>
<Dialog.Title class="flex items-center gap-2 text-base"><FileText class="h-4 w-4" />Backup log</Dialog.Title>
</Dialog.Header>
<div class="flex-1 flex flex-col min-h-0">
{#if logDialogLoading}
<div class="flex items-center justify-center py-8 gap-2 text-muted-foreground">
<Loader2 class="h-4 w-4 animate-spin" />
<span class="text-sm">Loading log…</span>
</div>
{:else if logDialogContent}
<ExecutionLogViewer logs={logDialogContent} />
{:else}
<p class="py-8 text-center text-sm text-muted-foreground">No log output was recorded for this run.</p>
{/if}
</div>
</Dialog.Content>
</Dialog.Root>
@@ -5,7 +5,7 @@
import * as Tabs from '$lib/components/ui/tabs';
import { Button } from '$lib/components/ui/button';
import { Badge } from '$lib/components/ui/badge';
import { Loader2, Box, Info, Layers, Cpu, MemoryStick, HardDrive, Network, Shield, Settings2, Code, Copy, Check, XCircle, Activity, Wifi, Pencil, RefreshCw, X, FolderOpen, Moon, Tags, ExternalLink, Gpu, Globe, Link, Unlink, Play, Square as SquareIcon, RotateCw, Trash2 } from 'lucide-svelte';
import { Loader2, Box, Info, Layers, Cpu, MemoryStick, HardDrive, Network, Shield, Settings2, Code, Copy, Check, XCircle, Activity, Wifi, Pencil, RefreshCw, X, Folder, FolderOpen, Moon, Tags, ExternalLink, Gpu, Globe, Link, Unlink, Play, Square as SquareIcon, RotateCw, Trash2 } from 'lucide-svelte';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import * as Select from '$lib/components/ui/select';
import { toast } from 'svelte-sonner';
@@ -677,7 +677,7 @@
<X class="w-3.5 h-3.5 text-muted-foreground hover:text-foreground" />
</button>
{:else}
<span class="text-muted-foreground font-normal">{displayName || containerId.slice(0, 12)}</span>
<span class="font-semibold">{displayName || containerId.slice(0, 12)}</span>
<button
type="button"
onclick={startEditing}
@@ -687,6 +687,9 @@
<Pencil class="w-3 h-3 text-muted-foreground hover:text-foreground" />
</button>
{/if}
{#if $currentEnvironment}
<span class="font-semibold">on <span class="text-amber-600 dark:text-amber-400">{$currentEnvironment.name}</span></span>
{/if}
{@const composeStack = containerData?.Config?.Labels?.['com.docker.compose.project']}
{#if composeStack && !loading}
<Tooltip.Root>
@@ -1336,7 +1339,15 @@
{#each containerData.Mounts as mount}
<div class="p-3 border border-border rounded-lg space-y-2">
<div class="flex items-center justify-between">
<Badge variant="outline" class="text-xs">{mount.Type}</Badge>
<!-- Typed mount chip, consistent with the backup picker/log (amber Folder
for bind, sky HardDrive for volume). -->
{#if mount.Type === 'bind'}
<span class="inline-flex items-center gap-1 rounded-full bg-amber-500/15 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-amber-600 dark:text-amber-400"><Folder class="h-3 w-3" />bind</span>
{:else if mount.Type === 'volume'}
<span class="inline-flex items-center gap-1 rounded-full bg-sky-500/15 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-sky-600 dark:text-sky-400"><HardDrive class="h-3 w-3" />volume</span>
{:else}
<Badge variant="outline" class="text-xs">{mount.Type}</Badge>
{/if}
<Badge variant={mount.RW ? 'default' : 'secondary'} class="text-xs">
{mount.RW ? 'Read/Write' : 'Read-Only'}
</Badge>
@@ -1399,7 +1410,7 @@
<div class="min-w-0">
{containerData.divergence.env.length} env var{containerData.divergence.env.length === 1 ? '' : 's'} differ from the image:
<span class="font-mono">{containerData.divergence.env.join(', ')}</span>.
Values set by you at create time will stay. To reset to the image's current values, Remove &amp; Deploy.
On the next update, image-provided values you haven't overridden are refreshed to the new image; values you set yourself are kept. Use Remove &amp; Deploy to reset everything to the image.
</div>
</div>
{/if}
@@ -1429,7 +1440,7 @@
<div class="min-w-0">
{containerData.divergence.labels.length} label{containerData.divergence.labels.length === 1 ? '' : 's'} differ from the image:
<span class="font-mono">{containerData.divergence.labels.join(', ')}</span>.
Values set by you at create time will stay. To reset to the image's current values, Remove &amp; Deploy.
On the next update, image-provided values you haven't overridden are refreshed to the new image; values you set yourself are kept. Use Remove &amp; Deploy to reset everything to the image.
</div>
</div>
{/if}
@@ -14,37 +14,7 @@
import type { VulnerabilityCriteria } from '$lib/components/VulnerabilityCriteriaSelector.svelte';
// Parse shell command respecting quotes
function parseShellCommand(cmd: string): string[] {
const args: string[] = [];
let current = '';
let inQuotes = false;
let quoteChar = '';
for (let i = 0; i < cmd.length; i++) {
const char = cmd[i];
if ((char === '"' || char === "'") && !inQuotes) {
inQuotes = true;
quoteChar = char;
} else if (char === quoteChar && inQuotes) {
inQuotes = false;
quoteChar = '';
} else if (char === ' ' && !inQuotes) {
if (current) {
args.push(current);
current = '';
}
} else {
current += char;
}
}
if (current) {
args.push(current);
}
return args;
}
import { parseShellCommand } from '$lib/utils/shell';
interface ConfigSet {
id: number;
@@ -608,7 +578,7 @@
<Dialog.Title class="text-base font-semibold">
Create new container
{#if $currentEnvironment}
<span class="font-medium">on <span class="text-amber-600 dark:text-amber-400">{$currentEnvironment.name}</span></span>
<span class="font-semibold">on <span class="text-amber-600 dark:text-amber-400">{$currentEnvironment.name}</span></span>
{/if}
</Dialog.Title>
<button
+135 -5
View File
@@ -1,10 +1,14 @@
<script lang="ts">
import * as Dialog from '$lib/components/ui/dialog';
import { Button } from '$lib/components/ui/button';
import { Pencil, Check, Loader2, X, Layers } from 'lucide-svelte';
import { Pencil, Check, Loader2, X, Layers, Settings, Archive } from 'lucide-svelte';
import { currentEnvironment, appendEnvParam } from '$lib/stores/environment';
import { page } from '$app/stores'; // BETA GATE: backups feature flag
import { focusFirstInput } from '$lib/utils';
import ContainerSettingsTab from './ContainerSettingsTab.svelte';
import BackupPanel from './BackupPanel.svelte';
import { mountTypeFromHostPath } from '$lib/utils/mounts';
import { fetchBackupExecutions } from '$lib/utils/backup';
import type { VulnerabilityCriteria } from '$lib/components/VulnerabilityCriteriaSelector.svelte';
import { parseHostPort, expandPortBindings, formatHostPort } from '$lib/utils/port-parse';
import { formatBytes } from '$lib/utils/format';
@@ -228,7 +232,16 @@
let loading = $state(false);
let loadingData = $state(true);
let error = $state('');
let activeTab = $state<'settings' | 'backups'>('settings');
let backupCount = $state(0);
// Ok/fail run tally, reported by BackupPanel — shown on the Backups tab so a
// failed backup is visible without opening the tab.
let backupTally = $state<{ ok: number; failed: number }>({ ok: 0, failed: 0 });
let abortController: AbortController | null = null;
// Unsaved-changes guard on close (mirrors StackModal): settings changes OR a
// half-edited backup schedule in the embedded panel.
let showConfirmClose = $state(false);
let backupPanelRef = $state<BackupPanel | undefined>(undefined);
let statusMessage = $state('');
let visible = $state(false);
@@ -598,6 +611,25 @@
error = 'Failed to load container data: ' + String(err);
} finally {
loadingData = false;
// Fetch backup schedule count (BETA GATE: only when backups enabled)
if ($page.data.backupsEnabled) try {
const envId = $currentEnvironment?.id;
const bp = new URLSearchParams({ target: name, type: 'container' });
if (envId) bp.set('env', String(envId));
const bRes = await fetch(`/api/backup/configs?${bp}`);
if (bRes.ok) {
const bData = await bRes.json();
const cfgs = Array.isArray(bData) ? bData : bData?.id ? [bData] : [];
backupCount = cfgs.length;
// Compute the run tally at modal level (not from BackupPanel, which
// only mounts when the Backups tab is open) so the fail count shows
// on the tab immediately.
if (cfgs.length > 0) {
const t = await fetchBackupExecutions(cfgs.map((c: any) => c.id));
backupTally = { ok: t.ok, failed: t.failed };
}
}
} catch {}
requestAnimationFrame(() => {
visible = true;
focusFirstInput();
@@ -1018,9 +1050,34 @@
abortController = null;
}
loading = false;
showConfirmClose = false;
onClose();
}
/** True if closing now would lose unsaved work: container settings changed, OR the
* embedded backup panel has a half-edited schedule. Guarded on `originalConfig`
* (the loaded baseline) — while the container config is still loading it is null,
* and hasContainerConfigChanged() returns true for a null baseline, which would
* falsely block a close during load. No baseline yet ⇒ nothing to lose. */
function hasUnsavedChanges(): boolean {
if (!originalConfig) return false;
return hasContainerConfigChanged() || (backupPanelRef?.isDirty() ?? false);
}
/** Intercept a close request: confirm first if there are unsaved changes. */
function tryClose() {
if (hasUnsavedChanges()) {
showConfirmClose = true;
} else {
handleClose();
}
}
function discardAndClose() {
showConfirmClose = false;
handleClose();
}
$effect(() => {
if (open && containerId && !hasLoadedData) {
visible = false;
@@ -1040,8 +1097,21 @@
});
</script>
<Dialog.Root bind:open onOpenChange={(isOpen) => isOpen && focusFirstInput()}>
<Dialog.Content class="max-w-4xl w-full max-h-[90vh] p-0 flex flex-col overflow-hidden sm:max-h-[85vh]">
<Dialog.Root
bind:open
onOpenChange={(isOpen) => {
if (isOpen) {
focusFirstInput();
} else if (hasUnsavedChanges()) {
// Re-open and show the confirmation instead of closing on unsaved changes.
open = true;
showConfirmClose = true;
} else {
handleClose();
}
}}
>
<Dialog.Content class="max-w-4xl w-full h-[85vh] p-0 flex flex-col overflow-hidden">
<Dialog.Header class="px-5 py-4 border-b bg-muted/30 shrink-0 sticky top-0 z-10">
<Dialog.Title class="text-base font-semibold flex items-center gap-1">
Edit container
@@ -1074,7 +1144,8 @@
<X class="w-3 h-3 text-muted-foreground hover:text-foreground" />
</button>
{:else if name}
<span class="font-normal text-muted-foreground ml-1">- {name}</span>
<span class="text-muted-foreground ml-1">-</span>
<span class="font-semibold">{name}</span>
<button
type="button"
onclick={startEditingTitle}
@@ -1083,6 +1154,9 @@
>
<Pencil class="w-3 h-3 text-muted-foreground hover:text-foreground" />
</button>
{#if $currentEnvironment}
<span class="font-semibold ml-1">on <span class="text-amber-600 dark:text-amber-400">{$currentEnvironment.name}</span></span>
{/if}
{/if}
</Dialog.Title>
</Dialog.Header>
@@ -1093,7 +1167,42 @@
Loading container data...
</div>
{:else}
<div class="px-5 py-4 flex-1 overflow-y-auto">
<div class="px-5 flex gap-1 border-b shrink-0">
<button
type="button"
class="flex items-center gap-1.5 px-3 py-2 text-sm transition-colors border-b-2 -mb-px {activeTab === 'settings' ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'}"
onclick={() => activeTab = 'settings'}
>
<Settings class="w-3.5 h-3.5" />
Settings
</button>
<!-- BETA GATE: Backups tab hidden unless FEAT_BACKUPS_ENABLED (see features.ts) -->
{#if $page.data.backupsEnabled}
<button
type="button"
class="flex items-center gap-1.5 px-3 py-2 text-sm transition-colors border-b-2 -mb-px {activeTab === 'backups' ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'}"
onclick={() => activeTab = 'backups'}
>
<Archive class="w-3.5 h-3.5" />
Backups
{#if backupCount > 0}<span class="bg-primary/15 text-primary text-[10px] px-1.5 rounded-full font-medium">{backupCount}</span>{/if}
<!-- Run tally so a failed backup is visible before opening the tab. -->
{#if backupTally.ok > 0}<span class="inline-flex items-center gap-0.5 rounded-full bg-emerald-500/15 px-1.5 text-[10px] font-medium text-emerald-500"><Check class="w-2.5 h-2.5" />{backupTally.ok}</span>{/if}
{#if backupTally.failed > 0}<span class="inline-flex items-center gap-0.5 rounded-full bg-red-500/15 px-1.5 text-[10px] font-semibold text-red-500"><X class="w-2.5 h-2.5" />{backupTally.failed}</span>{/if}
</button>
{/if}
</div>
<div class="px-5 py-4 flex-1 overflow-y-auto h-0">
{#if activeTab === 'backups'}
<BackupPanel
bind:this={backupPanelRef}
containerName={name}
volumes={volumeMappings.filter(v => v.hostPath && v.containerPath).map(v => ({ name: v.containerPath, mountPoint: v.hostPath, mountType: mountTypeFromHostPath(v.hostPath) }))}
type="container"
onTally={(t) => (backupTally = t)}
/>
{:else}
<!-- Compose warning banners -->
{#if showComposeRenameWarning}
<div class="mb-4 px-3 py-2 text-xs text-amber-700 dark:text-amber-300 bg-amber-100/50 dark:bg-amber-900/30 rounded-md flex items-start gap-2">
@@ -1175,6 +1284,7 @@
{error}
</div>
{/if}
{/if}
</div>
<div class="flex justify-end gap-2 px-5 py-3 border-t bg-muted/30 shrink-0">
@@ -1193,3 +1303,23 @@
{/if}
</Dialog.Content>
</Dialog.Root>
<!-- Unsaved changes confirmation dialog -->
<Dialog.Root bind:open={showConfirmClose}>
<Dialog.Content class="max-w-sm">
<Dialog.Header>
<Dialog.Title>Unsaved changes</Dialog.Title>
<Dialog.Description>
You have unsaved changes. Are you sure you want to close without saving?
</Dialog.Description>
</Dialog.Header>
<div class="flex justify-end gap-1.5 mt-4">
<Button variant="outline" size="sm" onclick={() => showConfirmClose = false}>
Continue editing
</Button>
<Button variant="destructive" size="sm" onclick={discardAndClose}>
Discard changes
</Button>
</div>
</Dialog.Content>
</Dialog.Root>
@@ -2,6 +2,7 @@
import * as Dialog from '$lib/components/ui/dialog';
import { FolderOpen } from 'lucide-svelte';
import FileBrowserPanel from './FileBrowserPanel.svelte';
import ModalHeader from '$lib/components/ModalHeader.svelte';
import { canAccess } from '$lib/stores/auth';
interface Props {
@@ -22,12 +23,9 @@
</script>
<Dialog.Root bind:open onOpenChange={handleOpenChange}>
<Dialog.Content class="max-w-4xl h-[90vh] sm:h-[80vh] flex flex-col">
<Dialog.Content class="max-w-4xl h-[90vh] sm:h-[80vh] flex flex-col" onOpenAutoFocus={(e) => e.preventDefault()}>
<Dialog.Header>
<Dialog.Title class="flex items-center gap-2">
<FolderOpen class="w-5 h-5" />
<span>Browse files - {containerName}</span>
</Dialog.Title>
<ModalHeader icon={FolderOpen} title="Browse files" name={containerName} />
<Dialog.Description>
Browse, upload, and download files from the container filesystem.
</Dialog.Description>
+82 -23
View File
@@ -52,7 +52,7 @@
readonly?: boolean;
}
type BrowserMode = 'container' | 'volume';
type BrowserMode = 'container' | 'volume' | 'snapshot';
type SortField = 'name' | 'size' | 'modified' | 'type';
type SortDirection = 'asc' | 'desc';
@@ -75,6 +75,9 @@
selectFilter?: RegExp;
// Callback when a file is selected (in selectMode)
onFileSelect?: (path: string, name: string) => void;
// Snapshot browsing mode
snapshotId?: string;
destinationId?: number;
}
let {
@@ -86,7 +89,9 @@
onUsageChange,
selectMode = false,
selectFilter,
onFileSelect
onFileSelect,
snapshotId,
destinationId
}: Props = $props();
// For volume mode, track whether volume is in use (controls editing ability)
@@ -96,12 +101,13 @@
let volumeHelperId = $state<string | null>(null);
// Determine mode based on which prop is provided
const mode: BrowserMode = $derived(volumeName ? 'volume' : 'container');
const mode: BrowserMode = $derived(snapshotId ? 'snapshot' : volumeName ? 'volume' : 'container');
const isVolumeMode = $derived(mode === 'volume');
const isSnapshotMode = $derived(mode === 'snapshot');
// Effective canEdit: for containers, use the prop; for volumes, only allow if not in use
// Effective canEdit: snapshots are always read-only; volumes only if not in use
const effectiveCanEdit = $derived(
isVolumeMode ? (canEdit && !volumeIsInUse) : canEdit
isSnapshotMode ? false : isVolumeMode ? (canEdit && !volumeIsInUse) : canEdit
);
// Effective container ID for file operations (use helper container for volume mode)
@@ -145,6 +151,11 @@
// Editor/Viewer state
let editingFile = $state<{ name: string; path: string; content: string } | null>(null);
let viewingFile = $state<{ name: string; path: string; content: string } | null>(null);
// Preview-only loading flag (distinct from loadingFile, which also covers
// edit/download): drives the "Loading preview…" overlay so a slow restic dump
// from a remote repo (B2/S3) shows immediate feedback in-place.
let loadingPreview = $state(false);
let previewingName = $state('');
let editorContent = $state('');
let loadingFile = $state(false);
// True when the editor buffer differs from the loaded file (unsaved changes).
@@ -368,16 +379,22 @@
async function openFileForView(entry: FileEntry) {
const filePath = currentPath === '/' ? `/${entry.name}` : `${currentPath}/${entry.name}`;
loadingFile = true;
loadingPreview = true;
previewingName = entry.name;
try {
const params = new URLSearchParams({ path: filePath });
if (envId) params.set('env', envId.toString());
let res: Response;
if (isVolumeMode) {
res = await fetch(`/api/volumes/${encodeURIComponent(volumeName!)}/browse/content?${params}`);
if (isSnapshotMode) {
const params = new URLSearchParams({ destinationId: String(destinationId), path: filePath });
res = await fetch(`/api/backup/snapshots/${snapshotId}/dump?${params}`);
} else {
res = await fetch(`/api/containers/${effectiveContainerId}/files/content?${params}`);
const params = new URLSearchParams({ path: filePath });
if (envId) params.set('env', envId.toString());
if (isVolumeMode) {
res = await fetch(`/api/volumes/${encodeURIComponent(volumeName!)}/browse/content?${params}`);
} else {
res = await fetch(`/api/containers/${effectiveContainerId}/files/content?${params}`);
}
}
const data = await res.json();
@@ -394,6 +411,7 @@
toast.error(err.message || 'Failed to open file');
} finally {
loadingFile = false;
loadingPreview = false;
}
}
@@ -704,7 +722,11 @@
let res: Response;
let data: any;
if (isVolumeMode) {
if (isSnapshotMode) {
const snapshotParams = new URLSearchParams({ destinationId: String(destinationId), path });
res = await fetch(`/api/backup/snapshots/${snapshotId}/browse?${snapshotParams}`);
data = await res.json();
} else if (isVolumeMode) {
res = await fetch(`/api/volumes/${encodeURIComponent(volumeName!)}/browse?${params}`);
data = await res.json();
@@ -738,7 +760,20 @@
}
currentPath = data.path || path;
entries = data.entries || [];
// Map snapshot entries to match FileEntry interface
if (isSnapshotMode) {
entries = (data.entries || []).map((e: any) => ({
name: e.name,
type: e.type === 'dir' ? 'directory' : e.type,
size: e.size || 0,
permissions: '',
owner: '',
group: '',
modified: e.mtime || ''
}));
} else {
entries = data.entries || [];
}
} catch (err: any) {
error = err.message;
entries = [];
@@ -778,17 +813,20 @@
function downloadFile(entry: FileEntry) {
const filePath =
currentPath === '/' ? `/${entry.name}` : `${currentPath}/${entry.name}`;
const params = new URLSearchParams({
path: filePath,
format: $appSettings.downloadFormat
});
if (envId) params.set('env', envId.toString());
let url: string;
if (isVolumeMode) {
url = `/api/volumes/${encodeURIComponent(volumeName!)}/export?${params}`;
if (isSnapshotMode) {
const params = new URLSearchParams({ destinationId: String(destinationId), path: filePath, download: '1' });
if (entry.type === 'directory') params.set('type', 'directory');
url = `/api/backup/snapshots/${snapshotId}/dump?${params}`;
} else {
url = `/api/containers/${effectiveContainerId}/files/download?${params}`;
const params = new URLSearchParams({ path: filePath, format: $appSettings.downloadFormat });
if (envId) params.set('env', envId.toString());
if (isVolumeMode) {
url = `/api/volumes/${encodeURIComponent(volumeName!)}/export?${params}`;
} else {
url = `/api/containers/${effectiveContainerId}/files/download?${params}`;
}
}
window.open(url, '_blank');
}
@@ -841,8 +879,24 @@
return currentPath.split('/').filter(Boolean);
});
// Track all identity props so the effect re-fires when they change
$effect(() => {
loadDirectory(initialPath);
// Read reactive values to establish dependencies
const _mode = mode;
const _snap = snapshotId;
const _dest = destinationId;
const _cont = containerId;
const _vol = volumeName;
const _path = initialPath;
// Guard: don't load if required props for the mode are missing
if (_mode === 'snapshot' && (!_snap || !_dest)) return;
if (_mode === 'container' && !_cont) return;
currentPath = _path;
entries = [];
error = null;
loadDirectory(_path);
});
</script>
@@ -1195,7 +1249,12 @@
</Dialog.Root>
<!-- File Viewer Overlay -->
{#if viewingFile}
{#if loadingPreview && !viewingFile}
<div class="absolute inset-0 bg-background flex flex-col items-center justify-center gap-2 z-10">
<Loader2 class="w-6 h-6 animate-spin text-muted-foreground" />
<span class="text-sm text-muted-foreground">Loading preview{previewingName ? ` — ${previewingName}` : ''}…</span>
</div>
{:else if viewingFile}
<div class="absolute inset-0 bg-background flex flex-col z-10">
<div class="flex items-center justify-between p-2 border-b bg-muted/30">
<div class="flex items-center gap-2 text-xs">
+756
View File
@@ -0,0 +1,756 @@
<script lang="ts">
import * as Dialog from '$lib/components/ui/dialog';
import * as Select from '$lib/components/ui/select';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { Checkbox } from '$lib/components/ui/checkbox';
import { Label } from '$lib/components/ui/label';
import { Badge } from '$lib/components/ui/badge';
import { RotateCcw, AlertTriangle, Loader2, HardDrive, Folder, Clock, Play, CheckCircle2, XCircle, Server, PackagePlus, Ban, Rocket, Box, Layers, HelpCircle, Info } from 'lucide-svelte';
import * as Tooltip from '$lib/components/ui/tooltip';
import { toast } from 'svelte-sonner';
import { watchJob } from '$lib/utils/sse-fetch';
import { environments } from '$lib/stores/environment';
import { formatDateTime } from '$lib/stores/settings';
import EnvironmentIcon from '$lib/components/EnvironmentIcon.svelte';
import LogConsole from '$lib/components/LogConsole.svelte';
import { tagLogLine, classifyJobResult } from '$lib/utils/backup';
interface Props {
open: boolean;
destinationId: number;
snapshotId: string;
containerName: string;
environmentId?: number;
/** Refresh callback fired once the restore succeeds — the caller reloads its
* snapshot list. This modal is ALWAYS self-contained (form → log → result in
* one dialog); it never delegates its progress UI to a parent. */
onDone?: () => void;
}
let { open = $bindable(), destinationId, snapshotId, containerName, environmentId, onDone }: Props = $props();
// The two restore modes, framed by DESTINATION intent (not safe-vs-destructive):
// - 'new-location' ("Restore to environment"): pick a target env and, per
// volume, a DESTINATION. A destination pointing at a named volume / host path
// the container mounts + a start action = a working CLONE; a plain extract
// path = today's safe inspect-to-a-folder. Cross-env.
// - 'in-place' ("Overwrite live"): overwrite the live volumes on the SOURCE env.
type RestoreMode = 'new-location' | 'in-place';
let loading = $state(false);
let restoring = $state(false);
let error = $state('');
let restoreStatus = $state<'idle' | 'running' | 'success' | 'warning' | 'error'>('idle');
let restoreLogs = $state<string[]>([]);
// Non-fatal caveat shown on the 'warning' result (e.g. data restored but the
// post-restore recreate/redeploy failed — the operator finishes manually).
let restoreWarning = $state('');
// After the restore, what to do with the target.
type PostRestore = 'start' | 'recreate' | 'redeploy' | 'none';
// One row per volume. `dest`/`destKind` are the editable clone destination on
// the target env (pre-filled 1:1 from the snapshot's original location). `type`
// is the ORIGINAL kind (for the badge). `conflict` is set when a named-volume
// destination already exists on the target env (fail-closed — must be resolved).
interface VolRow {
name: string;
selected: boolean;
type: 'volume' | 'bind';
dest: string;
destKind: 'volume' | 'path';
/** The snapshot's ORIGINAL destination + kind (the 1:1 pre-fill), kept so we
* can detect when the user redirects a volume to a new name/type — which the
* recreate/redeploy won't follow (it uses the stored config). */
origDest: string;
origDestKind: 'volume' | 'path';
conflict: boolean;
/** A host-path destination that isn't a valid absolute path (empty, no
* leading '/', or contains '..') — mirrors the server-side validation so the
* restore is blocked before submit with an inline hint. */
pathInvalid: boolean;
}
let mode = $state<RestoreMode>('new-location');
let volumes = $state<VolRow[]>([]);
let hasMetadata = $state(false);
let hasStackFiles = $state(false);
let backupTime = $state<string | null>(null);
let targetPath = $state('/restore');
let confirmOverwrite = $state(false);
let postRestore = $state<PostRestore>('recreate');
// Set once the user picks a post-restore action by hand, so the auto "→ none on
// remap" doesn't override a deliberate choice (they may know their config matches).
let postRestoreUserPicked = $state(false);
let targetEnvId = $state<number | undefined>(undefined);
// The snapshot's SOURCE env for in-place. Seeded from the environmentId prop, but
// the prop can be empty (a config with no env, or an orphan snapshot restored from
// the list) — in that case we recover it from the snapshot metadata on preview, so
// in-place still knows which env holds the live target (otherwise the button stays
// disabled and the header shows "on " with no name).
let sourceEnvId = $state<number | undefined>(undefined);
// Volume names that already exist on the chosen target env (for conflict marks).
let existingTargetVolumes = $state<string[]>([]);
// Target-NAME collision: a container/stack of the restore's name already exists
// on the chosen target env. Mirrors the server's fail-closed check so the user
// sees it before submitting. Only blocks when a bring-up action is selected.
let nameExistsOnTarget = $state(false);
const envList = $derived($environments ?? []);
const effectiveEnvId = $derived(mode === 'in-place' ? sourceEnvId : targetEnvId);
const targetIsStack = $derived(hasStackFiles);
// After-restore action options. For a clone, 'start' is not offered (there's no
// live container to start — the target is created); 'recreate'/'redeploy' build it.
const postRestoreOptions = $derived([
...(mode === 'in-place' ? [{ value: 'start', label: targetIsStack ? 'Start stack' : 'Start container', icon: Play }] : []),
{ value: 'recreate', label: targetIsStack ? 'Recreate if missing' : 'Recreate container', icon: PackagePlus },
...(targetIsStack ? [{ value: 'redeploy', label: 'Redeploy stack', icon: Rocket }] : []),
{ value: 'none', label: 'Do nothing', icon: Ban }
]);
const targetEnv = $derived(envList.find((e) => e.id === effectiveEnvId));
const targetEnvName = $derived(targetEnv?.name ?? '');
// The snapshot's source env (for the "from <env>" phrasing in the summary).
const sourceEnv = $derived(envList.find((e) => e.id === sourceEnvId));
const sourceEnvName = $derived(sourceEnv?.name ?? '');
const postRestoreLabel = $derived(postRestoreOptions.find((o) => o.value === postRestore)?.label ?? '');
// Step-rail styling: always neutral (primary). Only the What-will-happen box
// turns red on the destructive (in-place) path — the rail/numbers stay calm.
// z-10 + solid dialog bg so the connector line is capped AT the circle edge and
// never shows through its (previously translucent) center.
const stepRingClass = 'relative z-10 border-primary/40 bg-background text-primary';
const stepLineClass = 'bg-primary/25';
const selectedRows = $derived(volumes.filter((v) => v.selected));
// A selected volume redirected to a NEW name or type (vs the snapshot's original).
// The recreate/redeploy uses the STORED config/compose, which still references the
// original mounts — so it won't pick up the redirected data. We warn + default the
// post-restore action to 'none' so the target isn't started with the wrong data.
const remappedRows = $derived(selectedRows.filter(
(v) => v.dest.trim() !== v.origDest || v.destKind !== v.origDestKind
));
const hasRemap = $derived(mode === 'new-location' && remappedRows.length > 0);
// The clone will bring the target up (recreate a container / redeploy a stack).
const willBringUp = $derived(postRestore === 'recreate' || postRestore === 'redeploy');
// Target-name collision blocks only when we'd bring the target up — a name clash
// is harmless for a pure extract (postRestore 'none').
const nameConflict = $derived(mode === 'new-location' && willBringUp && nameExistsOnTarget);
// A blocking issue: a volume collision, an invalid host path, or a target-name clash.
const hasBlockingIssue = $derived(mode === 'new-location' && (nameConflict || selectedRows.some((v) => v.conflict || v.pathInvalid)));
const canRun = $derived(
// A target environment MUST be chosen.
effectiveEnvId != null &&
(mode === 'in-place'
? confirmOverwrite
: (
// Every selected volume needs a non-empty destination; none may have a
// blocking issue (collision / invalid host path).
selectedRows.every((v) => v.dest.trim().length > 0) &&
!hasBlockingIssue &&
// Not a no-op: either something to restore, or a start action for a
// config-only snapshot (recreate/redeploy from stored config).
(selectedRows.length > 0 || postRestore !== 'none')
))
);
$effect(() => {
if (open && snapshotId) {
mode = 'new-location';
confirmOverwrite = false;
postRestore = 'recreate';
postRestoreUserPicked = false;
// Clone: NO env preselected — the user must consciously pick where it goes
// (the header shows no "to <env>" until they do). sourceEnvId is still seeded
// for in-place (which overwrites the live target on its own source env).
targetEnvId = undefined;
sourceEnvId = environmentId;
targetPath = `/restore/${containerName}`;
existingTargetVolumes = [];
// Reset stack-ness so a stale value from the previous open can't flash the
// wrong type icon while the new snapshot is still being read.
hasStackFiles = false;
restoreStatus = 'idle';
restoreLogs = [];
restoreWarning = '';
error = '';
if (envList.length === 0) environments.refresh();
void loadPreview();
}
});
// Re-check volume-name AND target-name conflicts whenever the target env changes
// (fail-closed: a named-volume destination OR the container/stack name already on
// the target blocks the clone).
$effect(() => {
const envId = effectiveEnvId;
// Track targetIsStack so the name check re-runs once the preview resolves the type.
const isStack = targetIsStack;
if (!open || mode !== 'new-location' || envId == null) { existingTargetVolumes = []; nameExistsOnTarget = false; return; }
void refreshTargetVolumes(envId);
void refreshTargetName(envId, isStack);
});
async function refreshTargetVolumes(envId: number) {
try {
const res = await fetch(`/api/volumes?env=${envId}`);
if (!res.ok) { existingTargetVolumes = []; return; }
const list = await res.json();
existingTargetVolumes = (Array.isArray(list) ? list : []).map((v: any) => v.Name ?? v.name).filter(Boolean);
} catch {
existingTargetVolumes = [];
}
}
// Does a container/stack named `containerName` already exist on the target env?
async function refreshTargetName(envId: number, isStack: boolean) {
try {
const path = isStack ? `/api/stacks?env=${envId}` : `/api/containers?env=${envId}`;
const res = await fetch(path);
if (!res.ok) { nameExistsOnTarget = false; return; }
const list = await res.json();
const names = (Array.isArray(list) ? list : []).map((x: any) => x.name ?? (Array.isArray(x.Names) ? x.Names[0]?.replace(/^\//, '') : undefined)).filter(Boolean);
nameExistsOnTarget = names.includes(containerName);
} catch {
nameExistsOnTarget = false;
}
}
// Switching a row between "Volume" (a named-volume) and "Host path" (a bind) —
// convert `dest` so a stale value from the other kind can't be submitted. A host
// path like `/docker/data/postgres18` is NOT a valid named-volume name (the server
// rejects it: validate.ts requires `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`), and vice-versa.
// path→volume: derive a name from the path's last segment; volume→path: prefix `/`.
// Empty when we can't convert cleanly, so the placeholder guides the user.
function onDestKindChange(vol: VolRow, next: 'volume' | 'path') {
if (vol.destKind === next) return;
const cur = vol.dest.trim();
if (next === 'volume') {
// From a host path → suggest the last path segment as a volume name, sanitised.
const base = cur.replace(/\/+$/, '').split('/').pop() ?? '';
const nameLike = base.replace(/[^a-zA-Z0-9_.-]/g, '');
vol.dest = /^[a-zA-Z0-9]/.test(nameLike) ? nameLike : '';
} else {
// From a volume name → an absolute path is required; only keep an already-
// absolute value, otherwise clear so the user types one.
vol.dest = cur.startsWith('/') ? cur : '';
}
vol.destKind = next;
}
// Mark each row's conflict flag: a named-volume destination that already exists
// on the target env. Bind (path) destinations are never a "conflict" (the user
// owns the host path). Recomputed whenever destinations or target volumes change.
$effect(() => {
const existing = existingTargetVolumes;
for (const v of volumes) {
const dest = v.dest.trim();
v.conflict = v.destKind === 'volume' && dest.length > 0 && existing.includes(dest);
// Match validate.ts exactly so the UI blocks a bad target BEFORE submit
// (previously only host paths were checked, so a volume kind with a path
// value like `/docker/...` slipped through to a generic 400).
v.pathInvalid = v.destKind === 'path'
? (dest.length === 0 || !dest.startsWith('/') || dest.includes('..'))
: !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(dest); // volume: must be a valid volume name
}
});
// Keep postRestore valid for the current mode (the option set differs: 'start'
// exists only in-place). On a mode switch, snap to the first allowed option.
$effect(() => {
if (!postRestoreOptions.some((o) => o.value === postRestore)) {
postRestore = postRestoreOptions[0]?.value as PostRestore;
}
});
// When the user redirects a volume to a new name/type, default the post-restore
// action to 'none' — bringing the target up would start it on the ORIGINAL mount,
// not the restored data. The user can still override (they may have already fixed
// their config); postRestoreUserPicked guards against fighting that choice.
$effect(() => {
if (hasRemap && !postRestoreUserPicked && postRestore !== 'none') postRestore = 'none';
});
async function loadPreview() {
loading = true;
error = '';
try {
const res = await fetch('/api/backup/restore/preview', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ destinationId, snapshotId, environmentId })
});
if (!res.ok) {
error = (await res.json()).error || 'Failed to read the snapshot';
return;
}
const data = await res.json();
const types: Record<string, 'volume' | 'bind'> = data.volumeTypes || {};
const sources: Record<string, string> = data.volumeSources || {};
// Pre-fill each destination 1:1 from the snapshot's original location: a
// named volume → its name (destKind 'volume'); a bind → its absolute host
// path (destKind 'path'). The user edits these to redirect the clone.
volumes = (data.volumes || []).map((name: string) => {
const type = types[name] ?? 'volume';
// destKind is 'volume' | 'path' — a bind source defaults to a host PATH,
// a named volume to a volume. (type is 'volume' | 'bind', not a destKind.)
const destKind: 'volume' | 'path' = type === 'bind' ? 'path' : 'volume';
const dest = sources[name] ?? name;
return { name, selected: true, type, dest, destKind, origDest: dest, origDestKind: destKind, conflict: false, pathInvalid: false };
});
hasMetadata = !!data.hasMetadata;
hasStackFiles = !!data.hasStackFiles;
backupTime = data.backupTime ?? null;
postRestore = data.hasStackFiles ? 'redeploy' : 'recreate';
// Recover the source env from the snapshot when the caller didn't supply one
// (empty prop) — needed for in-place (effectiveEnvId) and to default the
// clone target env. Only if that env still exists on this instance.
if (typeof data.sourceEnvironmentId === 'number' && envList.some((e) => e.id === data.sourceEnvironmentId)) {
// Only recover the SOURCE env (for in-place). The clone target env stays
// unselected on purpose — the user picks it.
if (sourceEnvId == null) sourceEnvId = data.sourceEnvironmentId;
}
} catch {
error = 'Failed to read the snapshot';
} finally {
loading = false;
}
}
async function executeRestore() {
if (!canRun) return;
restoring = true;
error = '';
restoreStatus = 'running';
restoreLogs = [];
try {
// For a clone (new-location), every selected volume carries a destination.
const volumeDestinations = mode === 'new-location'
? selectedRows.map((v) => ({ volume: v.name, kind: v.destKind, target: v.dest.trim() }))
: undefined;
const res = await fetch('/api/backup/restore', {
method: 'POST',
// Ask for the job-polling/streaming path so the modal's log fills as the
// restore runs (Accept: application/json would take the synchronous path
// with no progress lines).
headers: { 'Content-Type': 'application/json', 'Accept': 'text/event-stream' },
body: JSON.stringify({
destinationId,
snapshotId,
mode,
targetType: hasStackFiles ? 'stack' : 'container',
volumes: selectedRows.map((v) => v.name),
environmentId: effectiveEnvId,
targetName: containerName,
confirmOverwrite: mode === 'in-place' ? confirmOverwrite : undefined,
// postRestore is sent for BOTH modes now (clone brings the target up).
postRestore,
targetPath: mode === 'new-location' ? targetPath.trim() : undefined,
volumeDestinations
})
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
// Surface the specific validation reason(s), not just the generic
// "Invalid restore request" — e.g. "volume destination for X is not a
// valid volume name" tells the user exactly what to fix.
const issues = Array.isArray(body.issues)
? body.issues.map((i: { field?: string; message?: string }) => i.message).filter(Boolean)
: [];
error = issues.length
? `${body.error || 'Restore failed'}: ${issues.join('; ')}`
: (body.error || 'Restore failed');
restoreStatus = 'error';
restoring = false;
return;
}
const data = await res.json();
if (data.jobId) {
const result = (await watchJob(data.jobId, (line: any) => {
if (line.event === 'progress' && line.data?.message) {
restoreLogs = [...restoreLogs, tagLogLine(line.data.message)];
}
})) as any;
// Same discriminated-union handling as the backup path: a restore can come
// back 'skipped' (a concurrent op holds the lock) or 'warning' (data was
// restored but the post-restore recreate/redeploy failed) — neither is a
// plain success, and reporting them as one hides a half-finished restore.
const { outcome, message } = classifyJobResult(result);
if (outcome === 'error' || outcome === 'skipped') {
restoreStatus = 'error';
error = message || 'Restore failed';
restoreLogs = [...restoreLogs, tagLogLine(`[dockhand] Restore failed: ${error}`)];
} else if (outcome === 'warning') {
restoreStatus = 'warning';
restoreWarning = message || 'Restore completed with warnings';
restoreLogs = [...restoreLogs, tagLogLine(`[dockhand] Restore completed with warnings: ${restoreWarning}`)];
onDone?.(); // the data DID land — refresh the snapshot list
} else {
restoreStatus = 'success';
restoreLogs = [...restoreLogs, tagLogLine('[dockhand] Restore completed.')];
onDone?.();
}
}
} catch (e: any) {
restoreStatus = 'error';
error = e?.message || 'Restore failed';
restoreLogs = [...restoreLogs, tagLogLine(`[dockhand] Restore failed: ${error}`)];
} finally {
restoring = false;
}
}
</script>
<Dialog.Root bind:open>
<!-- Anchored near the top (not vertically centered) so toggling a volume or
switching modes grows the dialog DOWNWARD instead of jumping the whole box.
max-h + scroll keeps it usable on short screens. -->
<!-- Fixed height + internal scroll: the outer box never resizes, so switching
modes or checking/unchecking volumes changes only the scroll area, never the
dialog's top/bottom edges — no jumping. -->
<!-- Tall fixed height only for the multi-step FORM; the progress/result views
(log, success, warning, error) size to their content up to a cap so the log
dialog isn't a giant near-empty box. The tall form is top-anchored (top-[4vh])
so growing it downward doesn't jump; the short result views drop that override
and use the dialog's DEFAULT centered position — otherwise a one-line result
box sits glued to the top of the screen. -->
<Dialog.Content class="max-w-5xl flex flex-col overflow-hidden {restoreStatus === 'idle' ? 'top-[4vh] translate-y-0 h-[88vh]' : 'top-[6vh] translate-y-0 h-[85vh]'}">
<Dialog.Header class="shrink-0">
<Dialog.Title class="flex flex-wrap items-center gap-x-2 gap-y-1">
<RotateCcw class="h-4 w-4" /> Restore
{#if !loading}{#if targetIsStack}<Layers class="h-4 w-4 text-muted-foreground" />{:else}<Box class="h-4 w-4 text-muted-foreground" />{/if}{/if}
<span>{containerName}</span>
{#if targetEnv}
<span class="text-muted-foreground">{mode === 'in-place' ? 'on' : 'to'}</span>
<span class="flex items-center gap-1 font-medium text-amber-500"><EnvironmentIcon icon={targetEnv.icon || 'globe'} envId={targetEnv.id} class="h-3.5 w-3.5" />{targetEnvName}</span>
{/if}
<Badge variant="outline" class="font-mono text-[10px]">{snapshotId.slice(0, 8)}</Badge>
{#if backupTime}<span class="flex items-center gap-1 text-xs font-normal text-muted-foreground"><Clock class="h-3 w-3" />{formatDateTime(backupTime)}</span>{/if}
</Dialog.Title>
<Dialog.Description class="sr-only">Restore snapshot {snapshotId.slice(0, 8)} for {containerName}.</Dialog.Description>
</Dialog.Header>
<!-- The single scroll region. flex-1 fills the fixed-height dialog between the
pinned header and footer; content growth scrolls here, not the outer box. -->
<div class="flex flex-1 flex-col overflow-y-auto -mx-6 px-6">
{#if loading}
<div class="flex flex-1 items-center justify-center text-muted-foreground">
<Loader2 class="h-5 w-5 animate-spin" /> <span class="ml-2">Reading snapshot…</span>
</div>
{:else if restoreStatus !== 'idle'}
<!-- Running AND finished states keep the LIVE LOG visible (no separate result
screen that hides what happened) — the outcome is appended as a final log
line and summarised in the status strip below, matching the backup dialog. -->
<!-- flex-1 + fixed dialog height: the log fills the space and SCROLLS
internally, so the dialog never grows/jumps as lines stream in. -->
<div class="flex min-h-0 flex-1 flex-col py-2">
<LogConsole lines={restoreLogs} class="flex-1 min-h-0" />
<div class="mt-2 flex shrink-0 items-center gap-1.5 text-sm">
{#if restoreStatus === 'running'}
<Loader2 class="h-4 w-4 animate-spin text-muted-foreground" /><span class="text-muted-foreground">Restoring…</span>
{:else if restoreStatus === 'success'}
<CheckCircle2 class="h-4 w-4 text-green-500" />
<span class="text-green-500">Restore completed</span>
<span class="text-muted-foreground">— {mode === 'new-location'
? `restored to ${targetEnvName}${postRestore !== 'none' ? (targetIsStack ? ', stack redeployed' : ', container recreated') : ''}`
: `live volume replaced — restart ${containerName}${hasStackFiles ? ' / redeploy the stack' : ''} to use it`}.</span>
{:else if restoreStatus === 'warning'}
<AlertTriangle class="h-4 w-4 text-amber-500" /><span class="text-amber-600 dark:text-amber-400">Restore completed with warnings — {restoreWarning}</span>
{:else}
<XCircle class="h-4 w-4 text-destructive" /><span class="text-destructive">{error || 'Restore failed'}</span>
{/if}
</div>
</div>
{:else}
<div class="flex-1 py-2">
{#if error}
<p class="mb-3 rounded bg-destructive/10 p-2 text-sm text-destructive">{error}</p>
{/if}
<!-- STEP 1 — Where does it go? (mode + target env) -->
<div class="grid grid-cols-[26px_1fr] gap-x-3">
<div class="flex flex-col items-center">
<span class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full border text-xs font-bold {stepRingClass}">1</span>
<span class="-mb-3 w-0.5 flex-1 rounded {stepLineClass}"></span>
</div>
<div class="space-y-2 pb-3">
<div class="text-sm font-semibold">Where does it go? <span class="font-normal text-xs text-muted-foreground">— pick where, and how</span></div>
<div class="grid grid-cols-2 gap-2">
<button
type="button"
class="rounded border p-3 text-left text-sm {mode === 'new-location' ? 'border-primary bg-primary/5' : ''}"
onclick={() => (mode = 'new-location')}
>
<div class="flex items-center gap-1.5 font-medium"><Server class="h-3.5 w-3.5" /> To an environment</div>
<div class="mt-1 text-xs text-muted-foreground">Clone it onto a chosen environment.</div>
</button>
<button
type="button"
class="rounded border p-3 text-left text-sm {mode === 'in-place' ? 'border-primary bg-primary/5' : ''}"
onclick={() => (mode = 'in-place')}
>
<div class="flex items-center gap-1.5 font-medium"><AlertTriangle class="h-3.5 w-3.5 text-destructive" /> Overwrite live</div>
<div class="mt-1 text-xs text-muted-foreground">Replace the live data in place. Destructive.</div>
</button>
</div>
{#if mode === 'new-location'}
<div class="space-y-1.5">
<Label class="flex items-center gap-1.5"><Server class="h-3.5 w-3.5" /> Target environment</Label>
<Select.Root type="single" value={effectiveEnvId != null ? String(effectiveEnvId) : ''} onValueChange={(v) => (targetEnvId = v ? parseInt(v) : undefined)}>
<Select.Trigger class="h-9 w-full">
{#if targetEnv}
<span class="flex items-center gap-2"><EnvironmentIcon icon={targetEnv.icon || 'globe'} envId={targetEnv.id} class="h-4 w-4 text-muted-foreground" />{targetEnv.name}</span>
{:else}
<span class="text-muted-foreground">Select an environment…</span>
{/if}
</Select.Trigger>
<Select.Content>
{#each envList as env}
<Select.Item value={String(env.id)}>
<span class="flex items-center gap-2"><EnvironmentIcon icon={env.icon || 'globe'} envId={env.id} class="h-4 w-4 text-muted-foreground" />{env.name}</span>
</Select.Item>
{/each}
</Select.Content>
</Select.Root>
</div>
{/if}
</div>
</div>
<!-- STEP 2 — What gets restored? (volumes + destinations) -->
<div class="grid grid-cols-[26px_1fr] gap-x-3">
<div class="flex flex-col items-center">
<span class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full border text-xs font-bold {stepRingClass}">2</span>
<span class="-mb-3 w-0.5 flex-1 rounded {stepLineClass}"></span>
</div>
<div class="space-y-2 pb-3">
<div class="flex items-center gap-1.5 text-sm font-semibold">
{mode === 'in-place' ? 'What gets overwritten?' : 'What gets restored?'}
<span class="font-normal text-xs text-muted-foreground">— {selectedRows.length} of {volumes.length} {volumes.length === 1 ? 'volume' : 'volumes'}</span>
{#if mode === 'new-location'}
<Tooltip.Root>
<Tooltip.Trigger class="ml-0.5"><HelpCircle class="h-3.5 w-3.5 text-muted-foreground opacity-70" /></Tooltip.Trigger>
<Tooltip.Content class="w-[22rem] max-w-[90vw]">
<p class="text-xs leading-relaxed">Each destination is resolved by <b>{targetEnvName || 'the target'}</b>'s Docker daemon: a <b>host path</b> must exist on that host (not on Dockhand's), while a <b>named volume</b> is created there. Prefer named volumes for portability. The post-restore step brings the {targetIsStack ? 'stack' : 'container'} up; if it fails, the data is still restored and you finish manually.</p>
</Tooltip.Content>
</Tooltip.Root>
{/if}
</div>
{#if volumes.length === 0}
<p class="text-sm text-muted-foreground">This snapshot has no volumes — restore recreates the {targetIsStack ? 'stack' : 'container'} from its saved config.</p>
{:else if mode === 'new-location'}
<!-- Clone mode: each selected volume maps to an editable DESTINATION on
the target env. Default is the original location (1:1 clone). -->
<div class="space-y-2 rounded border p-2">
{#each volumes as vol}
<div class="space-y-1">
<label class="flex cursor-pointer items-center gap-2 text-sm">
<Checkbox bind:checked={vol.selected} />
{#if vol.type === 'bind'}
<Folder class="h-3.5 w-3.5 shrink-0 text-amber-500" />
<span class="w-11 shrink-0 rounded-full bg-amber-500/15 px-1.5 py-0.5 text-center text-[10px] font-semibold uppercase tracking-wide text-amber-600 dark:text-amber-400">bind</span>
{:else}
<HardDrive class="h-3.5 w-3.5 shrink-0 text-sky-500" />
<span class="w-11 shrink-0 rounded-full bg-sky-500/15 px-1.5 py-0.5 text-center text-[10px] font-semibold uppercase tracking-wide text-sky-600 dark:text-sky-400">vol</span>
{/if}
<span class="truncate font-mono">{vol.name}</span>
</label>
{#if vol.selected}
<div class="flex items-center gap-1.5 pl-6">
<span class="text-xs text-muted-foreground">→</span>
<Select.Root type="single" value={vol.destKind} onValueChange={(v) => onDestKindChange(vol, v as 'volume' | 'path')}>
<Select.Trigger class="h-8 w-32 shrink-0 text-xs">
{#if vol.destKind === 'path'}
<span class="flex items-center gap-1.5"><Folder class="h-3.5 w-3.5 text-amber-500" /> Host path</span>
{:else}
<span class="flex items-center gap-1.5"><HardDrive class="h-3.5 w-3.5 text-sky-500" /> Volume</span>
{/if}
</Select.Trigger>
<Select.Content>
<Select.Item value="volume"><span class="flex items-center gap-1.5"><HardDrive class="h-3.5 w-3.5 text-sky-500" /> Volume</span></Select.Item>
<Select.Item value="path"><span class="flex items-center gap-1.5"><Folder class="h-3.5 w-3.5 text-amber-500" /> Host path</span></Select.Item>
</Select.Content>
</Select.Root>
<Input bind:value={vol.dest} class="h-8 flex-1 font-mono text-xs {(vol.conflict || vol.pathInvalid) ? 'border-destructive' : ''}" placeholder={vol.destKind === 'path' ? '/absolute/path' : 'volume-name'} />
</div>
{#if vol.conflict}
<p class="pl-6 text-xs text-destructive">Volume <span class="font-mono">{vol.dest}</span> already exists on {targetEnvName}. Remove it or choose another destination.</p>
{:else if vol.pathInvalid}
<p class="pl-6 text-xs text-destructive">A host path must be absolute — start it with <span class="font-mono">/</span> (e.g. <span class="font-mono">/srv/{vol.name}</span>).</p>
{/if}
{/if}
</div>
{/each}
</div>
{:else}
<div class="space-y-1.5 rounded border p-2">
{#each volumes as vol}
<label class="flex cursor-pointer items-center gap-2 text-sm">
<Checkbox bind:checked={vol.selected} />
{#if vol.type === 'bind'}
<Folder class="h-3.5 w-3.5 shrink-0 text-amber-500" />
<span class="w-11 shrink-0 rounded-full bg-amber-500/15 px-1.5 py-0.5 text-center text-[10px] font-semibold uppercase tracking-wide text-amber-600 dark:text-amber-400">bind</span>
{:else}
<HardDrive class="h-3.5 w-3.5 shrink-0 text-sky-500" />
<span class="w-11 shrink-0 rounded-full bg-sky-500/15 px-1.5 py-0.5 text-center text-[10px] font-semibold uppercase tracking-wide text-sky-600 dark:text-sky-400">vol</span>
{/if}
<span class="truncate font-mono">{vol.name}</span>
</label>
{/each}
</div>
{/if}
</div>
</div>
<!-- STEP 3 — Then what? (after-restore action) -->
<div class="grid grid-cols-[26px_1fr] gap-x-3">
<div class="flex flex-col items-center">
<span class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full border text-xs font-bold {stepRingClass}">3</span>
</div>
<div class="space-y-2 pb-1">
<div class="text-sm font-semibold">Then what? <span class="font-normal text-xs text-muted-foreground">— {mode === 'in-place' ? 'bring it back up' : 'bring it up on the target'}</span></div>
{#if mode === 'new-location'}
<!-- After restore: bring the target up on the chosen env. -->
<div class="space-y-1.5">
<Label class="sr-only">After restore</Label>
<Select.Root type="single" value={postRestore} onValueChange={(v) => { postRestore = v as PostRestore; postRestoreUserPicked = true; }}>
<Select.Trigger class="h-9">
{#each postRestoreOptions as opt}
{#if opt.value === postRestore}
{@const OptIcon = opt.icon}
<span class="flex items-center gap-2"><OptIcon class="h-3.5 w-3.5 text-muted-foreground" />{opt.label}</span>
{/if}
{/each}
</Select.Trigger>
<Select.Content>
{#each postRestoreOptions as opt}
{@const OptIcon = opt.icon}
<Select.Item value={opt.value}>
<span class="flex items-center gap-2"><OptIcon class="h-3.5 w-3.5 text-muted-foreground" />{opt.label}</span>
</Select.Item>
{/each}
</Select.Content>
</Select.Root>
{#if nameConflict}
<p class="text-xs text-destructive">A {targetIsStack ? 'stack' : 'container'} named <span class="font-mono">{containerName}</span> already exists on {targetEnvName}. Remove it or choose "Do nothing" — the restore won't overwrite it.</p>
{/if}
</div>
{:else}
<div class="space-y-1.5">
<Label>After restore</Label>
<Select.Root type="single" value={postRestore} onValueChange={(v) => { postRestore = v as PostRestore; postRestoreUserPicked = true; }}>
<Select.Trigger class="h-9">
{#each postRestoreOptions as opt}
{#if opt.value === postRestore}
{@const OptIcon = opt.icon}
<span class="flex items-center gap-2"><OptIcon class="h-3.5 w-3.5 text-muted-foreground" />{opt.label}</span>
{/if}
{/each}
</Select.Trigger>
<Select.Content>
{#each postRestoreOptions as opt}
{@const OptIcon = opt.icon}
<Select.Item value={opt.value}>
<span class="flex items-center gap-2"><OptIcon class="h-3.5 w-3.5 text-muted-foreground" />{opt.label}</span>
</Select.Item>
{/each}
</Select.Content>
</Select.Root>
</div>
{/if}
</div>
</div>
<!-- What will happen: a live prose recap driven by the form. Env names amber,
each prefixed by the env's icon (same as the modal header). -->
{#snippet envChip(env: { id: number; icon?: string | null } | undefined, name: string)}
<span class="inline-flex items-center gap-1 align-middle font-medium text-amber-500">{#if env}<EnvironmentIcon icon={env.icon || 'globe'} envId={env.id} class="h-3.5 w-3.5" />{/if}{name || '…'}</span>
{/snippet}
<div class="mt-3 rounded-md border border-l-[3px] p-3 text-sm {mode === 'in-place' ? 'border-l-destructive bg-destructive/5' : 'border-l-primary bg-primary/5'}">
<div class="mb-1.5 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">
{#if mode === 'in-place'}<AlertTriangle class="h-3.5 w-3.5 text-destructive" />{:else}<Info class="h-3.5 w-3.5 text-primary" />{/if}
What will happen
</div>
{#if mode === 'in-place'}
<p class="leading-relaxed">
The snapshot{#if backupTime}&nbsp;taken <span class="font-mono">{formatDateTime(backupTime)}</span>{/if}{#if sourceEnvName}&nbsp;from {@render envChip(sourceEnv, sourceEnvName)}{/if} will <b class="text-destructive">overwrite the live data</b>{#if targetEnvName}&nbsp;on {@render envChip(targetEnv, targetEnvName)}{/if}{#if selectedRows.length > 0}:{:else}.{/if}
</p>
{#if selectedRows.length > 0}
<ul class="mt-1.5 space-y-1">
{#each selectedRows as v}
<li class="flex items-center gap-2 text-xs">
{#if v.type === 'bind'}<Folder class="h-3 w-3 shrink-0 text-amber-500" />{:else}<HardDrive class="h-3 w-3 shrink-0 text-sky-500" />{/if}
{#if v.type === 'bind'}<span class="w-9 shrink-0 rounded-full bg-amber-500/15 px-1 py-0.5 text-center text-[9px] font-semibold uppercase tracking-wide text-amber-600 dark:text-amber-400">bind</span>{:else}<span class="w-9 shrink-0 rounded-full bg-sky-500/15 px-1 py-0.5 text-center text-[9px] font-semibold uppercase tracking-wide text-sky-600 dark:text-sky-400">vol</span>{/if}
<span class="font-mono">{v.name}</span>
<span class="text-muted-foreground">wiped &amp; replaced</span>
</li>
{/each}
</ul>
{/if}
<p class="mt-1.5 leading-relaxed">The {targetIsStack ? 'stack' : 'container'} is <b>stopped before the restore</b> (expect downtime); the volumes are swapped (staged then committed), then <b>{postRestoreLabel.toLowerCase()}</b>.</p>
<label class="mt-2.5 flex cursor-pointer items-center gap-2 border-t border-destructive/20 pt-2.5 text-sm">
<Checkbox bind:checked={confirmOverwrite} />
I understand this replaces the live volume data.
</label>
{:else}
<p class="leading-relaxed">
The snapshot{#if backupTime}&nbsp;taken <span class="font-mono">{formatDateTime(backupTime)}</span>{/if}{#if sourceEnvName}&nbsp;from {@render envChip(sourceEnv, sourceEnvName)}{/if} will be restored to {@render envChip(targetEnv, targetEnvName)}{#if selectedRows.length > 0}:{:else}.{/if}
</p>
{#if selectedRows.length > 0}
<ul class="mt-1.5 space-y-1">
{#each selectedRows as v}
<li class="flex items-center gap-2 text-xs">
{#if v.type === 'bind'}<Folder class="h-3 w-3 shrink-0 text-amber-500" />{:else}<HardDrive class="h-3 w-3 shrink-0 text-sky-500" />{/if}
{#if v.type === 'bind'}<span class="w-9 shrink-0 rounded-full bg-amber-500/15 px-1 py-0.5 text-center text-[9px] font-semibold uppercase tracking-wide text-amber-600 dark:text-amber-400">bind</span>{:else}<span class="w-9 shrink-0 rounded-full bg-sky-500/15 px-1 py-0.5 text-center text-[9px] font-semibold uppercase tracking-wide text-sky-600 dark:text-sky-400">vol</span>{/if}
<span class="font-mono">{v.name}</span>
<span class="text-muted-foreground">→ {v.destKind === 'path' ? 'host path' : 'named volume'}</span>
<span class="font-mono {(v.conflict || v.pathInvalid) ? 'text-destructive' : ''}">{v.dest.trim() || '…'}</span>
</li>
{/each}
</ul>
{/if}
{#if postRestore !== 'none'}
<p class="mt-1.5 leading-relaxed">Then Dockhand will <b>{postRestoreLabel.toLowerCase()}</b> on {@render envChip(targetEnv, targetEnvName)}{#if sourceEnvName && sourceEnvName !== targetEnvName}. Nothing on {@render envChip(sourceEnv, sourceEnvName)} is touched{/if}.</p>
{:else}
<p class="mt-1.5 leading-relaxed">The {targetIsStack ? 'stack' : 'container'} is <b>not started</b> — the data lands on {@render envChip(targetEnv, targetEnvName)} and you bring it up yourself.</p>
{/if}
{#if hasRemap}
<!-- The recreate/redeploy uses the snapshot's STORED config/compose, which
still references the ORIGINAL mounts — it won't follow a redirected
name/type, so the target would come up on the wrong (empty) volume. -->
<div class="mt-2.5 rounded-md border border-l-[3px] border-amber-500/30 border-l-amber-500 bg-amber-500/10 p-2.5">
<div class="mb-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-600 dark:text-amber-400">
<AlertTriangle class="h-3.5 w-3.5" /> You have changed a volume's name or type
</div>
<p class="text-xs leading-relaxed text-amber-700 dark:text-amber-300/90">Your data goes to the new volumes. But the {targetIsStack ? 'stack redeploys from the stored compose file, which still names' : 'recreated container mounts'} the <b>original</b> ones — so it {targetIsStack ? 'starts with empty volumes' : "won't see the restored data"}.</p>
<p class="mt-1 text-xs leading-relaxed text-amber-700 dark:text-amber-300/90"><b>After restoring:</b> {targetIsStack ? 'update the compose file to the new volume names, then redeploy.' : 'edit the container and point the mount at the new volume.'}</p>
{#if postRestore === 'none'}<p class="mt-1 text-[11px] leading-relaxed text-amber-600/70 dark:text-amber-300/60">Next step set to <b>Do nothing</b> so it can't start with the wrong data.</p>{/if}
</div>
{/if}
{/if}
</div>
</div>
{/if}
</div>
<Dialog.Footer class="shrink-0">
{#if restoreStatus === 'success' || restoreStatus === 'warning' || restoreStatus === 'error'}
<Button variant="outline" onclick={() => (open = false)}>OK</Button>
{:else if restoreStatus !== 'running'}
<Button variant="outline" onclick={() => (open = false)} disabled={restoring}>Cancel</Button>
<!-- Hide the restore action until the snapshot is read — until then we
don't know its volumes/target, so there's nothing to restore yet. -->
{#if !loading}
<Button
onclick={executeRestore}
disabled={!canRun || restoring}
variant={mode === 'in-place' ? 'destructive' : 'default'}
>
{#if restoring}<Loader2 class="mr-1.5 h-4 w-4 animate-spin" />{:else}<Play class="mr-1.5 h-4 w-4" />{/if}
{mode === 'in-place' ? 'Overwrite & restore' : (postRestore !== 'none' ? 'Restore & start' : 'Restore')}
</Button>
{/if}
{/if}
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>
@@ -0,0 +1,422 @@
<script lang="ts">
import * as Dialog from '$lib/components/ui/dialog';
import { Badge } from '$lib/components/ui/badge';
import {
FolderOpen, Box, Layers, Network, Loader2, HardDrive, Tag, Variable,
Plug, HeartPulse, ScrollText, ShieldAlert, Server, Globe, Cpu, FileText
} from 'lucide-svelte';
import MountTypeBadge from '$lib/components/MountTypeBadge.svelte';
import { getRepoTypeIcon } from '$lib/utils/backup';
import { formatBytes } from '$lib/utils/format';
import { formatDateTime } from '$lib/stores/settings';
import { environments } from '$lib/stores/environment';
import EnvironmentIcon from '$lib/components/EnvironmentIcon.svelte';
import FileBrowserPanel from './FileBrowserPanel.svelte';
interface Props {
open: boolean;
destinationId: number;
snapshotId: string;
targetName?: string;
targetType?: 'container' | 'stack';
environmentId?: number;
}
let { open = $bindable(), destinationId, snapshotId, targetName, targetType, environmentId }: Props = $props();
let activeTab = $state<'files' | 'metadata'>('files');
let metadata = $state<any>(null);
let metadataLoading = $state(false);
let metadataError = $state('');
let snapshotTime = $state('');
let destinationName = $state('');
let destinationRepo = $state('');
let snapshotEnvName = $state('');
let snapshotEnvIcon = $state('globe');
let snapshotEnvId = $state(0);
$effect(() => {
if (open && snapshotId) {
activeTab = 'files';
metadata = null;
metadataError = '';
snapshotTime = '';
destinationName = '';
destinationRepo = '';
snapshotEnvName = '';
snapshotEnvIcon = 'globe';
snapshotEnvId = 0;
fetchMetadata();
fetchSnapshotInfo();
}
});
const displayName = $derived(targetName || metadata?.targetName || '');
// The backup stores a full docker inspect (PascalCase keys) as metadata.container
// (singular) for container targets; null for stacks.
const containerInspect = $derived<any>(metadata?.container ?? null);
async function fetchSnapshotInfo() {
try {
// Get destination name
const destRes = await fetch(`/api/backup/destinations/${destinationId}`);
if (destRes.ok) {
const dest = await destRes.json();
destinationName = dest.name || '';
destinationRepo = dest.repository || '';
}
// Get snapshot time + owning environment from the snapshot's tags.
const snapRes = await fetch(`/api/backup/snapshots?destinationId=${destinationId}`);
if (snapRes.ok) {
const d = await snapRes.json();
const snaps = d.snapshots ?? d;
const snap = (Array.isArray(snaps) ? snaps : []).find((s: any) => s.id === snapshotId || s.shortId === snapshotId?.slice(0, 8));
if (snap) {
snapshotTime = snap.time;
// dockhand:envid=<n> tag identifies the source environment ('local' = none).
const envTag = (snap.tags || []).find((t: string) => t.startsWith('dockhand:envid='))?.replace('dockhand:envid=', '');
const envId = envTag && envTag !== 'local' ? parseInt(envTag) : NaN;
if (!isNaN(envId)) {
const env = $environments.find((e) => e.id === envId);
if (env) { snapshotEnvName = env.name; snapshotEnvIcon = env.icon || 'globe'; snapshotEnvId = env.id; }
}
}
}
} catch {}
}
async function fetchMetadata() {
metadataLoading = true;
metadataError = '';
try {
const res = await fetch(`/api/backup/snapshots/${snapshotId}/metadata?destinationId=${destinationId}`);
if (res.ok) {
metadata = await res.json();
} else {
try { metadataError = (await res.json()).error || 'No metadata available'; }
catch { metadataError = 'No metadata available'; }
}
} catch { metadataError = 'Failed to load metadata'; }
finally { metadataLoading = false; }
}
</script>
<Dialog.Root bind:open>
<Dialog.Content class="max-w-4xl h-[90vh] sm:h-[80vh] flex flex-col overflow-hidden">
<Dialog.Header>
<Dialog.Title class="flex items-center gap-2 flex-wrap">
<FolderOpen class="w-5 h-5" />
Browse snapshot
{#if snapshotEnvName}
<span class="text-muted-foreground font-normal">from</span>
<EnvironmentIcon icon={snapshotEnvIcon} envId={snapshotEnvId} class="w-4 h-4 text-amber-600 dark:text-amber-400" />
<span class="font-normal text-amber-600 dark:text-amber-400">{snapshotEnvName}</span>
{/if}
{#if displayName}
<span class="text-muted-foreground font-normal">—</span>
{#if (targetType || metadata?.type) === 'stack'}
<Layers class="w-4 h-4 text-purple-500" />
{:else}
<Box class="w-4 h-4 text-blue-500" />
{/if}
<span class="font-normal">{displayName}</span>
{/if}
{#if destinationName}
<span class="text-muted-foreground font-normal">on</span>
<svelte:component this={getRepoTypeIcon(destinationRepo)} class="w-4 h-4" />
<span class="font-normal">{destinationName}</span>
{/if}
</Dialog.Title>
<Dialog.Description class="flex items-center gap-2 text-xs text-muted-foreground">
{#if snapshotId}<Badge variant="outline" class="font-mono text-[10px]">{String(snapshotId).slice(0, 8)}</Badge>{/if}
{#if snapshotTime}{formatDateTime(snapshotTime)}{/if}
</Dialog.Description>
</Dialog.Header>
<!-- Tabs -->
<div class="flex gap-1 border-b pb-0 shrink-0">
<button
type="button"
class="px-3 py-1.5 text-sm transition-colors border-b-2 -mb-px {activeTab === 'files' ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'}"
onclick={() => activeTab = 'files'}
>
Files
</button>
<button
type="button"
class="px-3 py-1.5 text-sm transition-colors border-b-2 -mb-px {activeTab === 'metadata' ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'}"
onclick={() => activeTab = 'metadata'}
>
Metadata
</button>
</div>
<!-- Keep BOTH panels mounted and toggle visibility with `hidden` instead of
{#if}/{:else}. An {#if} destroys FileBrowserPanel on every switch to
Metadata, so returning to Files re-runs its load $effect and re-browses
the snapshot from the (possibly remote) restic repo each time. Keeping it
alive preserves the already-loaded directory + current path — no repeat
round-trip. -->
<div class="flex-1 overflow-hidden border rounded-lg" class:hidden={activeTab !== 'files'}>
<FileBrowserPanel
{snapshotId}
{destinationId}
canEdit={false}
/>
</div>
<!-- Metadata tab -->
{#if activeTab === 'metadata'}
<div class="flex-1 overflow-y-auto py-3">
{#if metadataLoading}
<div class="flex items-center justify-center py-8"><Loader2 class="w-5 h-5 animate-spin text-muted-foreground" /></div>
{:else if metadataError}
<p class="text-sm text-muted-foreground p-4">{metadataError}</p>
{:else if metadata}
<div class="max-w-2xl space-y-5 px-1">
<!-- Backup info -->
<section class="space-y-2">
<h4 class="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Backup info</h4>
<dl class="grid grid-cols-[130px_1fr] gap-y-1.5 text-sm">
<dt class="text-muted-foreground">Type</dt>
<dd><Badge variant="outline" class="text-[10px]">{metadata.type}</Badge></dd>
<dt class="text-muted-foreground">Name</dt>
<dd class="font-medium">{metadata.targetName}</dd>
<dt class="text-muted-foreground">Backup time</dt>
<dd>{formatDateTime(metadata.backupTime)}</dd>
{#if metadata.environmentId != null}
<dt class="text-muted-foreground">Environment ID</dt>
<dd class="font-mono text-xs">{metadata.environmentId}</dd>
{/if}
<dt class="text-muted-foreground">Volumes</dt>
<dd>{metadata.volumes?.length ?? 0}</dd>
{#if metadata.type === 'stack'}
{#if metadata.composeFileName}
<dt class="text-muted-foreground">Compose file</dt>
<dd class="font-mono text-xs">{metadata.composeFileName}</dd>
{/if}
<dt class="text-muted-foreground">Stack files</dt>
<dd>{metadata.hasStackFiles ? (metadata.stackFilesTruncated ? 'captured (truncated)' : 'captured') : 'not captured'}</dd>
{/if}
</dl>
</section>
<!-- Volumes / binds -->
{#if metadata.volumes?.length}
<section class="space-y-2 border-t pt-4">
<h4 class="text-xs font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-1.5"><HardDrive class="w-3.5 h-3.5" />Volumes &amp; binds ({metadata.volumes.length})</h4>
<div class="space-y-1">
{#each metadata.volumes as vol}
<!-- Docker convention: source (host path / volume name) → destination
(container path). `vol.source` is the host path/volume name,
`vol.name` is the container destination. -->
<div class="flex items-center gap-2 text-sm bg-muted/30 rounded px-2 py-1.5">
<MountTypeBadge type={vol.type} />
{#if vol.source && vol.source !== vol.name}
<span class="font-mono text-muted-foreground truncate">{vol.source}</span>
<span class="text-muted-foreground shrink-0">→</span>
<span class="font-medium truncate">{vol.name || vol.key}</span>
{:else}
<span class="font-medium truncate">{vol.name || vol.key}</span>
{/if}
</div>
{/each}
</div>
</section>
{/if}
<!-- Stack files (captured under stackfiles/). The list is recorded in
metadata.json at backup time so we can enumerate the exact files
without a browse roundtrip. -->
{#if metadata.type === 'stack' && metadata.stackFilesList?.length}
<section class="space-y-2 border-t pt-4">
<h4 class="text-xs font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-1.5"><FileText class="w-3.5 h-3.5" />Stack files ({metadata.stackFilesList.length}{metadata.stackFilesListTruncated ? '+' : ''})</h4>
<div class="space-y-1">
{#each metadata.stackFilesList as file}
<div class="flex items-center gap-2 text-sm bg-muted/30 rounded px-2 py-1.5">
<span class="font-mono truncate flex-1" class:font-medium={file.path === metadata.composeFileName}>{file.path}</span>
{#if file.path === metadata.composeFileName}
<Badge variant="outline" class="text-[10px] shrink-0">compose</Badge>
{/if}
<span class="text-muted-foreground text-xs shrink-0 tabular-nums">{formatBytes(file.bytes)}</span>
</div>
{/each}
</div>
{#if metadata.stackFilesListTruncated}
<p class="text-xs text-muted-foreground">Only the first {metadata.stackFilesList.length} files are listed. Browse the snapshot to see the full tree.</p>
{/if}
</section>
{/if}
<!-- Container config (docker inspect, PascalCase, singular). Only for
container targets — stacks have no metadata.container. -->
{#if containerInspect?.Config}
<section class="space-y-2 border-t pt-4">
<h4 class="text-xs font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-1.5">
<Box class="w-3 h-3" />
{(containerInspect.Name || metadata.targetName || '').replace(/^\//, '')}
</h4>
<dl class="grid grid-cols-[130px_1fr] gap-y-1.5 text-sm">
<dt class="text-muted-foreground">Image</dt>
<dd class="font-mono text-xs break-all">{containerInspect.Config.Image || '—'}</dd>
{#if containerInspect.Id}
<dt class="text-muted-foreground">Container ID</dt>
<dd class="font-mono text-xs">{containerInspect.Id.slice(0, 12)}</dd>
{/if}
{#if containerInspect.State?.Status}
<dt class="text-muted-foreground">State at backup</dt>
<dd class="text-xs">{containerInspect.State.Status}</dd>
{/if}
{#if containerInspect.Created}
<dt class="text-muted-foreground">Created</dt>
<dd class="text-xs">{formatDateTime(containerInspect.Created)}</dd>
{/if}
{#if containerInspect.Config.Cmd?.length}
<dt class="text-muted-foreground">Command</dt>
<dd class="font-mono text-xs break-all">{containerInspect.Config.Cmd.join(' ')}</dd>
{/if}
{#if containerInspect.Config.Entrypoint?.length}
<dt class="text-muted-foreground">Entrypoint</dt>
<dd class="font-mono text-xs break-all">{containerInspect.Config.Entrypoint.join(' ')}</dd>
{/if}
{#if containerInspect.Config.WorkingDir}
<dt class="text-muted-foreground">Working dir</dt>
<dd class="font-mono text-xs break-all">{containerInspect.Config.WorkingDir}</dd>
{/if}
{#if containerInspect.Config.User}
<dt class="text-muted-foreground">User</dt>
<dd class="font-mono text-xs">{containerInspect.Config.User}</dd>
{/if}
{#if containerInspect.Config.ExposedPorts}
<dt class="text-muted-foreground">Exposed ports</dt>
<dd class="text-xs break-all">{Object.keys(containerInspect.Config.ExposedPorts).join(', ')}</dd>
{/if}
{#if containerInspect.HostConfig?.RestartPolicy?.Name}
<dt class="text-muted-foreground">Restart policy</dt>
<dd class="text-xs">{containerInspect.HostConfig.RestartPolicy.Name}{containerInspect.HostConfig.RestartPolicy.MaximumRetryCount ? ` (max ${containerInspect.HostConfig.RestartPolicy.MaximumRetryCount})` : ''}</dd>
{/if}
{#if containerInspect.HostConfig?.NetworkMode}
<dt class="text-muted-foreground">Network mode</dt>
<dd class="text-xs break-all">{containerInspect.HostConfig.NetworkMode}</dd>
{/if}
{#if containerInspect.HostConfig?.Privileged}
<dt class="text-muted-foreground">Privileged</dt>
<dd class="text-xs">yes</dd>
{/if}
</dl>
<!-- Port bindings (host:container map — more useful than the internal
ExposedPorts above; only present when ports are published). -->
{#if containerInspect.HostConfig?.PortBindings && Object.keys(containerInspect.HostConfig.PortBindings).length}
<div class="pt-1 space-y-1.5">
<span class="text-xs font-semibold text-muted-foreground flex items-center gap-1.5"><Plug class="w-3.5 h-3.5" />Port bindings</span>
<div class="flex flex-wrap gap-1">
{#each Object.entries(containerInspect.HostConfig.PortBindings) as [containerPort, hostArr]}
{@const h = (hostArr as any[])?.[0]}
<Badge variant="secondary" class="text-xs font-mono">{h?.HostIp ? `${h.HostIp}:` : ''}{h?.HostPort || '?'} → {containerPort}</Badge>
{/each}
</div>
</div>
{/if}
<!-- Health at backup -->
{#if containerInspect.State?.Health?.Status}
<div class="pt-1 space-y-1.5">
<span class="text-xs font-semibold text-muted-foreground flex items-center gap-1.5"><HeartPulse class="w-3.5 h-3.5" />Health at backup</span>
<Badge variant="outline" class="text-xs {containerInspect.State.Health.Status === 'healthy' ? 'text-green-600 border-green-600/40' : containerInspect.State.Health.Status === 'unhealthy' ? 'text-destructive border-destructive/40' : ''}">{containerInspect.State.Health.Status}</Badge>
</div>
{/if}
<!-- Security flags -->
{#if containerInspect.HostConfig?.Privileged || containerInspect.HostConfig?.ReadonlyRootfs || containerInspect.HostConfig?.CapAdd?.length || containerInspect.HostConfig?.CapDrop?.length}
<div class="pt-1 space-y-1.5">
<span class="text-xs font-semibold text-muted-foreground flex items-center gap-1.5"><ShieldAlert class="w-3.5 h-3.5" />Security</span>
<div class="flex flex-wrap gap-1">
{#if containerInspect.HostConfig.Privileged}<Badge variant="outline" class="text-xs text-amber-600 border-amber-600/40">privileged</Badge>{/if}
{#if containerInspect.HostConfig.ReadonlyRootfs}<Badge variant="outline" class="text-xs">read-only rootfs</Badge>{/if}
{#each containerInspect.HostConfig.CapAdd ?? [] as cap}<Badge variant="outline" class="text-xs text-green-600 border-green-600/40 font-mono">+{cap}</Badge>{/each}
{#each containerInspect.HostConfig.CapDrop ?? [] as cap}<Badge variant="outline" class="text-xs text-muted-foreground font-mono">-{cap}</Badge>{/each}
</div>
</div>
{/if}
<!-- Runtime details (log driver, stop signal, platform) -->
{#if containerInspect.HostConfig?.LogConfig?.Type || containerInspect.Config?.StopSignal || containerInspect.Platform}
<div class="pt-1 space-y-1.5">
<span class="text-xs font-semibold text-muted-foreground flex items-center gap-1.5"><Server class="w-3.5 h-3.5" />Runtime</span>
<dl class="grid grid-cols-[130px_1fr] gap-y-1 text-sm">
{#if containerInspect.HostConfig?.LogConfig?.Type}
<dt class="text-muted-foreground flex items-center gap-1.5"><ScrollText class="w-3.5 h-3.5" />Log driver</dt>
<dd class="font-mono text-xs">{containerInspect.HostConfig.LogConfig.Type}</dd>
{/if}
{#if containerInspect.Config?.StopSignal}
<dt class="text-muted-foreground">Stop signal</dt>
<dd class="font-mono text-xs">{containerInspect.Config.StopSignal}</dd>
{/if}
{#if containerInspect.Platform}
<dt class="text-muted-foreground flex items-center gap-1.5"><Cpu class="w-3.5 h-3.5" />Platform</dt>
<dd class="font-mono text-xs">{containerInspect.Platform}</dd>
{/if}
</dl>
</div>
{/if}
<!-- DNS / extra hosts -->
{#if containerInspect.HostConfig?.Dns?.length || containerInspect.HostConfig?.ExtraHosts?.length}
<div class="pt-1 space-y-1.5">
<span class="text-xs font-semibold text-muted-foreground flex items-center gap-1.5"><Globe class="w-3.5 h-3.5" />DNS &amp; hosts</span>
<div class="flex flex-wrap gap-1">
{#each containerInspect.HostConfig.Dns ?? [] as dns}<Badge variant="secondary" class="text-xs font-mono">DNS {dns}</Badge>{/each}
{#each containerInspect.HostConfig.ExtraHosts ?? [] as host}<Badge variant="secondary" class="text-xs font-mono">{host}</Badge>{/each}
</div>
</div>
{/if}
<!-- Networks -->
{#if containerInspect.NetworkSettings?.Networks && Object.keys(containerInspect.NetworkSettings.Networks).length}
<div class="pt-1 space-y-1.5">
<span class="text-xs font-semibold text-muted-foreground flex items-center gap-1.5"><Network class="w-3.5 h-3.5" />Networks</span>
<div class="flex flex-wrap gap-1">
{#each Object.entries(containerInspect.NetworkSettings.Networks) as [net, cfg]}
<Badge variant="secondary" class="text-xs"><Network class="w-3.5 h-3.5 mr-1" />{net}{(cfg as any)?.IPAddress ? ` (${(cfg as any).IPAddress})` : ''}</Badge>
{/each}
</div>
</div>
{/if}
<!-- Labels -->
{#if containerInspect.Config.Labels && Object.keys(containerInspect.Config.Labels).length}
<div class="pt-1 space-y-1.5">
<span class="text-xs font-semibold text-muted-foreground flex items-center gap-1.5"><Tag class="w-3.5 h-3.5" />Labels ({Object.keys(containerInspect.Config.Labels).length})</span>
<div class="max-h-40 overflow-y-auto text-sm font-mono bg-muted/20 rounded p-2 space-y-0.5">
{#each Object.entries(containerInspect.Config.Labels) as [key, value]}
<div class="truncate"><span class="text-muted-foreground">{key}</span>=<span>{value}</span></div>
{/each}
</div>
</div>
{/if}
<!-- Env vars (values masked) -->
{#if containerInspect.Config.Env?.length}
<div class="pt-1 space-y-1.5">
<span class="text-xs font-semibold text-muted-foreground flex items-center gap-1.5"><Variable class="w-3.5 h-3.5" />Environment variables ({containerInspect.Config.Env.length})</span>
<div class="max-h-40 overflow-y-auto text-sm font-mono bg-muted/20 rounded p-2 space-y-0.5">
{#each containerInspect.Config.Env as envVar}
{@const eqIdx = envVar.indexOf('=')}
<div class="truncate">
<span class="text-muted-foreground">{eqIdx > 0 ? envVar.slice(0, eqIdx) : envVar}</span>{#if eqIdx > 0}=<span>***</span>{/if}
</div>
{/each}
</div>
</div>
{/if}
</section>
{/if}
</div>
{:else}
<p class="text-sm text-muted-foreground p-4">No metadata available for this snapshot</p>
{/if}
</div>
{/if}
</Dialog.Content>
</Dialog.Root>
+347
View File
@@ -0,0 +1,347 @@
<script lang="ts">
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import { Loader2, FolderOpen, RotateCcw, Trash2, ArrowLeftRight, HardDrive, Archive, RefreshCw } from 'lucide-svelte';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import { formatDateTime } from '$lib/stores/settings';
import { formatBytes } from '$lib/utils/format';
import { getRepoTypeIcon } from '$lib/utils/backup';
import SnapshotBrowser from './SnapshotBrowser.svelte';
import RestoreModal from './RestoreModal.svelte';
import SnapshotDiffModal from '../backups/SnapshotDiffModal.svelte';
interface Props {
/** The backup target name (container or stack) whose snapshots to list. */
targetName: string;
type?: 'container' | 'stack';
environmentId?: number;
/** Whether this target has any backup config. With none there can be no
* snapshots, so we skip the (slow) per-repo listing entirely. */
hasBackups?: boolean;
/** This target's backup config (schedule) ids — used to pull per-snapshot
* stats (files new/changed, data added) from schedule executions, which are
* already recorded at backup time (no extra restic call). */
configIds?: number[];
/** Reports the loaded snapshot count so the parent can badge the tab. */
onCount?: (n: number) => void;
/** Reports loading state so the parent can show a spinner on the tab. */
onLoadingChange?: (loading: boolean) => void;
}
let { targetName, type = 'container', environmentId, hasBackups = true, configIds = [], onCount, onLoadingChange }: Props = $props();
interface Snapshot {
id: string;
shortId: string;
time: string;
tags?: string[];
_destinationId: number;
_destinationName: string;
_destinationRepository: string;
}
let loading = $state(true);
let snapshots = $state<Snapshot[]>([]);
let deletingSnapshot = $state<string | null>(null);
let confirmDeleteSnapshot = $state<string | null>(null);
// snapshotId → { filesNew, filesChanged, dataAdded } from schedule executions.
let stats = $state<Map<string, { filesNew: number; filesChanged: number; dataAdded: number }>>(new Map());
// Browse
let showBrowser = $state(false);
let browserDestId = $state(0);
let browserSnapshotId = $state('');
// Restore
let showRestore = $state(false);
let restoreDestId = $state(0);
let restoreSnapshotId = $state('');
// Diff (click one to select, another to compare)
let showDiff = $state(false);
let diffDestId = $state(0);
let diffSnapA = $state<any>({ id: '', shortId: '', time: '' });
let diffSnapB = $state<any>({ id: '', shortId: '', time: '' });
let diffPending = $state<Snapshot | null>(null);
// Repo filter (Option C). A target can be backed up to more than one repository,
// so its snapshots interleave here. `repoFilter` = the selected destination id, or
// null for "all". The chip row only appears when there is more than one repo.
let repoFilter = $state<number | null>(null);
// Distinct repos present in the loaded snapshots, with a count each.
const repoGroups = $derived.by(() => {
const m = new Map<number, { id: number; name: string; repository: string; count: number }>();
for (const s of snapshots) {
const g = m.get(s._destinationId);
if (g) g.count++;
else m.set(s._destinationId, { id: s._destinationId, name: s._destinationName, repository: s._destinationRepository, count: 1 });
}
return [...m.values()].sort((a, b) => a.name.localeCompare(b.name));
});
const visibleSnapshots = $derived(
repoFilter == null ? snapshots : snapshots.filter((s) => s._destinationId === repoFilter)
);
// A dropped repo filter (e.g. after a delete removed the last snapshot of a repo)
// falls back to "all" so the list never shows an empty filtered view.
$effect(() => {
if (repoFilter != null && !repoGroups.some((g) => g.id === repoFilter)) repoFilter = null;
});
export async function refresh() { await loadSnapshots(); }
async function loadSnapshots() {
// No backup config → no snapshots possible → skip the slow per-repo listing.
if (!hasBackups) { snapshots = []; onCount?.(0); loading = false; onLoadingChange?.(false); return; }
loading = true;
onLoadingChange?.(true);
try {
const destRes = await fetch('/api/backup/destinations');
const destinations: { id: number; name: string; repository: string }[] = destRes.ok ? await destRes.json() : [];
const nameTag = `dockhand:name=${targetName}`;
const all: Snapshot[] = [];
// Query every destination and keep only THIS target's snapshots (by tag).
await Promise.all(destinations.map(async (dest) => {
try {
const res = await fetch(`/api/backup/snapshots?destinationId=${dest.id}`);
if (!res.ok) return;
const data = await res.json();
const snaps: any[] = data.snapshots ?? data;
for (const s of snaps) {
if ((s.tags || []).some((t: string) => t === nameTag)) {
all.push({ ...s, _destinationId: dest.id, _destinationName: dest.name, _destinationRepository: dest.repository });
}
}
} catch { /* skip an unreachable destination */ }
}));
all.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime());
snapshots = all;
onCount?.(all.length);
// Per-snapshot stats from schedule executions (recorded at backup time).
const statMap = new Map<string, { filesNew: number; filesChanged: number; dataAdded: number }>();
await Promise.all(configIds.map(async (id) => {
try {
const r = await fetch(`/api/schedules/executions?scheduleType=backup&scheduleId=${id}&limit=100`);
if (!r.ok) return;
const d = await r.json();
for (const exec of d.executions || []) {
if (exec.details?.snapshotId) {
statMap.set(exec.details.snapshotId, {
filesNew: exec.details.filesNew ?? 0,
filesChanged: exec.details.filesChanged ?? 0,
dataAdded: exec.details.dataAdded ?? 0,
});
}
}
} catch { /* stats are best-effort */ }
}));
stats = statMap;
} catch {
snapshots = [];
toast.error('Failed to load snapshots');
} finally {
loading = false;
onLoadingChange?.(false);
}
}
function openBrowser(s: Snapshot) {
browserDestId = s._destinationId;
browserSnapshotId = s.id;
showBrowser = true;
}
function openRestore(s: Snapshot) {
restoreDestId = s._destinationId;
restoreSnapshotId = s.id;
showRestore = true;
}
function toggleDiff(s: Snapshot) {
if (diffPending?.id === s.id) { diffPending = null; return; }
if (diffPending) {
// Second selection → compare (older first). Both must share a destination.
if (diffPending._destinationId !== s._destinationId) {
toast.error('Compare needs two snapshots from the same repository');
diffPending = null;
return;
}
const pair = [diffPending, s].sort((a, b) => new Date(a.time).getTime() - new Date(b.time).getTime());
diffDestId = pair[0]._destinationId;
// SnapshotDiffModal reads `short_id`; our snapshots carry `shortId` — alias it.
diffSnapA = { ...pair[0], short_id: pair[0].shortId };
diffSnapB = { ...pair[1], short_id: pair[1].shortId };
showDiff = true;
diffPending = null;
} else {
diffPending = s;
}
}
async function deleteSnapshot(s: Snapshot) {
deletingSnapshot = s.id;
try {
const res = await fetch(`/api/backup/snapshots/${s.id}?destinationId=${s._destinationId}`, { method: 'DELETE' });
if (res.ok) {
toast.success('Snapshot deleted');
await loadSnapshots();
} else {
const data = await res.json();
toast.error(data.error || 'Failed to delete snapshot');
}
} catch {
toast.error('Failed to delete snapshot');
} finally {
deletingSnapshot = null;
confirmDeleteSnapshot = null;
}
}
// `hasBackups` arrives from the parent AFTER this panel mounts (the parent
// fetches its configs async), so it starts false and flips true once configs
// load. A plain onMount would run with hasBackups=false and early-return,
// leaving the list empty until a manual refresh. This effect loads as soon as
// hasBackups is true, exactly once — so the list fills in the background without
// a click, and switching sub-tabs stays cached. If there genuinely are no
// configs (hasBackups never true), onMount shows the empty state below.
let loadedWithBackups = $state(false);
$effect(() => {
if (hasBackups && !loadedWithBackups) {
loadedWithBackups = true;
void loadSnapshots();
}
});
// Only needed for the genuine no-configs case (hasBackups never flips true) —
// render the empty state instead of the initial loading spinner forever.
onMount(() => { if (!hasBackups) void loadSnapshots(); });
</script>
<!-- Refresh header only when there are rows to refresh. On the empty/loading state
it's hidden so this tab's empty state lines up vertically with the History tab's
(which has no header row) instead of sitting one row lower. -->
{#if snapshots.length > 0}
<div class="mb-2 flex items-center justify-end">
<button type="button" class="flex items-center gap-1.5 rounded p-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50" onclick={() => refresh()} disabled={loading} title="Refresh snapshots">
<RefreshCw class="h-3.5 w-3.5" />
</button>
</div>
{/if}
{#if loading && snapshots.length === 0}
<!-- First load only: a quiet spinner, no skeleton. On a refresh where rows already
exist we fall through and keep the real table visible (the header refresh icon
already signals progress). Matches the History tab's empty/loading treatment. -->
<div class="flex flex-col items-center justify-center py-10 text-center">
<Loader2 class="mb-3 h-8 w-8 animate-spin text-muted-foreground/40" />
<p class="text-sm text-muted-foreground">Loading snapshots…</p>
</div>
{:else if snapshots.length === 0}
<div class="flex flex-col items-center justify-center py-10 text-center">
<Archive class="mb-3 h-10 w-10 text-muted-foreground/40" />
<p class="text-sm text-muted-foreground">No snapshots yet for {targetName}.</p>
<p class="mt-1 text-xs text-muted-foreground">Run a backup from the Schedules tab to create one.</p>
</div>
{:else}
<!-- Repo filter chips (Option C) — only when the target spans more than one repo. -->
{#if repoGroups.length > 1}
<div class="mb-2 flex flex-wrap items-center gap-1.5">
<button
type="button"
class="inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs transition-colors {repoFilter == null ? 'border-primary/50 bg-primary/10 text-primary' : 'border-border text-muted-foreground hover:text-foreground'}"
onclick={() => (repoFilter = null)}
>
All repositories <span class="text-[10px] opacity-70">{snapshots.length}</span>
</button>
{#each repoGroups as g}
{@const GIcon = getRepoTypeIcon(g.repository)}
<button
type="button"
class="inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs transition-colors {repoFilter === g.id ? 'border-primary/50 bg-primary/10 text-primary' : 'border-border text-muted-foreground hover:text-foreground'}"
onclick={() => (repoFilter = g.id)}
>
<GIcon class="h-3 w-3 {repoFilter === g.id ? 'text-primary' : 'text-primary/70'}" />{g.name} <span class="text-[10px] opacity-70">{g.count}</span>
</button>
{/each}
</div>
{/if}
<div class="overflow-x-auto">
<table class="w-full text-xs">
<thead>
<tr class="border-b text-left text-muted-foreground">
<th class="py-1.5 pl-2 font-medium">Snapshot</th>
<th class="py-1.5 pl-2 font-medium">Taken</th>
<th class="py-1.5 pl-2 font-medium">Added</th>
<th class="py-1.5 pl-2 font-medium">Repository</th>
<th class="py-1.5 pr-3 text-right font-medium">Actions</th>
</tr>
</thead>
<tbody>
{#each visibleSnapshots as s}
{@const isDiffPending = diffPending?.id === s.id}
{@const RepoIcon = getRepoTypeIcon(s._destinationRepository)}
{@const st = stats.get(s.id)}
<tr class="border-b text-xs last:border-0 hover:bg-muted/30 {isDiffPending ? 'bg-primary/10' : ''}">
<td class="py-1.5 pl-2 font-mono text-muted-foreground">{s.shortId}</td>
<td class="py-1.5 pl-2">{formatDateTime(s.time)}</td>
<td class="py-1.5 pl-2 text-muted-foreground" title={st ? `${st.filesNew} new, ${st.filesChanged} changed files` : ''}>{st ? formatBytes(st.dataAdded) : '—'}</td>
<td class="py-1.5 pl-2 text-muted-foreground">
<span class="flex items-center gap-1.5"><RepoIcon class="h-3.5 w-3.5 text-primary/70" />{s._destinationName}</span>
</td>
<td class="px-3 py-1.5 text-right">
<div class="flex items-center justify-end gap-0.5">
{#if visibleSnapshots.length >= 2}
<button type="button" class="rounded p-1 transition-colors {isDiffPending ? 'bg-primary/20 text-primary' : 'hover:bg-muted'}" onclick={() => toggleDiff(s)} title={isDiffPending ? 'Cancel compare' : diffPending ? 'Compare with selected' : 'Compare'}>
<ArrowLeftRight class="h-3 w-3 {isDiffPending ? 'text-primary' : 'text-muted-foreground'}" />
</button>
{/if}
<button type="button" class="rounded p-1 transition-colors hover:bg-muted" onclick={() => openBrowser(s)} title="Browse files">
<FolderOpen class="h-3 w-3 text-muted-foreground" />
</button>
<button type="button" class="rounded p-1 transition-colors hover:bg-muted" onclick={() => openRestore(s)} title="Restore">
<RotateCcw class="h-3 w-3 text-muted-foreground" />
</button>
<ConfirmPopover
open={confirmDeleteSnapshot === s.id}
action="Delete"
itemType="snapshot"
itemName={s.shortId}
title="Delete snapshot"
position="left"
onConfirm={() => deleteSnapshot(s)}
onOpenChange={(open) => confirmDeleteSnapshot = open ? s.id : null}
>
{#snippet children({ open })}
{#if deletingSnapshot === s.id}
<Loader2 class="h-3 w-3 animate-spin" />
{:else}
<Trash2 class="h-3 w-3 {open ? 'text-destructive' : 'text-muted-foreground hover:text-destructive'}" />
{/if}
{/snippet}
</ConfirmPopover>
</div>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
{/if}
<SnapshotBrowser
bind:open={showBrowser}
destinationId={browserDestId}
snapshotId={browserSnapshotId}
{targetName}
targetType={type}
{environmentId}
/>
<RestoreModal
bind:open={showRestore}
destinationId={restoreDestId}
snapshotId={restoreSnapshotId}
containerName={targetName}
{environmentId}
onDone={loadSnapshots}
/>
<SnapshotDiffModal
bind:open={showDiff}
destinationId={diffDestId}
snapshotA={diffSnapA}
snapshotB={diffSnapB}
/>