Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: move frontend files into more maintainable structure
Kyle Mendell938882a17432
diff --git a/frontend/.fallowrc.json b/frontend/.fallowrc.jsonindex e36d47e0b..8fe5d8708 100644--- a/frontend/.fallowrc.json+++ b/frontend/.fallowrc.json@@ -3,6 +3,7 @@"entry": ["src/routes/**/*.{svelte,ts,js}","src/hooks.*.ts",+ "src/service-worker/index.ts","src/lib/paraglide/messages/_index.js","src/lib/index.ts","src/lib/components/**/index.ts"@@ -32,6 +33,10 @@{"file": "src/lib/components/code-editor/analysis/compose-schema.ts","exports": ["getComposeSchemaContext", "getCompletionOptionsForPath", "getEnumValueCompletions", "getSchemaDocForPath"]+ },+ {+ "file": "src/lib/icons/index.ts",+ "exports": ["LayoutGridIcon", "LayoutListIcon", "MonitorSpeakerIcon"]}],"ignoreExportsUsedInFile": {diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex 7de88504d..098990666 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -1527,6 +1527,9 @@"security_trivy_network_help": "Leave this on Auto to inherit Arcane's network. Choose host, none, bridge, or a custom Docker network only when you need to override it.","security_trivy_network_auto_description": "Inherit Arcane's network","security_trivy_network_current_value_note": "Current configured value",+ "security_trivy_network_bridge": "bridge",+ "security_trivy_network_host": "host",+ "security_trivy_network_none": "none","security_trivy_security_opts_label": "Trivy Security Options","security_trivy_security_opts_description": "Docker security options applied to Trivy scan containers.","security_trivy_security_opts_help": "Use commas or new lines to separate entries. Prefer security options such as label=disable before enabling privileged mode.",@@ -2320,6 +2323,19 @@"notifications_discord_title": "Discord","notifications_telegram_title": "Telegram","notifications_telegram_description": "Send notifications via Telegram bot",+ "notifications_telegram_bot_token_label": "Bot Token",+ "notifications_telegram_bot_token_placeholder": "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11",+ "notifications_telegram_bot_token_help": "The bot token from @BotFather",+ "notifications_telegram_chat_ids_label": "Chat IDs",+ "notifications_telegram_chat_ids_placeholder": "@channel, 123456789, @another_channel",+ "notifications_telegram_chat_ids_help": "Comma-separated list of chat IDs or @channel names",+ "notifications_telegram_title_label": "Title (Optional)",+ "notifications_telegram_title_placeholder": "Arcane Notifications",+ "notifications_telegram_title_help": "Custom title for notifications",+ "notifications_telegram_preview_label": "Enable Link Previews",+ "notifications_telegram_preview_description": "Show web page previews for URLs in messages",+ "notifications_telegram_sound_label": "Enable Notification Sound",+ "notifications_telegram_sound_description": "Play notification sound when messages are received","notifications_ntfy_title": "Ntfy","notifications_pushover_title": "Pushover","notifications_gotify_title": "Gotify",@@ -2353,6 +2369,13 @@"notifications_email_to_addresses_label": "To Addresses","notifications_email_to_addresses_placeholder": "[email protected], [email protected]","notifications_email_to_addresses_help": "Comma-separated list of email addresses to send notifications to",+ "notifications_email_invalid_addresses": "Invalid email addresses: {addresses}",+ "notifications_email_tls_none": "None",+ "notifications_email_tls_starttls": "StartTLS",+ "notifications_email_tls_ssl": "SSL/TLS",+ "notifications_email_auth_plain": "PLAIN",+ "notifications_email_auth_login": "LOGIN",+ "notifications_email_auth_cram_md5": "CRAM-MD5","notifications_saved_failed": "Failed to save {provider} settings: {error}","notifications_test_success": "Test notification sent successfully via {provider}","notifications_test_failed": "Failed to send test notification: {error}",@@ -2449,6 +2472,13 @@"notifications_ntfy_password_help": "Password for authentication (if required by server)","priority": "Priority","notifications_ntfy_priority_help": "Notification priority level (Min=1, Low=2, Default=3, High=4, Max/Urgent=5)",+ "notifications_priority_min": "Min",+ "notifications_priority_low": "Low",+ "notifications_priority_default": "Default",+ "notifications_priority_high": "High",+ "notifications_priority_normal": "Normal",+ "notifications_priority_max": "Max",+ "notifications_priority_max_urgent": "Max/Urgent","title_optional": "Title (Optional)","container_update_placeholder": "Container Update","optional_title_override_for_notifications": "Optional title override for notifications",@@ -3117,6 +3147,7 @@"env_remote_docker_host": "Remote Docker Host","sidebar_toggle_submenu": "Toggle submenu","common_account": "Account",+ "account_loading": "Loading account...","common_log_out": "Log out","terminal_reconnect": "Reconnect shell","sidebar_toggle": "Toggle Sidebar",@@ -3145,6 +3176,11 @@"volume_search_files": "Search files","account_member_since": "Member since","account_roles_and_access": "Roles & access",+ "account_role_administrator": "Administrator",+ "account_role_editor": "Editor",+ "account_role_deployer": "Deployer",+ "account_role_viewer": "Viewer",+ "account_permissions_summary": "Global permissions: {globalCount}; environments: {environmentCount}.","account_role_environment": "Environment: {env}","account_global_scope": "Global scope","account_via_sso": "· via SSO",diff --git a/frontend/src/lib/components/action-buttons.svelte b/frontend/src/lib/components/action-buttons.svelteindex a88652b09..f8a913996 100644--- a/frontend/src/lib/components/action-buttons.svelte+++ b/frontend/src/lib/components/action-buttons.svelte@@ -389,8 +389,9 @@await refreshAll();itemState = 'running';onActionComplete('running');- } catch (e: any) {- const message = e?.message || m.common_action_failed_with_type({ action: m.common_start(), type });+ } catch (error) {+ const message =+ error instanceof Error ? error.message : m.common_action_failed_with_type({ action: m.common_start(), type });if (watch) {operationWatchStore.fail(message);} else {@@ -460,20 +461,16 @@}try {- projectService- .pullProjectImages(id, watch ? (frame: unknown) => operationWatchStore.onLine(frame) : () => {})- .then(async () => {- await refreshAll();- onActionComplete(itemState);- })- .catch((error: any) => {- const message = error?.message || m.images_pull_failed();- if (watch) {- operationWatchStore.fail(message);- } else {- toast.error(message);- }- });+ await projectService.pullProjectImages(id, watch ? (frame: unknown) => operationWatchStore.onLine(frame) : () => {});+ await refreshAll();+ onActionComplete(itemState);+ } catch (error) {+ const message = error instanceof Error ? error.message : m.images_pull_failed();+ if (watch) {+ operationWatchStore.fail(message);+ } else {+ toast.error(message);+ }} finally {setLoading('pull', false);}@@ -484,23 +481,19 @@try {const buildProvider = projectBuildProvider;- projectService- .buildProjectImages(- id,- {- provider: buildProvider,- push: buildProvider === 'depot',- load: buildProvider !== 'depot'- },- () => {}- )- .then(async () => {- await refreshAll();- })- .catch((error: any) => {- const message = error?.message || m.build_failed();- toast.error(message);- });+ await projectService.buildProjectImages(+ id,+ {+ provider: buildProvider,+ push: buildProvider === 'depot',+ load: buildProvider !== 'depot'+ },+ () => {}+ );+ await refreshAll();+ } catch (error) {+ const message = error instanceof Error ? error.message : m.build_failed();+ toast.error(message);} finally {setLoading('build', false);}diff --git a/frontend/src/lib/components/activity/activity-completion-toasts.ts b/frontend/src/lib/components/activity/activity-completion-toasts.tsindex b85491cf7..8fe4f8f5d 100644--- a/frontend/src/lib/components/activity/activity-completion-toasts.ts+++ b/frontend/src/lib/components/activity/activity-completion-toasts.ts@@ -2,7 +2,6 @@ import { toast } from 'svelte-sonner';import { PersistedState } from 'runed';import { m } from '#lib/paraglide/messages';import type { Activity, ActivityType } from '#lib/types/activity.type';-import { activityStore } from '#lib/stores/activity.store.svelte';import { activityTypeLabel } from './activity-labels';/**@@ -41,7 +40,10 @@ const LONG_RUNNING_TYPES = new Set<ActivityType>(['system_prune']);-let pending: Activity[] = [];+type ActivityToastNavigator = (activityId?: string, batchId?: string) => void;+type PendingActivityToast = { activity: Activity; navigate: ActivityToastNavigator };++let pending: PendingActivityToast[] = [];let debounceTimer: ReturnType<typeof setTimeout> | null = null;let hardFlushTimer: ReturnType<typeof setTimeout> | null = null;const shownActivityIds = new Map<string, number>();@@ -66,14 +68,14 @@ function wasToastShownInternal(activityId: string): boolean {return shownAt !== undefined && performance.now() - shownAt <= SHOWN_SUPPRESSION_MS;}-export function queueActivityCompletionToast(activity: Activity) {+export function queueActivityCompletionToast(activity: Activity, navigate: ActivityToastNavigator) {if (!activityCompletionToastsEnabled.current) {return;}if (!LONG_RUNNING_TYPES.has(activity.type)) {return;}- pending.push(activity);+ pending.push({ activity, navigate });if (debounceTimer) {clearTimeout(debounceTimer);}@@ -106,19 +108,20 @@ function flushInternal() {return;}- const groups = new Map<string, Activity[]>();- for (const activity of items) {+ const groups = new Map<string, PendingActivityToast[]>();+ for (const item of items) {+ const { activity } = item;const key = activity.batchId ?? `${activity.type}:${activity.status}`;const group = groups.get(key);if (group) {- group.push(activity);+ group.push(item);} else {- groups.set(key, [activity]);+ groups.set(key, [item]);}}for (const members of groups.values()) {// A response toast (single or bulk summary) already covered this work.- if (members.some((activity) => wasToastShownInternal(activity.id))) {+ if (members.some(({ activity }) => wasToastShownInternal(activity.id))) {continue;}emitGroupToastInternal(members);@@ -131,8 +134,9 @@ function shortenDockerIdInternal(value: string): string {return /^[0-9a-f]{25,64}$/i.test(value) ? value.slice(0, 12) : value;}-function emitGroupToastInternal(members: Activity[]) {- const first = members[0];+function emitGroupToastInternal(members: PendingActivityToast[]) {+ const firstItem = members[0];+ const first = firstItem?.activity;if (!first) {return;}@@ -140,7 +144,7 @@ function emitGroupToastInternal(members: Activity[]) {if (members.length === 1) {const rawName = first.resourceName || first.resourceId || '';const name = rawName ? shortenDockerIdInternal(rawName) : activityTypeLabel(first.type);- const action = viewActionInternal(first.id, first.batchId);+ const action = viewActionInternal(first.id, first.batchId, firstItem.navigate);if (first.status === 'failed') {toast.error(m.activity_toast_failed({ name }), { action });} else {@@ -150,8 +154,8 @@ function emitGroupToastInternal(members: Activity[]) {}const type = activityTypeLabel(first.type);- const failed = members.filter((activity) => activity.status === 'failed').length;- const action = viewActionInternal(undefined, first.batchId);+ const failed = members.filter(({ activity }) => activity.status === 'failed').length;+ const action = viewActionInternal(undefined, first.batchId, firstItem.navigate);if (failed > 0) {toast.error(m.activity_toast_batch_partial({ type, failed, total: members.length }), { action });} else {@@ -159,9 +163,9 @@ function emitGroupToastInternal(members: Activity[]) {}}-function viewActionInternal(activityId: string | undefined, batchId: string | undefined) {+function viewActionInternal(activityId: string | undefined, batchId: string | undefined, navigate: ActivityToastNavigator) {return {label: m.activity_toast_view(),- onClick: () => activityStore.openCenter(activityId, batchId)+ onClick: () => navigate(activityId, batchId)};}diff --git a/frontend/src/lib/components/activity/activity-output.svelte b/frontend/src/lib/components/activity/activity-output.svelteindex d0bfb3020..793da72fb 100644--- a/frontend/src/lib/components/activity/activity-output.svelte+++ b/frontend/src/lib/components/activity/activity-output.svelte@@ -2,31 +2,10 @@import type { ActivityMessage } from '#lib/types/activity.type';import { ansiToHtml } from '#lib/utils/formatting';import { cn } from '#lib/utils';+ import PinnedScrollRegion from '#lib/components/pinned-scroll-region.svelte';let { messages }: { messages: ActivityMessage[] } = $props();- let container = $state<HTMLElement | null>(null);- let pinnedToBottom = $state(true);-- function handleScroll() {- if (!container) {- return;- }- pinnedToBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 24;- }-- $effect(() => {- messages.length;- if (!container || !pinnedToBottom) {- return;- }- queueMicrotask(() => {- if (container && pinnedToBottom) {- container.scrollTop = container.scrollHeight;- }- });- });-function lineClassInternal(level: ActivityMessage['level']): string {switch (level) {case 'error':@@ -39,11 +18,11 @@}</script>-<div bind:this={container} onscroll={handleScroll} class="max-h-80 min-h-40 overflow-auto px-5 py-4">+<PinnedScrollRegion itemCount={messages.length} class="max-h-80 min-h-40 overflow-auto px-5 py-4">{#each messages as message (message.id)}<!-- eslint-disable-next-line svelte/no-at-html-tags -- ansiToHtml escapes markup before adding color spans --><div class={cn('wrap-break-word whitespace-pre-wrap', lineClassInternal(message.level))}>{@html ansiToHtml(message.message)}</div>{/each}-</div>+</PinnedScrollRegion>diff --git a/frontend/src/lib/components/arcane-table/arcane-table.svelte b/frontend/src/lib/components/arcane-table/arcane-table.svelteindex c4182621f..2df211680 100644--- a/frontend/src/lib/components/arcane-table/arcane-table.svelte+++ b/frontend/src/lib/components/arcane-table/arcane-table.svelte@@ -386,6 +386,7 @@const item = row.original as TData;const value = accessorKey ? row.getValue(accessorKey) : getValue?.();if (spec.cell) return renderSnippet(spec.cell, { row, item, value });+ if (spec.cellComponent) return renderComponent(spec.cellComponent, { value });return renderComponent(ArcaneTableCell, { value });},enableSorting: !!spec.sortable || !!spec.clientSort,diff --git a/frontend/src/lib/components/arcane-table/arcane-table.types.svelte.ts b/frontend/src/lib/components/arcane-table/arcane-table.types.svelte.tsindex b302e8533..1ba891a9d 100644--- a/frontend/src/lib/components/arcane-table/arcane-table.types.svelte.ts+++ b/frontend/src/lib/components/arcane-table/arcane-table.types.svelte.ts@@ -26,7 +26,7 @@ export type ColumnAlign = 'left' | 'center' | 'right';export type ColumnSpec<T extends RowData> = {accessorKey?: keyof T & string;- accessorFn?: (row: T) => any;+ accessorFn?: (row: T) => unknown;id?: string;title: string;hidden?: boolean;@@ -37,6 +37,8 @@ export type ColumnSpec<T extends RowData> = {*/clientSort?: boolean;cell?: Snippet<[{ row: ArcaneRow<T>; item: T; value: unknown }]>;+ /** Render a shared value-only Svelte component without a per-table wrapper snippet. */+ cellComponent?: Component<{ value: unknown }>;header?: Snippet<[{ column: ArcaneColumn<T>; title: string; class?: string }]>;class?: string;filterFn?: ArcaneFilterFn<T>;@@ -153,7 +155,7 @@ export type BulkAction = {disabled?: boolean;disabledReason?: string;loading?: boolean;- icon?: any;+ icon?: Component;};// Grouping typesdiff --git a/frontend/src/lib/components/arcane-table/table-features.ts b/frontend/src/lib/components/arcane-table/table-features.tsindex 4526b8acf..0e1688d23 100644--- a/frontend/src/lib/components/arcane-table/table-features.ts+++ b/frontend/src/lib/components/arcane-table/table-features.ts@@ -8,7 +8,7 @@ import {type SvelteTable} from '@tanstack/svelte-table';import { metaHelper } from '@tanstack/table-core';-import type { Cell, Column, ColumnDef, FilterFn, Header, Row, RowData, Table } from '@tanstack/table-core';+import type { Cell, Column, ColumnDef, FilterFn, Row, RowData, Table } from '@tanstack/table-core';// Type-only cycle with arcane-table.types.svelte.ts (which imports only types from here) — erased at emit.import type { ColumnAlign, ColumnWidth, FilterOption } from './arcane-table.types.svelte';@@ -67,7 +67,6 @@ export type ArcaneColumnDef<T extends RowData> = ColumnDef<ArcaneFeatures, T>;export type ArcaneRow<T extends RowData> = Row<ArcaneFeatures, T>;export type ArcaneColumn<T extends RowData> = Column<ArcaneFeatures, T>;export type ArcaneCell<T extends RowData> = Cell<ArcaneFeatures, T>;-export type ArcaneHeader<T extends RowData> = Header<ArcaneFeatures, T>;/** Core table type — used for callback contexts and read-only method access. */export type ArcaneTable<T extends RowData> = Table<ArcaneFeatures, T>;/** The Svelte adapter table instance — adds reactive `.state` (read state slices). */diff --git a/frontend/src/lib/components/containers/container-form/container-form-state.ts b/frontend/src/lib/components/containers/container-form/container-form-state.tsindex 75bf8679f..48df6cc8e 100644--- a/frontend/src/lib/components/containers/container-form/container-form-state.ts+++ b/frontend/src/lib/components/containers/container-form/container-form-state.ts@@ -100,7 +100,7 @@ export type ContainerFormRows = {// Splits a command string into words, honoring single/double quotes so// entries like `sh -c "echo hi"` survive the round-trip.-export function splitShellWords(input: string): string[] {+function splitShellWords(input: string): string[] {const words: string[] = [];const re = /"([^"]*)"|'([^']*)'|(\S+)/g;for (const match of input.matchAll(re)) {diff --git a/frontend/src/lib/components/operation-watch-dialog.svelte b/frontend/src/lib/components/operation-watch-dialog.svelteindex 2ea319a7f..0746fd200 100644--- a/frontend/src/lib/components/operation-watch-dialog.svelte+++ b/frontend/src/lib/components/operation-watch-dialog.svelte@@ -4,6 +4,7 @@import { operationWatchStore } from '#lib/stores/operation-watch.store.svelte';import { ansiToHtml } from '#lib/utils/formatting';import { m } from '#lib/paraglide/messages';+ import PinnedScrollRegion from '#lib/components/pinned-scroll-region.svelte';// Dismissing an attached session stops the project (the Ctrl-C of a// non-detached compose up), so every close attempt confirms first.@@ -21,28 +22,6 @@}});});-- let container = $state<HTMLElement | null>(null);- let pinnedToBottom = $state(true);-- function handleScroll() {- if (!container) {- return;- }- pinnedToBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 24;- }-- $effect(() => {- operationWatchStore.lines.length;- if (!container || !pinnedToBottom) {- return;- }- queueMicrotask(() => {- if (container && pinnedToBottom) {- container.scrollTop = container.scrollHeight;- }- });- });</script><ResponsiveDialog@@ -52,9 +31,8 @@class="min-h-0"><div class="space-y-3 pb-4">- <div- bind:this={container}- onscroll={handleScroll}+ <PinnedScrollRegion+ itemCount={operationWatchStore.lines.length}class="max-h-[70vh] min-h-[280px] overflow-auto rounded-lg border border-border/50 bg-zinc-950 p-4 font-mono text-[12px] leading-relaxed text-zinc-100">{#each operationWatchStore.lines as line, idx (idx)}@@ -66,7 +44,7 @@{m.activity_output_loading()}</div>{/if}- </div>+ </PinnedScrollRegion>{#if operationWatchStore.error}<div class="rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">diff --git a/frontend/src/lib/components/pinned-scroll-region.svelte b/frontend/src/lib/components/pinned-scroll-region.sveltenew file mode 100644index 000000000..7053be6d5--- /dev/null+++ b/frontend/src/lib/components/pinned-scroll-region.svelte@@ -0,0 +1,36 @@+<script lang="ts">+ import { cn } from '#lib/utils';+ import type { Snippet } from 'svelte';+ import type { Attachment } from 'svelte/attachments';++ interface Props {+ itemCount: number;+ threshold?: number;+ class?: string;+ children: Snippet;+ }++ let { itemCount, threshold = 24, class: className, children }: Props = $props();+ let pinnedToBottom = $state(true);++ const pinToBottom: Attachment<HTMLElement> = (node) => {+ function handleScroll() {+ pinnedToBottom = node.scrollHeight - node.scrollTop - node.clientHeight < threshold;+ }++ node.addEventListener('scroll', handleScroll, { passive: true });+ $effect(() => {+ void itemCount;+ if (!pinnedToBottom) return;+ queueMicrotask(() => {+ if (node.isConnected && pinnedToBottom) node.scrollTop = node.scrollHeight;+ });+ });++ return () => node.removeEventListener('scroll', handleScroll);+ };+</script>++<div class={cn(className)} {@attach pinToBottom}>+ {@render children()}+</div>diff --git a/frontend/src/lib/components/resource-detail/key-value-card.svelte b/frontend/src/lib/components/resource-detail/key-value-card.svelteindex 13183a220..f31d60c92 100644--- a/frontend/src/lib/components/resource-detail/key-value-card.svelte+++ b/frontend/src/lib/components/resource-detail/key-value-card.svelte@@ -9,6 +9,8 @@valueClass?: string;valueTitle?: string;cardClass?: string;+ contentClass?: string;+ variant?: 'default' | 'subtle' | 'outlined';}let {@@ -17,12 +19,14 @@labelClass = 'text-muted-foreground text-xs font-semibold tracking-wide break-all uppercase',valueClass = 'text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all',valueTitle,- cardClass+ cardClass,+ contentClass,+ variant = 'subtle'}: Props = $props();</script>{#snippet content()}- <Card.Content class="flex flex-col gap-2 p-4">+ <Card.Content class={contentClass ?? 'flex flex-col gap-2 p-4'}><div class={labelClass}>{label}</div><div class={valueClass} title={valueTitle}>{@render children()}@@ -30,6 +34,6 @@</Card.Content>{/snippet}-<Card.Root variant="subtle" class={cardClass}>+<Card.Root {variant} class={cardClass}>{@render content()}</Card.Root>diff --git a/frontend/src/lib/components/section-card.svelte b/frontend/src/lib/components/section-card.sveltenew file mode 100644index 000000000..d5a204b67--- /dev/null+++ b/frontend/src/lib/components/section-card.svelte@@ -0,0 +1,51 @@+<script lang="ts">+ import * as Card from '#lib/components/ui/card';+ import type { IconType } from '#lib/icons';+ import { cn } from '#lib/utils';+ import type { Snippet } from 'svelte';++ interface Props {+ title: string;+ description?: string;+ icon?: IconType;+ iconVariant?: 'primary' | 'emerald' | 'red' | 'amber' | 'blue' | 'purple' | 'cyan' | 'orange' | 'indigo' | 'pink';+ class?: string;+ headerClass?: string;+ contentClass?: string;+ actions?: Snippet;+ children: Snippet;+ }++ let {+ title,+ description,+ icon,+ iconVariant = 'primary',+ class: className,+ headerClass,+ contentClass = 'p-4',+ actions,+ children+ }: Props = $props();+</script>++<Card.Root class={className}>+ <Card.Header {icon} {iconVariant} class={headerClass}>+ <div class="flex min-w-0 flex-1 flex-col space-y-1.5">+ <Card.Title>+ <h2>{title}</h2>+ </Card.Title>+ {#if description}+ <Card.Description>{description}</Card.Description>+ {/if}+ </div>+ {#if actions}+ <Card.Action class={cn(icon && 'top-4 right-4')}>+ {@render actions()}+ </Card.Action>+ {/if}+ </Card.Header>+ <Card.Content class={contentClass}>+ {@render children()}+ </Card.Content>+</Card.Root>diff --git a/frontend/src/lib/components/settings/image-patch-settings.svelte b/frontend/src/lib/components/settings/image-patch-settings.svelteindex 957d10027..d69f3bc4d 100644--- a/frontend/src/lib/components/settings/image-patch-settings.svelte+++ b/frontend/src/lib/components/settings/image-patch-settings.svelte@@ -1,11 +1,11 @@<script lang="ts">- import * as Card from '#lib/components/ui/card/index.js';import { Switch } from '#lib/components/ui/switch/index.js';import TextInputWithLabel from '#lib/components/form/text-input-with-label.svelte';import SettingsRow from '#lib/components/settings/settings-row.svelte';import { SecurityIcon } from '#lib/icons';import { m } from '#lib/paraglide/messages';import type { Readable } from 'svelte/store';+ import SectionCard from '#lib/components/section-card.svelte';type ImagePatchFormValues = {imagePatchSuffix: string;@@ -28,51 +28,47 @@let { formInputs }: { formInputs: ImagePatchFormInputs } = $props();</script>-<Card.Root class="flex flex-col">- <Card.Header icon={SecurityIcon}>- <div class="flex flex-col space-y-1.5">- <Card.Title>- <h2>{m.security_image_patching_heading()}</h2>- </Card.Title>- </div>- </Card.Header>- <Card.Content class="divide-y divide-border/40 lg:p-6 lg:pt-0 [&>*]:py-5 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0">- <SettingsRow- label={m.security_image_auto_patch_enabled_label()}- description={m.security_image_auto_patch_enabled_description()}- layout="inline"- >- <Switch id="imageAutoPatchEnabledSwitch" bind:checked={$formInputs.imageAutoPatchEnabled.value} />- </SettingsRow>+<SectionCard+ title={m.security_image_patching_heading()}+ icon={SecurityIcon}+ class="flex flex-col"+ contentClass="divide-y divide-border/40 lg:p-6 lg:pt-0 [&>*]:py-5 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0"+>+ <SettingsRow+ label={m.security_image_auto_patch_enabled_label()}+ description={m.security_image_auto_patch_enabled_description()}+ layout="inline"+ >+ <Switch id="imageAutoPatchEnabledSwitch" bind:checked={$formInputs.imageAutoPatchEnabled.value} />+ </SettingsRow>- <SettingsRow- label={m.security_image_patch_all_platforms_label()}- description={m.security_image_patch_all_platforms_description()}- layout="inline"- >- <Switch id="imagePatchAllPlatformsSwitch" bind:checked={$formInputs.imagePatchAllPlatforms.value} />- </SettingsRow>+ <SettingsRow+ label={m.security_image_patch_all_platforms_label()}+ description={m.security_image_patch_all_platforms_description()}+ layout="inline"+ >+ <Switch id="imagePatchAllPlatformsSwitch" bind:checked={$formInputs.imagePatchAllPlatforms.value} />+ </SettingsRow>- <div class="max-w-xl">- <TextInputWithLabel- bind:value={$formInputs.imagePatchSuffix.value}- error={$formInputs.imagePatchSuffix.error}- label={m.security_image_patch_suffix_label()}- description={m.security_image_patch_suffix_description()}- placeholder="patched"- type="text"- />- </div>+ <div class="max-w-xl">+ <TextInputWithLabel+ bind:value={$formInputs.imagePatchSuffix.value}+ error={$formInputs.imagePatchSuffix.error}+ label={m.security_image_patch_suffix_label()}+ description={m.security_image_patch_suffix_description()}+ placeholder="patched"+ type="text"+ />+ </div>- <div class="max-w-xs">- <TextInputWithLabel- bind:value={$formInputs.imagePatchTimeoutSec.value}- error={$formInputs.imagePatchTimeoutSec.error}- label={m.security_image_patch_timeout_label()}- description={m.security_image_patch_timeout_description()}- placeholder="600"- type="number"- />- </div>- </Card.Content>-</Card.Root>+ <div class="max-w-xs">+ <TextInputWithLabel+ bind:value={$formInputs.imagePatchTimeoutSec.value}+ error={$formInputs.imagePatchTimeoutSec.error}+ label={m.security_image_patch_timeout_label()}+ description={m.security_image_patch_timeout_description()}+ placeholder="600"+ type="number"+ />+ </div>+</SectionCard>diff --git a/frontend/src/lib/components/settings/lifecycle-security-settings.svelte b/frontend/src/lib/components/settings/lifecycle-security-settings.svelteindex 10bdbd410..06812a143 100644--- a/frontend/src/lib/components/settings/lifecycle-security-settings.svelte+++ b/frontend/src/lib/components/settings/lifecycle-security-settings.svelte@@ -1,12 +1,12 @@<script lang="ts">import * as Alert from '#lib/components/ui/alert';- import * as Card from '#lib/components/ui/card/index.js';import { Switch } from '#lib/components/ui/switch/index.js';import TextInputWithLabel from '#lib/components/form/text-input-with-label.svelte';import SettingsRow from '#lib/components/settings/settings-row.svelte';import { AlertIcon, CodeIcon } from '#lib/icons';import { m } from '#lib/paraglide/messages';import type { Readable } from 'svelte/store';+ import SectionCard from '#lib/components/section-card.svelte';type LifecycleSecurityFormValues = {lifecycleEnabled: boolean;@@ -28,53 +28,49 @@let { formInputs }: { formInputs: LifecycleSecurityFormInputs } = $props();</script>-<Card.Root class="flex flex-col">- <Card.Header icon={CodeIcon}>- <div class="flex flex-col space-y-1.5">- <Card.Title>- <h2>{m.security_lifecycle_hooks_heading()}</h2>- </Card.Title>- </div>- </Card.Header>- <Card.Content class="divide-y divide-border/40 lg:p-6 lg:pt-0 [&>*]:py-5 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0">- <SettingsRow- label={m.security_lifecycle_enabled_label()}- description={m.security_lifecycle_enabled_description()}- layout="inline"- >- <Switch id="lifecycleEnabledSwitch" bind:checked={$formInputs.lifecycleEnabled.value} />- </SettingsRow>+<SectionCard+ title={m.security_lifecycle_hooks_heading()}+ icon={CodeIcon}+ class="flex flex-col"+ contentClass="divide-y divide-border/40 lg:p-6 lg:pt-0 [&>*]:py-5 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0"+>+ <SettingsRow+ label={m.security_lifecycle_enabled_label()}+ description={m.security_lifecycle_enabled_description()}+ layout="inline"+ >+ <Switch id="lifecycleEnabledSwitch" bind:checked={$formInputs.lifecycleEnabled.value} />+ </SettingsRow>- <div class="max-w-xl">- <TextInputWithLabel- bind:value={$formInputs.lifecycleDefaultRunnerImage.value}- error={$formInputs.lifecycleDefaultRunnerImage.error}- label={m.security_lifecycle_runner_image_label()}- description={m.security_lifecycle_runner_image_description()}- helpText={m.security_lifecycle_runner_image_help()}- placeholder="alpine:latest"- type="text"- />- </div>+ <div class="max-w-xl">+ <TextInputWithLabel+ bind:value={$formInputs.lifecycleDefaultRunnerImage.value}+ error={$formInputs.lifecycleDefaultRunnerImage.error}+ label={m.security_lifecycle_runner_image_label()}+ description={m.security_lifecycle_runner_image_description()}+ helpText={m.security_lifecycle_runner_image_help()}+ placeholder="alpine:latest"+ type="text"+ />+ </div>- <div class="max-w-xs">- <TextInputWithLabel- bind:value={$formInputs.lifecycleMaxTimeoutSec.value}- error={$formInputs.lifecycleMaxTimeoutSec.error}- label={m.security_lifecycle_max_timeout_label()}- description={m.security_lifecycle_max_timeout_description()}- helpText={m.security_lifecycle_max_timeout_help()}- type="number"- />- </div>+ <div class="max-w-xs">+ <TextInputWithLabel+ bind:value={$formInputs.lifecycleMaxTimeoutSec.value}+ error={$formInputs.lifecycleMaxTimeoutSec.error}+ label={m.security_lifecycle_max_timeout_label()}+ description={m.security_lifecycle_max_timeout_description()}+ helpText={m.security_lifecycle_max_timeout_help()}+ type="number"+ />+ </div>- <div>- <Alert.Root variant="warning" class="py-2 [&>svg]:top-2">- <AlertIcon class="size-4" />- <Alert.Description class="text-xs">- {m.security_lifecycle_hooks_note()}- </Alert.Description>- </Alert.Root>- </div>- </Card.Content>-</Card.Root>+ <div>+ <Alert.Root variant="warning" class="py-2 [&>svg]:top-2">+ <AlertIcon class="size-4" />+ <Alert.Description class="text-xs">+ {m.security_lifecycle_hooks_note()}+ </Alert.Description>+ </Alert.Root>+ </div>+</SectionCard>diff --git a/frontend/src/lib/components/settings/trivy-security-settings.svelte b/frontend/src/lib/components/settings/trivy-security-settings.svelteindex 0a5ebed45..ff55df466 100644--- a/frontend/src/lib/components/settings/trivy-security-settings.svelte+++ b/frontend/src/lib/components/settings/trivy-security-settings.svelte@@ -1,5 +1,4 @@<script lang="ts">- import * as Card from '#lib/components/ui/card/index.js';import { Switch } from '#lib/components/ui/switch/index.js';import { Textarea } from '#lib/components/ui/textarea/index.js';import * as Alert from '#lib/components/ui/alert';@@ -13,6 +12,7 @@import type { SearchPaginationSortRequest } from '#lib/types/shared';import type { Settings } from '#lib/types/settings';import type { Readable } from 'svelte/store';+ import SectionCard from '#lib/components/section-card.svelte';type TrivySecurityFormValues = Pick<Settings,@@ -61,9 +61,9 @@label: m.auto(),description: m.security_trivy_network_auto_description()},- { value: 'bridge', label: 'bridge' },- { value: 'host', label: 'host' },- { value: 'none', label: 'none' }+ { value: 'bridge', label: m.security_trivy_network_bridge() },+ { value: 'host', label: m.security_trivy_network_host() },+ { value: 'none', label: m.security_trivy_network_none() }];let customTrivyNetworkOptions = $state<TrivyNetworkOption[]>([]);@@ -149,170 +149,166 @@});</script>-<Card.Root class="flex flex-col">- <Card.Header icon={SecurityIcon}>- <div class="flex flex-col space-y-1.5">- <Card.Title>- <h2>{m.security_vulnerability_scanning_heading()}</h2>- </Card.Title>- </div>- </Card.Header>- <Card.Content class="divide-y divide-border/40 lg:p-6 lg:pt-0 [&>*]:py-5 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0">- <div class="max-w-xl">- <TextInputWithLabel- bind:value={$formInputs.trivyImage.value}- error={$formInputs.trivyImage.error}- disabled={true}- label={m.security_trivy_image_label()}- description={m.security_trivy_image_description()}- helpText={m.security_trivy_image_note()}- placeholder="ghcr.io/getarcaneapp/tools:latest"- type="text"- />- </div>+<SectionCard+ title={m.security_vulnerability_scanning_heading()}+ icon={SecurityIcon}+ class="flex flex-col"+ contentClass="divide-y divide-border/40 lg:p-6 lg:pt-0 [&>*]:py-5 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0"+>+ <div class="max-w-xl">+ <TextInputWithLabel+ bind:value={$formInputs.trivyImage.value}+ error={$formInputs.trivyImage.error}+ disabled={true}+ label={m.security_trivy_image_label()}+ description={m.security_trivy_image_description()}+ helpText={m.security_trivy_image_note()}+ placeholder="ghcr.io/getarcaneapp/tools:latest"+ type="text"+ />+ </div>++ <SettingsRow+ label={m.security_trivy_ignore_unfixed_label()}+ description={m.security_trivy_ignore_unfixed_description()}+ layout="inline"+ >+ <Switch id="trivyIgnoreUnfixedSwitch" bind:checked={$formInputs.trivyIgnoreUnfixed.value} />+ </SettingsRow>++ <SettingsRow+ label={m.security_trivy_network_label()}+ description={m.security_trivy_network_description()}+ helpText={m.security_trivy_network_help()}+ contentClass="max-w-xs"+ >+ <SearchableSelect+ triggerId="trivyNetwork"+ items={trivyNetworkOptions.map((option) => ({+ value: option.value,+ label: option.label,+ hint: option.description+ }))}+ bind:value={$formInputs.trivyNetwork.value}+ onSelect={(value) => ($formInputs.trivyNetwork.value = value)}+ placeholder={false}+ class="w-full justify-between"+ />+ {#if $formInputs.trivyNetwork.error}+ <p class="mt-2 text-sm text-destructive">{$formInputs.trivyNetwork.error}</p>+ {/if}+ </SettingsRow>+ <div class="space-y-4"><SettingsRow- label={m.security_trivy_ignore_unfixed_label()}- description={m.security_trivy_ignore_unfixed_description()}+ label={m.security_trivy_server_enabled_label()}+ description={m.security_trivy_server_enabled_description()}layout="inline">- <Switch id="trivyIgnoreUnfixedSwitch" bind:checked={$formInputs.trivyIgnoreUnfixed.value} />+ <Switch id="trivyServerEnabledSwitch" bind:checked={$formInputs.trivyServerEnabled.value} /></SettingsRow>+ {#if $formInputs.trivyServerEnabled.value}+ <div class="space-y-4 border-l-2 border-border/60 pl-5">+ <TextInputWithLabel+ bind:value={$formInputs.trivyServerUrl.value}+ error={$formInputs.trivyServerUrl.error}+ label={m.security_trivy_server_url_label()}+ description={m.security_trivy_server_url_description()}+ placeholder={m.security_trivy_server_url_placeholder()}+ type="url"+ />+ <TextInputWithLabel+ bind:value={$formInputs.trivyServerToken.value}+ error={$formInputs.trivyServerToken.error}+ label={m.security_trivy_server_token_label()}+ description={m.security_trivy_server_token_description()}+ type="password"+ />+ <Alert.Root variant="default" class="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950">+ <InfoIcon class="h-4 w-4 text-amber-900 dark:text-amber-100" />+ <Alert.Description class="text-amber-800 dark:text-amber-200">+ {m.security_trivy_server_note()}+ </Alert.Description>+ </Alert.Root>+ </div>+ {/if}+ </div>+ <SettingsRow+ label={m.security_trivy_security_opts_label()}+ description={m.security_trivy_security_opts_description()}+ helpText={m.security_trivy_security_opts_help()}+ >+ <Textarea+ bind:value={$formInputs.trivySecurityOpts.value}+ aria-label={m.security_trivy_security_opts_label()}+ class="min-h-28 font-mono text-sm"+ placeholder={m.security_trivy_security_opts_placeholder()}+ rows={4}+ />+ {#if $formInputs.trivySecurityOpts.error}+ <p class="mt-2 text-sm text-destructive">{$formInputs.trivySecurityOpts.error}</p>+ {/if}+ </SettingsRow>++ <SettingsRow+ label={m.security_trivy_privileged_label()}+ description={m.security_trivy_privileged_description()}+ layout="inline"+ >+ <Switch id="trivyPrivilegedSwitch" bind:checked={$formInputs.trivyPrivileged.value} />+ </SettingsRow>+ {#if $formInputs.trivyPrivileged.value}+ <Alert.Root variant="default" class="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950">+ <InfoIcon class="h-4 w-4 text-amber-900 dark:text-amber-100" />+ <Alert.Description class="text-amber-800 dark:text-amber-200">+ {m.security_trivy_privileged_note()}+ </Alert.Description>+ </Alert.Root>+ {/if}++ <div class="space-y-4"><SettingsRow- label={m.security_trivy_network_label()}- description={m.security_trivy_network_description()}- helpText={m.security_trivy_network_help()}- contentClass="max-w-xs"+ label={m.security_trivy_resource_limits_label()}+ description={m.security_trivy_resource_limits_description()}+ layout="inline">- <SearchableSelect- triggerId="trivyNetwork"- items={trivyNetworkOptions.map((option) => ({- value: option.value,- label: option.label,- hint: option.description- }))}- bind:value={$formInputs.trivyNetwork.value}- onSelect={(value) => ($formInputs.trivyNetwork.value = value)}- placeholder={false}- class="w-full justify-between"+ <Switch+ id="trivyResourceLimitsEnabledSwitch"+ bind:checked={$formInputs.trivyResourceLimitsEnabled.value}+ onCheckedChange={handleTrivyResourceLimitsChange}/>- {#if $formInputs.trivyNetwork.error}- <p class="mt-2 text-sm text-destructive">{$formInputs.trivyNetwork.error}</p>- {/if}</SettingsRow>-- <div class="space-y-4">- <SettingsRow- label={m.security_trivy_server_enabled_label()}- description={m.security_trivy_server_enabled_description()}- layout="inline"- >- <Switch id="trivyServerEnabledSwitch" bind:checked={$formInputs.trivyServerEnabled.value} />- </SettingsRow>- {#if $formInputs.trivyServerEnabled.value}- <div class="space-y-4 border-l-2 border-border/60 pl-5">+ {#if $formInputs.trivyResourceLimitsEnabled.value}+ <div class="space-y-4 border-l-2 border-border/60 pl-5">+ <div class="grid gap-4 sm:grid-cols-2"><TextInputWithLabel- bind:value={$formInputs.trivyServerUrl.value}- error={$formInputs.trivyServerUrl.error}- label={m.security_trivy_server_url_label()}- description={m.security_trivy_server_url_description()}- placeholder={m.security_trivy_server_url_placeholder()}- type="url"+ bind:value={$formInputs.trivyCpuLimit.value}+ error={$formInputs.trivyCpuLimit.error}+ disabled={!$formInputs.trivyResourceLimitsEnabled.value}+ label={m.security_trivy_cpu_limit_label()}+ helpText={m.security_trivy_cpu_limit_help()}+ type="number"/><TextInputWithLabel- bind:value={$formInputs.trivyServerToken.value}- error={$formInputs.trivyServerToken.error}- label={m.security_trivy_server_token_label()}- description={m.security_trivy_server_token_description()}- type="password"+ bind:value={$formInputs.trivyMemoryLimitMb.value}+ error={$formInputs.trivyMemoryLimitMb.error}+ disabled={!$formInputs.trivyResourceLimitsEnabled.value}+ label={m.security_trivy_memory_limit_label()}+ reserveHelpTextSpace={true}+ type="number"/>- <Alert.Root variant="default" class="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950">- <InfoIcon class="h-4 w-4 text-amber-900 dark:text-amber-100" />- <Alert.Description class="text-amber-800 dark:text-amber-200">- {m.security_trivy_server_note()}- </Alert.Description>- </Alert.Root></div>- {/if}- </div>-- <SettingsRow- label={m.security_trivy_security_opts_label()}- description={m.security_trivy_security_opts_description()}- helpText={m.security_trivy_security_opts_help()}- >- <Textarea- bind:value={$formInputs.trivySecurityOpts.value}- aria-label={m.security_trivy_security_opts_label()}- class="min-h-28 font-mono text-sm"- placeholder={m.security_trivy_security_opts_placeholder()}- rows={4}- />- {#if $formInputs.trivySecurityOpts.error}- <p class="mt-2 text-sm text-destructive">{$formInputs.trivySecurityOpts.error}</p>- {/if}- </SettingsRow>-- <SettingsRow- label={m.security_trivy_privileged_label()}- description={m.security_trivy_privileged_description()}- layout="inline"- >- <Switch id="trivyPrivilegedSwitch" bind:checked={$formInputs.trivyPrivileged.value} />- </SettingsRow>- {#if $formInputs.trivyPrivileged.value}- <Alert.Root variant="default" class="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950">- <InfoIcon class="h-4 w-4 text-amber-900 dark:text-amber-100" />- <Alert.Description class="text-amber-800 dark:text-amber-200">- {m.security_trivy_privileged_note()}- </Alert.Description>- </Alert.Root>- {/if}-- <div class="space-y-4">- <SettingsRow- label={m.security_trivy_resource_limits_label()}- description={m.security_trivy_resource_limits_description()}- layout="inline"- >- <Switch- id="trivyResourceLimitsEnabledSwitch"- bind:checked={$formInputs.trivyResourceLimitsEnabled.value}- onCheckedChange={handleTrivyResourceLimitsChange}- />- </SettingsRow>- {#if $formInputs.trivyResourceLimitsEnabled.value}- <div class="space-y-4 border-l-2 border-border/60 pl-5">- <div class="grid gap-4 sm:grid-cols-2">- <TextInputWithLabel- bind:value={$formInputs.trivyCpuLimit.value}- error={$formInputs.trivyCpuLimit.error}- disabled={!$formInputs.trivyResourceLimitsEnabled.value}- label={m.security_trivy_cpu_limit_label()}- helpText={m.security_trivy_cpu_limit_help()}- type="number"- />- <TextInputWithLabel- bind:value={$formInputs.trivyMemoryLimitMb.value}- error={$formInputs.trivyMemoryLimitMb.error}- disabled={!$formInputs.trivyResourceLimitsEnabled.value}- label={m.security_trivy_memory_limit_label()}- reserveHelpTextSpace={true}- type="number"- />- </div>- <div class="max-w-xs">- <TextInputWithLabel- bind:value={$formInputs.trivyConcurrentScanContainers.value}- error={$formInputs.trivyConcurrentScanContainers.error}- label={m.security_trivy_concurrent_scan_containers_label()}- helpText={m.security_trivy_concurrent_scan_containers_help()}- type="number"- />- </div>+ <div class="max-w-xs">+ <TextInputWithLabel+ bind:value={$formInputs.trivyConcurrentScanContainers.value}+ error={$formInputs.trivyConcurrentScanContainers.error}+ label={m.security_trivy_concurrent_scan_containers_label()}+ helpText={m.security_trivy_concurrent_scan_containers_help()}+ type="number"+ /></div>- {/if}- </div>- </Card.Content>-</Card.Root>+ </div>+ {/if}+ </div>+</SectionCard>diff --git a/frontend/src/lib/components/workspace-editor/workspace-draft-state.svelte.ts b/frontend/src/lib/components/workspace-editor/workspace-draft-state.svelte.tsnew file mode 100644index 000000000..d5e187c3d--- /dev/null+++ b/frontend/src/lib/components/workspace-editor/workspace-draft-state.svelte.ts@@ -0,0 +1,203 @@+import type { WorkspaceFileDraft } from '#lib/types/workspace';+import { m } from '#lib/paraglide/messages';+import {+ isWorkspaceFileSelectionUnder,+ readWorkspaceTextUpload,+ remapSelectedWorkspaceFileKey,+ remapWorkspaceFilePath,+ remapWorkspaceFileRecord,+ removeWorkspaceFileRecord,+ workspaceFileBasename,+ workspaceFilePathMatches,+ type WorkspaceDisplayEntry+} from '#lib/utils/workspace-files';++type RenamePlan = { newPath: string };++type WorkspaceDraftStateOptions = {+ initialFiles?: WorkspaceFileDraft[];+ initialContents?: Record<string, string>;+ initialErrors?: Record<string, boolean>;+ initialValidationReady?: Record<string, boolean>;+ initialOpenTabs?: string[];+ initialSelection?: string;+ pendingEntries?: boolean;+ fallbackTab: string;+ isFixedTab: (key: string) => boolean;+ isTabAvailable?: (key: string) => boolean;+ planCreate: (existingPaths: ReadonlySet<string>, parentPath: string, name: string) => string | null;+ planRename: (existingPaths: ReadonlySet<string>, relativePath: string, newName: string) => RenamePlan | null;+ planMove: (+ entry: Pick<WorkspaceDisplayEntry, 'isDirectory'> | undefined,+ existingPaths: ReadonlySet<string>,+ relativePath: string,+ newParentPath: string+ ) => string | null;+};++export class WorkspaceDraftState {+ files = $state<WorkspaceFileDraft[]>([]);+ contents = $state<Record<string, string>>({});+ hasErrors = $state<Record<string, boolean>>({});+ validationReady = $state<Record<string, boolean>>({});+ openTabs = $state<string[]>([]);+ selectedKey = $state('');++ readonly #fallbackTab: string;+ readonly #pendingEntries: boolean;+ readonly #isFixedTab: (key: string) => boolean;+ readonly #isTabAvailable: (key: string) => boolean;+ readonly #planCreate: WorkspaceDraftStateOptions['planCreate'];+ readonly #planRename: WorkspaceDraftStateOptions['planRename'];+ readonly #planMove: WorkspaceDraftStateOptions['planMove'];++ constructor(options: WorkspaceDraftStateOptions) {+ this.files = options.initialFiles?.map((file) => ({ ...file })) ?? [];+ this.contents = { ...options.initialContents };+ this.hasErrors = { ...options.initialErrors };+ this.validationReady = { ...options.initialValidationReady };+ this.openTabs = [...(options.initialOpenTabs ?? [options.fallbackTab])];+ this.selectedKey = options.initialSelection ?? options.fallbackTab;+ this.#fallbackTab = options.fallbackTab;+ this.#pendingEntries = options.pendingEntries ?? true;+ this.#isFixedTab = options.isFixedTab;+ this.#isTabAvailable = options.isTabAvailable ?? (() => true);+ this.#planCreate = options.planCreate;+ this.#planRename = options.planRename;+ this.#planMove = options.planMove;+ }++ get entries(): WorkspaceDisplayEntry[] {+ return this.files.map((file) => ({+ path: file.relativePath,+ relativePath: file.relativePath,+ name: workspaceFileBasename(file.relativePath),+ isDirectory: !!file.isDirectory,+ size: file.isDirectory ? 0 : (this.contents[file.relativePath]?.length ?? 0),+ content: file.isDirectory ? undefined : (this.contents[file.relativePath] ?? ''),+ pending: this.#pendingEntries+ }));+ }++ get paths(): ReadonlySet<string> {+ return new Set(this.entries.map((file) => file.relativePath));+ }++ get validOpenTabs(): string[] {+ const valid = this.openTabs.filter((key) => {+ if (this.#isFixedTab(key)) return this.#isTabAvailable(key);+ if (!key.startsWith('file:')) return false;+ const entry = this.entries.find((file) => file.relativePath === key.slice(5));+ return !!entry && !entry.isDirectory;+ });+ return valid.length > 0 ? valid : [this.#fallbackTab];+ }++ get activeTab(): string {+ const tabs = this.validOpenTabs;+ return tabs.includes(this.selectedKey) ? this.selectedKey : (tabs[0] ?? this.#fallbackTab);+ }++ isDirectoryKey(key: string): boolean {+ if (!key.startsWith('file:')) return false;+ return this.entries.find((file) => file.relativePath === key.slice(5))?.isDirectory === true;+ }++ openTab = (key: string) => {+ if (!this.isDirectoryKey(key) && !this.openTabs.includes(key)) {+ this.openTabs = [...this.openTabs, key];+ }+ this.selectedKey = key;+ };++ closeTab = (key: string) => {+ const tabs = this.validOpenTabs;+ const index = tabs.indexOf(key);+ const remaining = tabs.filter((tab) => tab !== key);+ this.openTabs = this.openTabs.filter((tab) => tab !== key);+ if (this.selectedKey === key) {+ this.selectedKey = remaining[Math.min(Math.max(index - 1, 0), remaining.length - 1)] ?? this.#fallbackTab;+ }+ };++ createFile = (parentPath: string, name: string, content = ''): string | null => {+ const relativePath = this.#planCreate(this.paths, parentPath, name);+ if (!relativePath) return null;+ this.files = [...this.files, { relativePath, isDirectory: false }];+ this.contents = { ...this.contents, [relativePath]: content };+ this.ensureValidationState(relativePath);+ this.openTab(`file:${relativePath}`);+ return relativePath;+ };++ createFolder = (parentPath: string, name: string): string | null => {+ const relativePath = this.#planCreate(this.paths, parentPath, name);+ if (!relativePath) return null;+ this.files = [...this.files, { relativePath, isDirectory: true }];+ this.selectedKey = `file:${relativePath}`;+ return relativePath;+ };++ uploadFile = async (parentPath: string, files: File[], maxFileSizeMb: number): Promise<string | void> => {+ const file = files[0];+ if (!file) return m.workspace_upload_file_required();+ const result = await readWorkspaceTextUpload(file, maxFileSizeMb);+ if (result.error) return result.error;+ this.createFile(parentPath, file.name, result.content ?? '');+ };++ rename = (relativePath: string, newName: string): string | null => {+ const plan = this.#planRename(this.paths, relativePath, newName);+ if (!plan) return null;+ this.applyPathChange(relativePath, plan.newPath);+ return plan.newPath;+ };++ move = (relativePath: string, newParentPath: string): string | null => {+ const entry = this.entries.find((file) => file.relativePath === relativePath);+ const newPath = this.#planMove(entry, this.paths, relativePath, newParentPath);+ if (!newPath) return null;+ this.applyPathChange(relativePath, newPath);+ return newPath;+ };++ remove = (relativePath: string) => {+ this.files = this.files.filter((file) => !workspaceFilePathMatches(file.relativePath, relativePath));+ this.contents = removeWorkspaceFileRecord(this.contents, relativePath);+ this.hasErrors = removeWorkspaceFileRecord(this.hasErrors, relativePath);+ this.validationReady = removeWorkspaceFileRecord(this.validationReady, relativePath);+ this.openTabs = this.openTabs.filter((tab) => !isWorkspaceFileSelectionUnder(tab, relativePath));+ if (isWorkspaceFileSelectionUnder(this.selectedKey, relativePath)) {+ this.selectedKey = this.validOpenTabs[0] ?? this.#fallbackTab;+ }+ };++ toDrafts(): WorkspaceFileDraft[] {+ return this.files.map((file) => ({+ relativePath: file.relativePath,+ isDirectory: !!file.isDirectory,+ content: file.isDirectory ? undefined : (this.contents[file.relativePath] ?? '')+ }));+ }++ private ensureValidationState(relativePath: string) {+ if (this.hasErrors[relativePath] === undefined) {+ this.hasErrors = { ...this.hasErrors, [relativePath]: false };+ }+ if (this.validationReady[relativePath] === undefined) {+ this.validationReady = { ...this.validationReady, [relativePath]: true };+ }+ }++ private applyPathChange(oldPath: string, newPath: string) {+ this.files = this.files.map((file) => ({+ ...file,+ relativePath: remapWorkspaceFilePath(file.relativePath, oldPath, newPath)+ }));+ this.contents = remapWorkspaceFileRecord(this.contents, oldPath, newPath);+ this.hasErrors = remapWorkspaceFileRecord(this.hasErrors, oldPath, newPath);+ this.validationReady = remapWorkspaceFileRecord(this.validationReady, oldPath, newPath);+ this.openTabs = this.openTabs.map((tab) => remapSelectedWorkspaceFileKey(tab, oldPath, newPath) ?? tab);+ this.selectedKey = remapSelectedWorkspaceFileKey(this.selectedKey, oldPath, newPath) ?? this.selectedKey;+ }+}diff --git a/frontend/src/lib/components/workspace-file-tree-panel.svelte b/frontend/src/lib/components/workspace-file-tree-panel.svelteindex ba6926586..2e8aa07fe 100644--- a/frontend/src/lib/components/workspace-file-tree-panel.svelte+++ b/frontend/src/lib/components/workspace-file-tree-panel.svelte@@ -32,11 +32,11 @@workspaceFileParentPath,workspaceFilePathMatches,validateWorkspaceFileName,- type WorkspaceFileEntry+ type WorkspaceDisplayEntry} from '#lib/utils/workspace-files';type DialogMode = 'create_file' | 'create_folder' | 'rename' | 'move' | 'upload';- type TreeRow = WorkspaceFileEntry & {+ type TreeRow = WorkspaceDisplayEntry & {depth: number;hasChildren: boolean;};@@ -60,7 +60,7 @@interface Props {title?: string;leadingRows?: WorkspaceTreeLeadingRow[];- entries: WorkspaceFileEntry[];+ entries: WorkspaceDisplayEntry[];selectedFile: string;disabled?: boolean;readOnlyMessage?: string;@@ -182,8 +182,8 @@};}- function flattenRows(files: WorkspaceFileEntry[], folderStates: Record<string, boolean>): TreeRow[] {- const byParent = new Map<string, WorkspaceFileEntry[]>();+ function flattenRows(files: WorkspaceDisplayEntry[], folderStates: Record<string, boolean>): TreeRow[] {+ const byParent = new Map<string, WorkspaceDisplayEntry[]>();for (const entry of files) {const parentPath = workspaceFileParentPath(entry.relativePath);const siblings = byParent.get(parentPath) ?? [];@@ -497,7 +497,7 @@dialogOpen = false;}- function handleDelete(entry: WorkspaceFileEntry) {+ function handleDelete(entry: WorkspaceDisplayEntry) {if (disabled) return;openConfirmDialog({title: m.delete_name({ name: entry.relativePath }),diff --git a/frontend/src/lib/hooks/use-responsive-table-limit.svelte.ts b/frontend/src/lib/hooks/use-responsive-table-limit.svelte.tsdeleted file mode 100644index db0ae4933..000000000--- a/frontend/src/lib/hooks/use-responsive-table-limit.svelte.ts+++ /dev/null@@ -1,79 +0,0 @@-import type { SearchPaginationSortRequest } from '#lib/types/shared';-import { IsMobile } from './is-mobile.svelte';--const MOBILE_ROWS = 4;-const ROW_HEIGHT = 57;-const HEADER_HEIGHT = 145;-const FOOTER_HEIGHT = 48;-const MIN_ROWS = 3;-const MAX_ROWS = 50;-const DEFAULT_ROWS = 5;--type ResponsiveTableLimitOptions = {- initialLimit?: number;- sort: NonNullable<SearchPaginationSortRequest['sort']>;- getTotalItems: () => number;-};--export function useResponsiveTableLimit({ initialLimit = DEFAULT_ROWS, sort, getTotalItems }: ResponsiveTableLimitOptions) {- const isMobile = new IsMobile();- let measuredHeight = $state(0);- let baseRequestOptions = $state<SearchPaginationSortRequest>({- pagination: { page: 1, limit: initialLimit },- sort- });-- function shouldReserveFooter(limit: number) {- return getTotalItems() > limit;- }-- function calculateLimitForHeight(height: number) {- if (isMobile.current) return MOBILE_ROWS;- if (height <= 0) return DEFAULT_ROWS;-- let availableHeight = height - HEADER_HEIGHT;- const initialRows = Math.floor(Math.max(0, availableHeight) / ROW_HEIGHT);- const footerLimit = Math.max(MIN_ROWS, Math.min(MAX_ROWS, initialRows));- if (shouldReserveFooter(footerLimit)) {- availableHeight -= FOOTER_HEIGHT;- }-- const rows = Math.floor(Math.max(0, availableHeight) / ROW_HEIGHT);- return Math.max(MIN_ROWS, Math.min(MAX_ROWS, rows));- }-- const displayLimit = $derived(calculateLimitForHeight(measuredHeight));- const requestOptions = $derived.by(() => {- const limit = displayLimit;- if (baseRequestOptions.pagination?.limit === limit) return baseRequestOptions;-- return {- ...baseRequestOptions,- pagination: {- page: baseRequestOptions.pagination?.page ?? 1,- limit- }- };- });-- return {- get displayLimit() {- return displayLimit;- },- get measuredHeight() {- return measuredHeight;- },- set measuredHeight(value: number) {- measuredHeight = value;- },- get requestOptions() {- return requestOptions;- },- set requestOptions(value: SearchPaginationSortRequest) {- baseRequestOptions = value;- },- shouldShowFooter(dataLength: number) {- return dataLength >= displayLimit && getTotalItems() > displayLimit;- }- };-}diff --git a/frontend/src/lib/icons/index.ts b/frontend/src/lib/icons/index.tsindex 2b58d1a85..7ae9f2f03 100644--- a/frontend/src/lib/icons/index.ts+++ b/frontend/src/lib/icons/index.ts@@ -16,7 +16,6 @@ export { default as VolumesIcon } from 'virtual:icons/fluent/hard-drive-20-filleexport { default as EventsIcon } from 'virtual:icons/material-symbols/event-list';export { default as ActivityIcon } from 'virtual:icons/lucide/activity';export { default as SettingsIcon } from 'virtual:icons/solar/settings-outline';-export { default as AppearanceIcon } from 'virtual:icons/f7/paintbrush';export { default as DockerBrandIcon } from 'virtual:icons/cib/docker';export { default as SecurityIcon } from 'virtual:icons/ic/round-security';export { default as ApiKeyIcon } from 'virtual:icons/hugeicons/lock-key';diff --git a/frontend/src/lib/services/container-registry-service.ts b/frontend/src/lib/services/container-registry-service.tsindex 21a025901..fd0f881ec 100644--- a/frontend/src/lib/services/container-registry-service.ts+++ b/frontend/src/lib/services/container-registry-service.ts@@ -35,7 +35,7 @@ class ContainerRegistryService extends BaseAPIService {return this.handleResponse(this.api.delete(`/container-registries/${id}`));}- async testRegistry(id: string): Promise<any> {+ async testRegistry(id: string): Promise<unknown> {return this.handleResponse(this.api.post(`/container-registries/${id}/test`));}}diff --git a/frontend/src/lib/stores/activity.store.svelte.ts b/frontend/src/lib/stores/activity.store.svelte.tsindex bdc34fc83..0b7462147 100644--- a/frontend/src/lib/stores/activity.store.svelte.ts+++ b/frontend/src/lib/stores/activity.store.svelte.ts@@ -177,7 +177,7 @@ function createActivityStore() {if (!activity.startedBy?.userId || !currentUserId || activity.startedBy.userId !== currentUserId) {return;}- queueActivityCompletionToast(activity);+ queueActivityCompletionToast(activity, openCenterInternal);}const core = createEnvironmentStreamStore<ActivityEnvironmentState, ActivityStreamEvent>({@@ -464,6 +464,17 @@ function createActivityStore() {}}+ function openCenterInternal(activityId?: string, batchId?: string) {+ _open = true;+ discardPendingActivityToasts();+ if (activityId) {+ setActivityExpanded(activityId, true);+ }+ if (batchId) {+ setBatchExpandedInternal(batchId, true);+ }+ }+function environmentFailuresInternal(): ActivityEnvironmentFailure[] {return Object.values(core.environmentStates).filter((state) => state.streamError)@@ -667,16 +678,7 @@ function createActivityStore() {discardPendingActivityToasts();}},- openCenter: (activityId?: string, batchId?: string) => {- _open = true;- discardPendingActivityToasts();- if (activityId) {- setActivityExpanded(activityId, true);- }- if (batchId) {- setBatchExpandedInternal(batchId, true);- }- },+ openCenter: openCenterInternal,retryLoadDetail: (activityId: string) => {const nextErrors = { ..._detailErrorIds };delete nextErrors[activityId];diff --git a/frontend/src/lib/types/notifications.ts b/frontend/src/lib/types/notifications.tsindex d4bf6751d..2cff47c0c 100644--- a/frontend/src/lib/types/notifications.ts+++ b/frontend/src/lib/types/notifications.ts@@ -18,7 +18,7 @@ export type EmailAuthMode = 'none' | 'auto' | 'plain' | 'login' | 'crammd5';export interface NotificationSettings {provider: NotificationProvider;enabled: boolean;- config?: Record<string, any>;+ config?: Record<string, unknown>;}export interface TestNotificationResponse {@@ -31,20 +31,20 @@ export interface TestNotificationResponse {error?: string;}-// --- Provider keys (source of truth, alphabetical) ---+// --- Provider keys (source of truth, display order) ---export const NOTIFICATION_PROVIDER_KEYS = [- 'discord','email',- 'generic',- 'googlechat',- 'gotify',- 'matrix',- 'ntfy',- 'pushover',+ 'discord',+ 'telegram','signal','slack',- 'telegram'+ 'ntfy',+ 'pushover',+ 'gotify',+ 'matrix',+ 'googlechat',+ 'generic'] as const;export type NotificationProviderKey = (typeof NOTIFICATION_PROVIDER_KEYS)[number];@@ -238,6 +238,16 @@ function eventFlagsToFormValues(};}+function formValuesToEventFlags(values: BaseProviderFormValues): ProviderEvents {+ return {+ image_update: values.eventImageUpdate,+ container_update: values.eventContainerUpdate,+ vulnerability_found: values.eventVulnerabilityFound,+ prune_report: values.eventPruneReport,+ auto_heal: values.eventAutoHeal+ };+}+export function discordSettingsToFormValues(settings?: NotificationSettings): DiscordFormValues {const cfg = getConfig(settings);const events = getEvents(cfg);@@ -324,13 +334,7 @@ export function discordFormValuesToSettings(values: DiscordFormValues): Notificatoken: values.token,username: values.username,avatarUrl: values.avatarUrl,- events: {- image_update: values.eventImageUpdate,- container_update: values.eventContainerUpdate,- vulnerability_found: values.eventVulnerabilityFound,- prune_report: values.eventPruneReport,- auto_heal: values.eventAutoHeal- }+ events: formValuesToEventFlags(values)}};}@@ -351,13 +355,7 @@ export function emailFormValuesToSettings(values: EmailFormValues): Notification.filter((addr) => addr.length > 0),tlsMode: values.tlsMode,authMode: values.authMode,- events: {- image_update: values.eventImageUpdate,- container_update: values.eventContainerUpdate,- vulnerability_found: values.eventVulnerabilityFound,- prune_report: values.eventPruneReport,- auto_heal: values.eventAutoHeal- }+ events: formValuesToEventFlags(values)}};}@@ -375,13 +373,7 @@ export function telegramFormValuesToSettings(values: TelegramFormValues): Notifipreview: values.preview,notification: values.notification,title: values.title,- events: {- image_update: values.eventImageUpdate,- container_update: values.eventContainerUpdate,- vulnerability_found: values.eventVulnerabilityFound,- prune_report: values.eventPruneReport,- auto_heal: values.eventAutoHeal- }+ events: formValuesToEventFlags(values)}};}@@ -402,13 +394,7 @@ export function signalFormValuesToSettings(values: SignalFormValues): Notificati.map((recipient) => recipient.trim()).filter((recipient) => recipient.length > 0),disableTls: values.disableTls,- events: {- image_update: values.eventImageUpdate,- container_update: values.eventContainerUpdate,- vulnerability_found: values.eventVulnerabilityFound,- prune_report: values.eventPruneReport,- auto_heal: values.eventAutoHeal- }+ events: formValuesToEventFlags(values)}};}@@ -425,13 +411,7 @@ export function slackFormValuesToSettings(values: SlackFormValues): Notificationtitle: values.title,channel: values.channel,threadTs: values.threadTs,- events: {- image_update: values.eventImageUpdate,- container_update: values.eventContainerUpdate,- vulnerability_found: values.eventVulnerabilityFound,- prune_report: values.eventPruneReport,- auto_heal: values.eventAutoHeal- }+ events: formValuesToEventFlags(values)}};}@@ -559,13 +539,7 @@ export function ntfyFormValuesToSettings(values: NtfyFormValues): NotificationSefirebase: values.firebase,disableTls: values.disableTls,disableTlsVerification: values.disableTlsVerification,- events: {- image_update: values.eventImageUpdate,- container_update: values.eventContainerUpdate,- vulnerability_found: values.eventVulnerabilityFound,- prune_report: values.eventPruneReport,- auto_heal: values.eventAutoHeal- }+ events: formValuesToEventFlags(values)}};}@@ -583,13 +557,7 @@ export function pushoverFormValuesToSettings(values: PushoverFormValues): Notifi.filter((device) => device.length > 0),priority: values.priority,title: values.title,- events: {- image_update: values.eventImageUpdate,- container_update: values.eventContainerUpdate,- vulnerability_found: values.eventVulnerabilityFound,- prune_report: values.eventPruneReport,- auto_heal: values.eventAutoHeal- }+ events: formValuesToEventFlags(values)}};}@@ -608,13 +576,7 @@ export function gotifyFormValuesToSettings(values: GotifyFormValues): NotificatidisableTls: values.disableTls,insecureSkipVerify: values.insecureSkipVerify,useHeader: values.useHeader,- events: {- image_update: values.eventImageUpdate,- container_update: values.eventContainerUpdate,- vulnerability_found: values.eventVulnerabilityFound,- prune_report: values.eventPruneReport,- auto_heal: values.eventAutoHeal- }+ events: formValuesToEventFlags(values)}};}@@ -630,13 +592,7 @@ export function matrixFormValuesToSettings(values: MatrixFormValues): Notificatiusername: values.username,password: values.password,disableTlsVerification: values.disableTlsVerification,- events: {- image_update: values.eventImageUpdate,- container_update: values.eventContainerUpdate,- vulnerability_found: values.eventVulnerabilityFound,- prune_report: values.eventPruneReport,- auto_heal: values.eventAutoHeal- }+ events: formValuesToEventFlags(values)}};}@@ -647,13 +603,7 @@ export function googleChatFormValuesToSettings(values: GoogleChatFormValues): Noenabled: values.enabled,config: {webhookUrl: values.webhookUrl,- events: {- image_update: values.eventImageUpdate,- container_update: values.eventContainerUpdate,- vulnerability_found: values.eventVulnerabilityFound,- prune_report: values.eventPruneReport,- auto_heal: values.eventAutoHeal- }+ events: formValuesToEventFlags(values)}};}@@ -685,13 +635,7 @@ export function genericFormValuesToSettings(values: GenericFormValues): NotificacustomHeaders: customHeaders,payloadTemplate: values.payloadTemplate,successBodyContains: values.successBodyContains,- events: {- image_update: values.eventImageUpdate,- container_update: values.eventContainerUpdate,- vulnerability_found: values.eventVulnerabilityFound,- prune_report: values.eventPruneReport,- auto_heal: values.eventAutoHeal- }+ events: formValuesToEventFlags(values)}};}diff --git a/frontend/src/lib/types/project-workspace.ts b/frontend/src/lib/types/project-workspace.tsindex 8eb837da5..7fc55e855 100644--- a/frontend/src/lib/types/project-workspace.ts+++ b/frontend/src/lib/types/project-workspace.ts@@ -1,6 +1,5 @@-import type { Workspace, WorkspaceFileChange, WorkspaceFileContent, WorkspaceFileDraft, WorkspaceFileEntry } from './workspace';+import type { Workspace, WorkspaceFileChange, WorkspaceFileContent, WorkspaceFileDraft } from './workspace';-export type ProjectWorkspaceFile = WorkspaceFileEntry;export type ProjectWorkspace = Workspace;export type ProjectWorkspaceFileContent = WorkspaceFileContent;export type ProjectWorkspaceFileChange = WorkspaceFileChange;@@ -10,7 +9,3 @@ export interface ProjectWorkspaceUpdateManifest {fileTreeRevision: string;fileChanges: ProjectWorkspaceFileChange[];}--export interface CreateProjectWorkspaceManifest {- fileChanges: ProjectWorkspaceFileChange[];-}diff --git a/frontend/src/lib/types/volume-workspace.ts b/frontend/src/lib/types/volume-workspace.tsindex 3fd476fad..b9c667cbe 100644--- a/frontend/src/lib/types/volume-workspace.ts+++ b/frontend/src/lib/types/volume-workspace.ts@@ -1,12 +1,5 @@-import type {- Workspace,- WorkspaceFileChange,- WorkspaceFileContent,- WorkspaceFileEntry,- WorkspaceReadOnlyReason-} from './workspace';+import type { Workspace, WorkspaceFileChange, WorkspaceFileContent, WorkspaceReadOnlyReason } from './workspace';-export type VolumeWorkspaceFile = WorkspaceFileEntry;export type VolumeWorkspace = Workspace;export interface VolumeWorkspaceFileContent extends Omit<WorkspaceFileContent, 'readOnlyReason'> {readOnlyReason?: WorkspaceReadOnlyReason | 'restore_pending';diff --git a/frontend/src/lib/utils/notification-providers.ts b/frontend/src/lib/utils/notification-providers.tsnew file mode 100644index 000000000..363fae776--- /dev/null+++ b/frontend/src/lib/utils/notification-providers.ts@@ -0,0 +1,174 @@+import * as m from '#lib/paraglide/messages.js';+import {+ NOTIFICATION_PROVIDER_KEYS,+ type NotificationProviderKey,+ type NotificationSettings,+ type ProviderFormValuesMap,+ discordSettingsToFormValues,+ emailSettingsToFormValues,+ telegramSettingsToFormValues,+ signalSettingsToFormValues,+ slackSettingsToFormValues,+ ntfySettingsToFormValues,+ pushoverSettingsToFormValues,+ gotifySettingsToFormValues,+ matrixSettingsToFormValues,+ googleChatSettingsToFormValues,+ genericSettingsToFormValues,+ discordFormValuesToSettings,+ emailFormValuesToSettings,+ telegramFormValuesToSettings,+ signalFormValuesToSettings,+ slackFormValuesToSettings,+ ntfyFormValuesToSettings,+ pushoverFormValuesToSettings,+ gotifyFormValuesToSettings,+ matrixFormValuesToSettings,+ googleChatFormValuesToSettings,+ genericFormValuesToSettings+} from '#lib/types/notifications';++export type NotificationSettingsByProvider = Record<NotificationProviderKey, NotificationSettings | null>;+export type NotificationProviderFormState = { [K in NotificationProviderKey]: ProviderFormValuesMap[K] };++export type NotificationProviderDefinition<K extends NotificationProviderKey> = {+ key: K;+ label: () => string;+ description: () => string;+ fromSettings: (settings?: NotificationSettings) => ProviderFormValuesMap[K];+ toSettings: (values: ProviderFormValuesMap[K]) => NotificationSettings;+};++type NotificationProviderDefinitions = {+ [K in NotificationProviderKey]: NotificationProviderDefinition<K>;+};++const notificationProviderDefinitions = {+ discord: {+ key: 'discord',+ label: m.notifications_discord_title,+ description: m.notifications_discord_description,+ fromSettings: discordSettingsToFormValues,+ toSettings: discordFormValuesToSettings+ },+ email: {+ key: 'email',+ label: m.common_email,+ description: m.notifications_email_description,+ fromSettings: emailSettingsToFormValues,+ toSettings: emailFormValuesToSettings+ },+ generic: {+ key: 'generic',+ label: m.notifications_generic_title,+ description: m.notifications_generic_description,+ fromSettings: genericSettingsToFormValues,+ toSettings: genericFormValuesToSettings+ },+ googlechat: {+ key: 'googlechat',+ label: m.notifications_googlechat_title,+ description: m.notifications_googlechat_description,+ fromSettings: googleChatSettingsToFormValues,+ toSettings: googleChatFormValuesToSettings+ },+ gotify: {+ key: 'gotify',+ label: m.notifications_gotify_title,+ description: m.notifications_gotify_description,+ fromSettings: gotifySettingsToFormValues,+ toSettings: gotifyFormValuesToSettings+ },+ matrix: {+ key: 'matrix',+ label: m.notifications_matrix_title,+ description: m.notifications_matrix_description,+ fromSettings: matrixSettingsToFormValues,+ toSettings: matrixFormValuesToSettings+ },+ ntfy: {+ key: 'ntfy',+ label: m.notifications_ntfy_title,+ description: m.notifications_ntfy_description,+ fromSettings: ntfySettingsToFormValues,+ toSettings: ntfyFormValuesToSettings+ },+ pushover: {+ key: 'pushover',+ label: m.notifications_pushover_title,+ description: m.notifications_pushover_description,+ fromSettings: pushoverSettingsToFormValues,+ toSettings: pushoverFormValuesToSettings+ },+ signal: {+ key: 'signal',+ label: m.notifications_signal_title,+ description: m.notifications_signal_description,+ fromSettings: signalSettingsToFormValues,+ toSettings: signalFormValuesToSettings+ },+ slack: {+ key: 'slack',+ label: m.notifications_slack_title,+ description: m.notifications_slack_description,+ fromSettings: slackSettingsToFormValues,+ toSettings: slackFormValuesToSettings+ },+ telegram: {+ key: 'telegram',+ label: m.notifications_telegram_title,+ description: m.notifications_telegram_description,+ fromSettings: telegramSettingsToFormValues,+ toSettings: telegramFormValuesToSettings+ }+} satisfies NotificationProviderDefinitions;++export function createNotificationSettingsByProvider(settings: NotificationSettings[] = []): NotificationSettingsByProvider {+ const byProvider = Object.fromEntries(+ NOTIFICATION_PROVIDER_KEYS.map((provider) => [provider, null])+ ) as NotificationSettingsByProvider;+ for (const setting of settings) {+ if (NOTIFICATION_PROVIDER_KEYS.includes(setting.provider as NotificationProviderKey)) {+ byProvider[setting.provider as NotificationProviderKey] = setting;+ }+ }+ return byProvider;+}++export function createNotificationProviderFormState(+ settings: NotificationSettingsByProvider = createNotificationSettingsByProvider()+): NotificationProviderFormState {+ return Object.fromEntries(+ NOTIFICATION_PROVIDER_KEYS.map((provider) => [+ provider,+ getNotificationProviderDefinition(provider).fromSettings(settings[provider] ?? undefined)+ ])+ ) as NotificationProviderFormState;+}++export function cloneNotificationProviderFormState(state: NotificationProviderFormState): NotificationProviderFormState {+ return Object.fromEntries(+ NOTIFICATION_PROVIDER_KEYS.map((provider) => [provider, { ...state[provider] }])+ ) as NotificationProviderFormState;+}++export function updateNotificationProviderFormState<K extends NotificationProviderKey>(+ state: NotificationProviderFormState,+ provider: K,+ values: ProviderFormValuesMap[K]+): NotificationProviderFormState {+ return { ...state, [provider]: { ...values } } as NotificationProviderFormState;+}++export function getNotificationProviderDefinition<K extends NotificationProviderKey>(+ provider: K+): NotificationProviderDefinition<K> {+ return notificationProviderDefinitions[provider] as unknown as NotificationProviderDefinition<K>;+}++export function notificationProviderFormValuesToSettings<K extends NotificationProviderKey>(+ provider: K,+ values: ProviderFormValuesMap[K]+): NotificationSettings {+ return getNotificationProviderDefinition(provider).toSettings(values);+}diff --git a/frontend/src/lib/utils/registry.ts b/frontend/src/lib/utils/registry.tsindex f6156f6c5..3e9dde8f3 100644--- a/frontend/src/lib/utils/registry.ts+++ b/frontend/src/lib/utils/registry.ts@@ -15,7 +15,7 @@ export function getRegistryDisplayName(registry: RegistryIdentity): string {}/** Strips the scheme and trailing slashes so a registry URL can be used as an image host. */-export function normalizeRegistryHost(url: string): string {+function normalizeRegistryHost(url: string): string {return url.replace(/^https?:\/\//, '').replace(/\/+$/, '');}diff --git a/frontend/src/lib/utils/resource-actions.ts b/frontend/src/lib/utils/resource-actions.tsindex 7986920b2..d2507e6a2 100644--- a/frontend/src/lib/utils/resource-actions.ts+++ b/frontend/src/lib/utils/resource-actions.ts@@ -1,29 +1,29 @@import type { ActionButton } from '#lib/layouts';type CreateRefreshActionOptions = {- canCreate: boolean;- createLabel: string;- onCreate: () => void;+ create?: {+ allowed: boolean;+ label: string;+ onclick: () => void;+ };refreshLabel: string;onRefresh: () => void | Promise<void>;refreshing: boolean;};export function createRefreshActionButtons({- canCreate,- createLabel,- onCreate,+ create,refreshLabel,onRefresh,refreshing}: CreateRefreshActionOptions): ActionButton[] {const buttons: ActionButton[] = [];- if (canCreate) {+ if (create?.allowed) {buttons.push({id: 'create',action: 'create',- label: createLabel,- onclick: onCreate+ label: create.label,+ onclick: create.onclick});}buttons.push({diff --git a/frontend/src/lib/utils/theme.ts b/frontend/src/lib/utils/theme.tsindex 2fd974b77..1d91f40d0 100644--- a/frontend/src/lib/utils/theme.ts+++ b/frontend/src/lib/utils/theme.ts@@ -1,7 +1,7 @@import { writable } from 'svelte/store';import type { ApplicationTheme } from '#lib/types/settings';-export const APPLICATION_THEME_VALUES = [+const APPLICATION_THEME_VALUES = ['default','graphite','ocean',diff --git a/frontend/src/lib/utils/workspace-files.ts b/frontend/src/lib/utils/workspace-files.tsindex a16e2becc..cbfaed058 100644--- a/frontend/src/lib/utils/workspace-files.ts+++ b/frontend/src/lib/utils/workspace-files.ts@@ -8,7 +8,7 @@ import type {WorkspaceReadOnlyReason} from '#lib/types/workspace';-export interface WorkspaceFileEntry extends Omit<WorkspaceFileDto, 'editable' | 'isSymlink' | 'readOnlyReason'> {+export interface WorkspaceDisplayEntry extends Omit<WorkspaceFileDto, 'editable' | 'isSymlink' | 'readOnlyReason'> {editable?: boolean;isSymlink?: boolean;readOnlyReason?: WorkspaceReadOnlyReason | 'restore_pending';@@ -77,7 +77,7 @@ export function buildWorkspaceMultipartUpdate<T extends WorkspaceDisplayFileChanreturn { fileChanges, files };}-export function normalizeWorkspaceRelativePath(relativePath: string): string {+function normalizeWorkspaceRelativePath(relativePath: string): string {return relativePath.trim().replaceAll('\\', '/').split('/').filter(Boolean).join('/');}@@ -138,7 +138,7 @@ export function planWorkspaceFileRename(}export function planWorkspaceFileMove(- entry: Pick<WorkspaceFileEntry, 'isDirectory'> | undefined,+ entry: Pick<WorkspaceDisplayEntry, 'isDirectory'> | undefined,existingPaths: ReadonlySet<string>,relativePath: string,newParentPath: string@@ -220,17 +220,17 @@ export function workspaceFileLanguage(relativePath: string): CodeLanguage {return 'plaintext';}-export function compareWorkspaceFileEntries(a: WorkspaceFileEntry, b: WorkspaceFileEntry): number {+export function compareWorkspaceFileEntries(a: WorkspaceDisplayEntry, b: WorkspaceDisplayEntry): number {if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;const baseComparison = a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });return baseComparison || a.name.localeCompare(b.name);}export function applyWorkspaceFileChangesForDisplay(- files: WorkspaceFileEntry[],+ files: WorkspaceDisplayEntry[],changes: WorkspaceDisplayFileChange[]-): WorkspaceFileEntry[] {- const entries = new Map<string, WorkspaceFileEntry>();+): WorkspaceDisplayEntry[] {+ const entries = new Map<string, WorkspaceDisplayEntry>();for (const file of files) {const modeType = file.mode?.[0];@@ -280,7 +280,7 @@ export function applyWorkspaceFileChangesForDisplay(change.operation === 'rename' && change.newName? joinWorkspaceFilePath(workspaceFileParentPath(relativePath), change.newName): joinWorkspaceFilePath(change.newParentPath ?? '', workspaceFileBasename(relativePath));- const remapped = new Map<string, WorkspaceFileEntry>();+ const remapped = new Map<string, WorkspaceDisplayEntry>();for (const [entryPath, current] of entries.entries()) {if (!workspaceFilePathMatches(entryPath, relativePath)) {remapped.set(entryPath, current);diff --git a/frontend/src/routes/(app)/account/+page.svelte b/frontend/src/routes/(app)/account/+page.svelteindex 066104735..160387600 100644--- a/frontend/src/routes/(app)/account/+page.svelte+++ b/frontend/src/routes/(app)/account/+page.svelte@@ -1,12 +1,7 @@<script lang="ts">- import { onMount } from 'svelte';import { fromStore } from 'svelte/store';import { toast } from 'svelte-sonner';- import { mode } from 'mode-watcher';- import ThemeModeSelector from '#lib/components/theme-mode/theme-mode-selector.svelte';import HeaderCard from '#lib/components/header-card.svelte';- import ApiKeyFormSheet from '#lib/components/sheets/api-key-form-sheet.svelte';- import PasskeySettings from '#lib/components/auth/passkey-settings.svelte';import * as Tabs from '#lib/components/ui/tabs/index.js';import { TabBar, type TabItem } from '#lib/components/tab-bar/index.js';import { useUrlTab } from '#lib/hooks/use-url-tab.svelte';@@ -14,21 +9,8 @@import * as ImageCropper from '#lib/components/ui/image-cropper';import { ArcaneButton } from '#lib/components/arcane-button/index.js';import TextInputWithLabel from '#lib/components/form/text-input-with-label.svelte';- import LocalePicker from '#lib/components/locale-picker.svelte';- import TimeFormatPicker from '#lib/components/time-format-picker.svelte';- import FontSizePicker from '#lib/components/font-size-picker.svelte';- import SettingsRow from '#lib/components/settings/settings-row.svelte';- import SelectWithLabel from '#lib/components/form/select-with-label.svelte';- import AccentColorPicker from '#lib/components/accent-color/accent-color-picker.svelte';- import ApplicationThemePicker from '#lib/components/application-theme/application-theme-picker.svelte';- import { Switch } from '#lib/components/ui/switch/index.js';- import { DEFAULT_LANDING_PAGE, getLandingPageNavItems } from '#lib/config/navigation-config';- import { resetNavigationVisibility } from '#lib/utils/navigation';- import { applyGlassEffects, applyInterfaceAnimations, applyOledMode, DEFAULT_ACCENT_COLOR } from '#lib/utils/theme';- import { debounced } from '#lib/utils/ws';import { m } from '#lib/paraglide/messages';import { userService } from '#lib/services/user-service';- import { apiKeyService } from '#lib/services/api-key-service';import userStore from '#lib/stores/user-store';import settingsStore from '#lib/stores/config-store';import { getDefaultProfilePicture } from '#lib/utils/docker';@@ -36,23 +18,13 @@import { formatDate, formatRelativeTime } from '#lib/utils/formatting';import { cn } from '#lib/utils';import { GLOBAL_SCOPE } from '#lib/types/auth';- import type { ApiKey, ApiKeyCreated, ApiKeyPermissionGrant, CreateUserApiKey, UserPreferences } from '#lib/types/auth';- import type { ApplicationTheme, IconCatalog } from '#lib/types/settings';import { Temporal } from 'temporal-polyfill';- import {- UserIcon,- LogoutIcon,- ShieldAlertIcon,- ApiKeyIcon,- AddIcon,- CopyIcon,- TrashIcon,- MonitorSpeakerIcon,- DockIcon,- SettingsIcon- } from '#lib/icons';+ import { UserIcon, SettingsIcon } from '#lib/icons';+ import AccountPreferencesPanel from './account-preferences-panel.svelte';+ import AccountApiKeysPanel from './account-api-keys-panel.svelte';+ import AccountSecurityPanel from './account-security-panel.svelte';- let { data: _data }: PageProps = $props();+ let {}: PageProps = $props();type AccountTab = 'account' | 'preferences';@@ -69,23 +41,21 @@});const activeTab = $derived(urlTab.value);- const BUILT_IN_ROLE_LABELS: Record<string, string> = {- role_admin: 'Administrator',- role_editor: 'Editor',- role_deployer: 'Deployer',- role_viewer: 'Viewer'+ const BUILT_IN_ROLE_LABELS: Record<string, () => string> = {+ role_admin: m.account_role_administrator,+ role_editor: m.account_role_editor,+ role_deployer: m.account_role_deployer,+ role_viewer: m.account_role_viewer};function prettyRoleName(roleId: string): string {- return BUILT_IN_ROLE_LABELS[roleId] ?? roleId.replace(/^role_/, '').replace(/_/g, ' ');+ return BUILT_IN_ROLE_LABELS[roleId]?.() ?? roleId.replace(/^role_/, '').replace(/_/g, ' ');}const currentUser = $derived($userStore);const isOidcUser = $derived(Boolean(currentUser?.oidcSubjectId));const settings = fromStore(settingsStore);- const autoLogin = fromStore(settingsStore.autoLoginEnabled);- const autoLoginEnabled = $derived(autoLogin.current);const gravatarEnabled = $derived(Boolean(settings.current?.enableGravatar));const avatarMaxUploadSizeMb = $derived(Number(settings.current?.avatarMaxUploadSizeMb) > 0 ? Number(settings.current?.avatarMaxUploadSizeMb) : 2@@ -97,23 +67,11 @@let profileSaving = $state(false);let profileLoaded = $state(false);- let currentPassword = $state('');- let newPassword = $state('');- let confirmPassword = $state('');- let passwordSaving = $state(false);-- let revokingAll = $state(false);let avatarUrl = $state<string>(getDefaultProfilePicture());let avatarCacheBuster = $state(Temporal.Now.instant().epochMilliseconds);const avatarSrc = $derived(currentUser?.avatarUrl ? `${currentUser.avatarUrl}?t=${avatarCacheBuster}` : '');let cropperAvatarSrc = $derived(avatarSrc || avatarUrl);- let apiKeys = $state<ApiKey[]>([]);- let apiKeysLoading = $state(false);- let showCreateKeyForm = $state(false);- let creatingKey = $state(false);- let createdKey = $state<ApiKeyCreated | null>(null);-let avatarUploading = $state(false);$effect(() => {@@ -132,84 +90,6 @@profileDisplayName.trim() !== (currentUser?.displayName ?? '') || profileEmail.trim() !== (currentUser?.email ?? ''));- const passwordValid = $derived(currentPassword.length > 0 && newPassword.length >= 8 && newPassword === confirmPassword);-- // --- Appearance preferences ---- // Each control writes straight through to the account: the visual change is- // applied by the control itself, then persisted; a failed save reverts by- // re-applying the stored user.- const preferences = $derived(currentUser?.preferences ?? {});- const applicationThemeValue = $derived<ApplicationTheme>(preferences.applicationTheme ?? 'default');- const accentColorValue = $derived(- preferences.accentColor && preferences.accentColor !== 'default' ? preferences.accentColor : DEFAULT_ACCENT_COLOR- );- const iconCatalogValue = $derived(preferences.iconCatalog ?? 'selfhst');- const oledModeEnabled = $derived(preferences.oledMode ?? false);- const glassEffectsEnabled = $derived(preferences.glassEffectsEnabled ?? true);- const animationsEnabled = $derived(preferences.animationsEnabled ?? true);- const sidebarHoverExpansionEnabled = $derived(preferences.sidebarHoverExpansion ?? true);- const keyboardShortcutsEnabled = $derived(preferences.keyboardShortcutsEnabled ?? true);-- const isDarkMode = $derived(mode.current === 'dark');- const isDefaultApplicationTheme = $derived(applicationThemeValue === 'default');-- const iconCatalogOptions = $derived([- { value: 'selfhst', label: m.icon_catalog_selfhst(), description: m.icon_catalog_selfhst_description() },- {- value: 'dashboard-icons',- label: m.icon_catalog_dashboard_icons(),- description: m.icon_catalog_dashboard_icons_description()- }- ]);-- const landingPageOptions = $derived(getLandingPageNavItems().map((item) => ({ value: item.url, label: item.title })));- const landingValue = $derived.by(() => {- const current = preferences.defaultLandingPage ?? DEFAULT_LANDING_PAGE;- // A stale value (page removed, or a hand-edited preference) falls back to- // the dashboard rather than leaving the select showing a placeholder.- return landingPageOptions.some((option) => option.value === current) ? current : DEFAULT_LANDING_PAGE;- });-- async function savePreferences(patch: Partial<UserPreferences>) {- const previous = currentUser;- if (!previous) return;- try {- const updated = await userService.updateMyProfile({ preferences: patch });- await userStore.setUser(updated);- } catch (err) {- toast.error(err instanceof Error ? err.message : m.common_update_failed({ resource: m.account_preferences() }));- // Re-applying the stored user rolls the live preview back.- await userStore.setUser(previous);- }- }-- // The theme carousel emits a value per scroll snap, so persistence is- // debounced. Patches are merged rather than replaced, so a theme change- // immediately followed by an accent change still saves both.- let pendingPreferences: Partial<UserPreferences> = {};- const flushPreferences = debounced(() => {- const patch = pendingPreferences;- pendingPreferences = {};- void savePreferences(patch);- }, 400);-- function savePreferencesDebounced(patch: Partial<UserPreferences>) {- pendingPreferences = { ...pendingPreferences, ...patch };- flushPreferences();- }-- // --- Mobile navigation ---- const mobileNavigationMode = $derived(preferences.mobileNavigationMode ?? 'floating');- const mobileNavigationShowLabels = $derived(preferences.mobileNavigationShowLabels ?? true);-- function selectMobileNavigationMode(value: 'floating' | 'docked') {- if (value === mobileNavigationMode) return;- // The bar hides itself on scroll in floating mode; reset it so the change- // is visible right away.- resetNavigationVisibility();- void savePreferences({ mobileNavigationMode: value });- }-async function updateAvatar(email: string | undefined, enabled: boolean) {if (!enabled || !email) {avatarUrl = getDefaultProfilePicture();@@ -239,7 +119,7 @@await userStore.setUser(updated);toast.success(m.account_profile_updated());} catch (err) {- const msg = err instanceof Error ? err.message : 'Failed to update profile';+ const msg = err instanceof Error ? err.message : m.common_update_failed({ resource: m.account_profile_title() });toast.error(msg);} finally {profileSaving = false;@@ -295,94 +175,6 @@avatarUploading = false;}}-- async function changePassword() {- if (!passwordValid || passwordSaving) return;- passwordSaving = true;- try {- await userService.changePassword({ currentPassword, newPassword });- toast.success(m.account_password_updated());- currentPassword = '';- newPassword = '';- confirmPassword = '';- } catch (err) {- const msg = err instanceof Error ? err.message : 'Failed to update password';- toast.error(msg);- } finally {- passwordSaving = false;- }- }-- async function loadApiKeys() {- apiKeysLoading = true;- try {- apiKeys = await apiKeyService.listMine();- } catch (err) {- toast.error(err instanceof Error ? err.message : 'Failed to load API keys');- } finally {- apiKeysLoading = false;- }- }-- async function createApiKey({- apiKey- }: {- apiKey: { name: string; description?: string; expiresAt?: string; permissions?: ApiKeyPermissionGrant[] };- isEditMode: boolean;- apiKeyId?: string;- }) {- creatingKey = true;- try {- // Personal keys carry no grants; they inherit the owner's role permissions.- const payload: CreateUserApiKey = {- name: apiKey.name,- description: apiKey.description,- expiresAt: apiKey.expiresAt- };- const created = await apiKeyService.createMine(payload);- createdKey = created;- showCreateKeyForm = false;- await loadApiKeys();- } catch (err) {- toast.error(err instanceof Error ? err.message : 'Failed to create API key');- } finally {- creatingKey = false;- }- }-- async function deleteApiKey(id: string, name: string) {- if (!confirm(`Delete API key "${name}"? This cannot be undone.`)) return;- try {- await apiKeyService.deleteMine(id);- toast.success(m.account_api_key_deleted());- await loadApiKeys();- } catch (err) {- toast.error(err instanceof Error ? err.message : 'Failed to delete API key');- }- }-- function copyKeyToClipboard(key: string) {- void navigator.clipboard.writeText(key);- toast.success(m.common_key_copied());- }-- onMount(() => {- void loadApiKeys();- });-- async function logoutAllOther() {- if (revokingAll) return;- revokingAll = true;- try {- await userService.logoutAllOtherSessions();- toast.success(m.account_sessions_signed_out());- } catch (err) {- const msg = err instanceof Error ? err.message : 'Failed to sign out other sessions';- toast.error(msg);- } finally {- revokingAll = false;- }- }</script><div class="space-y-6 pb-5 md:space-y-8 md:pb-5">@@ -562,410 +354,21 @@{@const envCount = Object.keys(currentUser.permissionsByEnv).length}{@const globalCount = currentUser.permissionsByEnv[GLOBAL_SCOPE]?.length ?? 0}<p class="text-xs text-muted-foreground">- {globalCount} global permission{globalCount === 1 ? '' : 's'} across {envCount} environment{envCount === 1- ? ''- : 's'}.+ {m.account_permissions_summary({ globalCount, environmentCount: envCount })}</p>{/if}</div></section>- {#if !isOidcUser}- <section class="space-y-5">- <div>- <h2 class="text-base font-semibold tracking-tight sm:text-lg">{m.common_password()}</h2>- <p class="mt-1 text-xs text-muted-foreground sm:text-sm">{m.account_password_desc()}</p>- </div>- <TextInputWithLabel- id="account-current-password"- type="password"- bind:value={currentPassword}- label={m.account_current_password()}- autocomplete="current-password"- />- <div class="grid gap-5 sm:grid-cols-2">- <TextInputWithLabel- id="account-new-password"- type="password"- bind:value={newPassword}- label={m.account_new_password()}- helpText={m.account_password_min_length()}- autocomplete="new-password"- />- <TextInputWithLabel- id="account-confirm-password"- type="password"- bind:value={confirmPassword}- label={m.account_confirm_password()}- error={confirmPassword.length > 0 && confirmPassword !== newPassword ? m.account_passwords_dont_match() : null}- autocomplete="new-password"- />- </div>- <div class="flex justify-end">- <ArcaneButton- action="save"- customLabel={m.account_update_password()}- onclick={changePassword}- loading={passwordSaving}- disabled={!passwordValid || passwordSaving}- />- </div>- </section>- {/if}-- <section class="space-y-5">- <div class="flex flex-wrap items-start justify-between gap-3">- <div class="min-w-0">- <h2 class="text-base font-semibold tracking-tight sm:text-lg">{m.account_api_keys_title()}</h2>- <p class="mt-1 text-xs text-muted-foreground sm:text-sm">{m.account_api_keys_description()}</p>- </div>- {#if !showCreateKeyForm && !createdKey}- <ArcaneButton- action="create"- tone="outline"- size="sm"- customLabel={m.account_new_key()}- icon={AddIcon}- class="shrink-0"- onclick={() => (showCreateKeyForm = true)}- />- {/if}- </div>- {#if createdKey}- <div class="mb-4 space-y-3 rounded-lg border border-primary/30 bg-primary/5 p-4">- <div>- <div class="truncate text-sm font-semibold">{m.api_key_created_title()}: {createdKey.name}</div>- <p class="mt-1 text-xs text-muted-foreground">{m.api_key_save_warning()}</p>- </div>- <code class="block truncate rounded border bg-background px-3 py-2 font-mono text-xs">- {createdKey.key}- </code>- <div class="flex flex-wrap justify-end gap-2">- <ArcaneButton- action="base"- tone="outline"- size="sm"- customLabel={m.common_copy()}- icon={CopyIcon}- onclick={() => copyKeyToClipboard(createdKey!.key)}- />- <ArcaneButton- action="cancel"- tone="ghost"- size="sm"- customLabel={m.common_ive_saved_it()}- onclick={() => (createdKey = null)}- />- </div>- </div>- {/if}-- <div class="overflow-hidden rounded-xl border border-border/60 bg-card/30">- {#if apiKeysLoading && apiKeys.length === 0}- <div class="p-6 text-center text-sm text-muted-foreground">{m.common_loading()}</div>- {:else if apiKeys.length === 0}- <div class="p-6 text-center text-sm text-muted-foreground">- <ApiKeyIcon class="mx-auto mb-2 size-8 opacity-40" />- {m.api_keys_empty()}- </div>- {:else}- <ul class="divide-y divide-border/60">- {#each apiKeys as key (key.id)}- <li class="px-4 py-3">- <div class="flex items-start justify-between gap-2">- <div class="min-w-0 flex-1">- <div class="truncate text-sm font-medium">{key.name}</div>- {#if key.description}- <div class="mt-0.5 truncate text-xs text-muted-foreground">{key.description}</div>- {/if}- </div>- <ArcaneButton- action="remove"- tone="ghost"- size="sm"- icon={TrashIcon}- customLabel={m.common_delete()}- showLabel={false}- class="shrink-0 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"- onclick={() => deleteApiKey(key.id, key.name)}- />- </div>- <div class="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">- <code class="rounded bg-muted/40 px-1.5 py-0.5 font-mono">{key.keyPrefix}…</code>- {#if formatDate(key.createdAt)}- <span>{m.common_created()} {formatDate(key.createdAt)}</span>- <span aria-hidden="true">·</span>- {/if}- <span>{m.last_used()} {formatRelativeTime(key.lastUsedAt) || m.common_never()}</span>- </div>- </li>- {/each}- </ul>- {/if}- </div>- </section>-- <PasskeySettings />-- {#if !autoLoginEnabled}- <section class="space-y-5">- <div class="flex items-center gap-2">- <ShieldAlertIcon class="size-4 text-destructive" />- <div>- <h2 class="text-base font-semibold tracking-tight sm:text-lg">{m.account_danger_zone()}</h2>- <p class="mt-1 text-xs text-muted-foreground sm:text-sm">{m.account_danger_zone_desc()}</p>- </div>- </div>- <div class="rounded-xl border border-destructive/30 bg-destructive/5 p-4">- <div class="grid gap-4 sm:grid-cols-2">- <div class="space-y-2">- <div class="text-sm font-medium">{m.account_signout_other()}</div>- <p class="text-xs text-muted-foreground">{m.account_signout_other_desc()}</p>- <ArcaneButton- action="restart"- tone="outline"- size="sm"- customLabel={m.account_signout_other()}- onclick={logoutAllOther}- loading={revokingAll}- disabled={revokingAll}- />- </div>-- <div class="space-y-2">- <div class="text-sm font-medium">{m.common_log_out()}</div>- <p class="text-xs text-muted-foreground">{m.account_signout_this()}</p>- <form action="/logout" method="POST">- <ArcaneButton- action="cancel"- tone="outline"- size="sm"- customLabel={m.common_log_out()}- icon={LogoutIcon}- type="submit"- class="border-destructive/30 text-destructive hover:bg-destructive/10 hover:text-destructive"- />- </form>- </div>- </div>- </div>- </section>- {/if}+ <AccountApiKeysPanel />+ <AccountSecurityPanel /></Tabs.Content><Tabs.Content value="preferences" class="mt-6">- <div class="space-y-10">- <!-- General -->- <section>- <h3 class="text-xs font-semibold tracking-wide text-muted-foreground uppercase">{m.general_title()}</h3>- <div class="mt-4 divide-y divide-border/40 [&>*]:py-4 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0">- <SettingsRow label={m.language()} description={m.account_language_desc()} layout="inline">- <LocalePicker inline id="accountLocalePicker" />- </SettingsRow>-- <SettingsRow label={m.time_format()} description={m.account_time_format_desc()} layout="inline">- <TimeFormatPicker id="accountTimeFormatPicker" />- </SettingsRow>- </div>- </section>-- <!-- Appearance -->- <section>- <h3 class="text-xs font-semibold tracking-wide text-muted-foreground uppercase">{m.appearance_title()}</h3>- <div class="mt-4 divide-y divide-border/40 [&>*]:py-4 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0">- <SettingsRow label={m.account_theme()} description={m.appearance_theme_current_user_description()} layout="inline">- <ThemeModeSelector />- </SettingsRow>-- <SettingsRow label={m.font_size()} description={m.font_size_description()} layout="inline">- <FontSizePicker />- </SettingsRow>-- <SettingsRow label={m.icon_catalog()} description={m.icon_catalog_description()} layout="inline">- <div class="w-52">- <SelectWithLabel- id="account-icon-catalog"- label={m.icon_catalog()}- hideLabel- triggerSize="sm"- value={iconCatalogValue}- options={iconCatalogOptions}- onValueChange={(value) => void savePreferences({ iconCatalog: value as IconCatalog })}- />- </div>- </SettingsRow>-- <SettingsRow label={m.application_theme()} description={m.application_theme_description()}>- <ApplicationThemePicker- selectedTheme={applicationThemeValue}- accentColor={accentColorValue}- onSelect={(value) => savePreferencesDebounced({ applicationTheme: value })}- />- </SettingsRow>-- <SettingsRow label={m.accent_color()} description={m.accent_color_description()}>- <AccentColorPicker- previousColor={accentColorValue}- selectedColor={accentColorValue}- onSelect={(value) => savePreferencesDebounced({ accentColor: value })}- />- </SettingsRow>-- <SettingsRow label={m.oled_mode()} description={m.oled_mode_description()} layout="inline">- {#snippet helpText()}- {#if !isDefaultApplicationTheme}- <p class="mt-1 text-xs text-muted-foreground/70 italic">{m.oled_mode_requires_default_theme()}</p>- {:else if !isDarkMode}- <p class="mt-1 text-xs text-muted-foreground/70 italic">{m.oled_mode_requires_dark()}</p>- {/if}- {/snippet}- <Switch- id="account-oled-mode"- checked={oledModeEnabled}- disabled={!isDefaultApplicationTheme}- onCheckedChange={(checked) => {- applyOledMode(checked);- void savePreferences({ oledMode: checked });- }}- />- </SettingsRow>-- <SettingsRow label={m.glass_effects()} description={m.glass_effects_description()} layout="inline">- <Switch- id="account-glass-effects"- checked={glassEffectsEnabled}- onCheckedChange={(checked) => {- applyGlassEffects(checked);- void savePreferences({ glassEffectsEnabled: checked });- }}- />- </SettingsRow>-- <SettingsRow label={m.interface_animations()} description={m.interface_animations_description()} layout="inline">- <Switch- id="account-animations"- checked={animationsEnabled}- onCheckedChange={(checked) => {- applyInterfaceAnimations(checked);- void savePreferences({ animationsEnabled: checked });- }}- />- </SettingsRow>- </div>- </section>-- <!-- Navigation -->- <section>- <h3 class="text-xs font-semibold tracking-wide text-muted-foreground uppercase">{m.navigation_title()}</h3>- <div class="mt-4 divide-y divide-border/40 [&>*]:py-4 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0">- <SettingsRow- label={m.navigation_default_landing_page_label()}- description={m.navigation_default_landing_page_description()}- layout="inline"- >- <div class="w-52">- <SelectWithLabel- id="account-default-landing-page"- label={m.navigation_default_landing_page_label()}- hideLabel- triggerSize="sm"- value={landingValue}- options={landingPageOptions}- onValueChange={(value) => void savePreferences({ defaultLandingPage: value })}- />- </div>- </SettingsRow>-- <SettingsRow- label={m.navigation_sidebar_hover_expansion_label()}- description={m.navigation_sidebar_hover_expansion_description()}- layout="inline"- >- <Switch- id="account-sidebar-hover-expansion"- checked={sidebarHoverExpansionEnabled}- onCheckedChange={(checked) => void savePreferences({ sidebarHoverExpansion: checked })}- />- </SettingsRow>-- <SettingsRow- label={m.navigation_keyboard_shortcuts_label()}- description={m.navigation_keyboard_shortcuts_description()}- layout="inline"- >- <Switch- id="account-keyboard-shortcuts"- checked={keyboardShortcutsEnabled}- onCheckedChange={(checked) => void savePreferences({ keyboardShortcutsEnabled: checked })}- />- </SettingsRow>- </div>- </section>-- <!-- Mobile navigation -->- <section>- <h3 class="text-xs font-semibold tracking-wide text-muted-foreground uppercase">- {m.navigation_mobile_appearance_title()}- </h3>- <div class="mt-4 divide-y divide-border/40 [&>*]:py-4 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0">- <SettingsRow label={m.navigation_mode_label()} description={m.navigation_mode_description()} layout="inline">- <div class="inline-flex rounded-lg bg-muted/40 p-0.5">- <button- type="button"- aria-pressed={mobileNavigationMode === 'floating'}- onclick={() => selectMobileNavigationMode('floating')}- class={cn(- 'inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors',- mobileNavigationMode === 'floating'- ? 'bg-background text-foreground shadow-sm'- : 'text-muted-foreground hover:text-foreground'- )}- >- <MonitorSpeakerIcon class="size-3.5" />- {m.navigation_mode_floating()}- </button>- <button- type="button"- aria-pressed={mobileNavigationMode === 'docked'}- onclick={() => selectMobileNavigationMode('docked')}- class={cn(- 'inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors',- mobileNavigationMode === 'docked'- ? 'bg-background text-foreground shadow-sm'- : 'text-muted-foreground hover:text-foreground'- )}- >- <DockIcon class="size-3.5" />- {m.navigation_mode_docked()}- </button>- </div>- </SettingsRow>-- <SettingsRow- label={m.navigation_show_labels_label()}- description={m.navigation_show_labels_description()}- layout="inline"- >- <Switch- id="account-mobile-nav-labels"- checked={mobileNavigationShowLabels}- onCheckedChange={(checked) => void savePreferences({ mobileNavigationShowLabels: checked })}- />- </SettingsRow>- </div>- </section>- </div>+ <AccountPreferencesPanel /></Tabs.Content></Tabs.Root>{:else}- <div class="py-12 text-center text-sm text-muted-foreground">Loading account…</div>+ <div class="py-12 text-center text-sm text-muted-foreground">{m.account_loading()}</div>{/if}</div>--<ApiKeyFormSheet- bind:open={showCreateKeyForm}- apiKeyToEdit={null}- mode="personal"- onSubmit={createApiKey}- isLoading={creatingKey}-/>diff --git a/frontend/src/routes/(app)/account/account-api-keys-panel.svelte b/frontend/src/routes/(app)/account/account-api-keys-panel.sveltenew file mode 100644index 000000000..1fb591ca4--- /dev/null+++ b/frontend/src/routes/(app)/account/account-api-keys-panel.svelte@@ -0,0 +1,182 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import { toast } from 'svelte-sonner';+ import ApiKeyFormSheet from '#lib/components/sheets/api-key-form-sheet.svelte';+ import { ArcaneButton } from '#lib/components/arcane-button';+ import { apiKeyService } from '#lib/services/api-key-service';+ import type { ApiKey, ApiKeyCreated, ApiKeyPermissionGrant, CreateUserApiKey } from '#lib/types/auth';+ import { AddIcon, ApiKeyIcon, CopyIcon, TrashIcon } from '#lib/icons';+ import { formatDate, formatRelativeTime } from '#lib/utils/formatting';+ import { m } from '#lib/paraglide/messages';+ import { confirmAndRun } from '#lib/utils/bulk-actions';++ let apiKeys = $state<ApiKey[]>([]);+ let apiKeysLoading = $state(false);+ let showCreateKeyForm = $state(false);+ let creatingKey = $state(false);+ let deletingKeyId = $state<string | null>(null);+ let createdKey = $state<ApiKeyCreated | null>(null);++ async function loadApiKeys() {+ apiKeysLoading = true;+ try {+ apiKeys = await apiKeyService.listMine();+ } catch (error) {+ toast.error(error instanceof Error ? error.message : m.common_refresh_failed({ resource: m.api_key_page_title() }));+ } finally {+ apiKeysLoading = false;+ }+ }++ async function createApiKey({+ apiKey+ }: {+ apiKey: { name: string; description?: string; expiresAt?: string; permissions?: ApiKeyPermissionGrant[] };+ isEditMode: boolean;+ apiKeyId?: string;+ }) {+ creatingKey = true;+ try {+ const payload: CreateUserApiKey = {+ name: apiKey.name,+ description: apiKey.description,+ expiresAt: apiKey.expiresAt+ };+ createdKey = await apiKeyService.createMine(payload);+ showCreateKeyForm = false;+ await loadApiKeys();+ } catch (error) {+ toast.error(error instanceof Error ? error.message : m.api_key_create_failed({ name: apiKey.name }));+ } finally {+ creatingKey = false;+ }+ }++ function deleteApiKey(id: string, name: string) {+ const safeName = name.trim() || m.common_unknown();+ confirmAndRun({+ title: m.api_key_delete_title({ name: safeName }),+ message: m.api_key_delete_message({ name: safeName }),+ confirmLabel: m.common_delete(),+ destructive: true,+ setLoading: (loading) => (deletingKeyId = loading ? id : null),+ run: () => apiKeyService.deleteMine(id),+ failureMessage: m.api_key_delete_failed({ name: safeName }),+ onSuccess: async () => {+ toast.success(m.account_api_key_deleted());+ await loadApiKeys();+ }+ });+ }++ function copyKeyToClipboard(key: string) {+ void navigator.clipboard.writeText(key);+ toast.success(m.common_key_copied());+ }++ onMount(() => {+ void loadApiKeys();+ });+</script>++<section class="space-y-5">+ <div class="flex flex-wrap items-start justify-between gap-3">+ <div class="min-w-0">+ <h2 class="text-base font-semibold tracking-tight sm:text-lg">{m.account_api_keys_title()}</h2>+ <p class="mt-1 text-xs text-muted-foreground sm:text-sm">{m.account_api_keys_description()}</p>+ </div>+ {#if !showCreateKeyForm && !createdKey}+ <ArcaneButton+ action="create"+ tone="outline"+ size="sm"+ customLabel={m.account_new_key()}+ icon={AddIcon}+ class="shrink-0"+ onclick={() => (showCreateKeyForm = true)}+ />+ {/if}+ </div>+ {#if createdKey}+ <div class="mb-4 space-y-3 rounded-lg border border-primary/30 bg-primary/5 p-4">+ <div>+ <div class="truncate text-sm font-semibold">{m.api_key_created_title()}: {createdKey.name}</div>+ <p class="mt-1 text-xs text-muted-foreground">{m.api_key_save_warning()}</p>+ </div>+ <code class="block truncate rounded border bg-background px-3 py-2 font-mono text-xs">+ {createdKey.key}+ </code>+ <div class="flex flex-wrap justify-end gap-2">+ <ArcaneButton+ action="base"+ tone="outline"+ size="sm"+ customLabel={m.common_copy()}+ icon={CopyIcon}+ onclick={() => copyKeyToClipboard(createdKey!.key)}+ />+ <ArcaneButton+ action="cancel"+ tone="ghost"+ size="sm"+ customLabel={m.common_ive_saved_it()}+ onclick={() => (createdKey = null)}+ />+ </div>+ </div>+ {/if}++ <div class="overflow-hidden rounded-xl border border-border/60 bg-card/30">+ {#if apiKeysLoading && apiKeys.length === 0}+ <div class="p-6 text-center text-sm text-muted-foreground">{m.common_loading()}</div>+ {:else if apiKeys.length === 0}+ <div class="p-6 text-center text-sm text-muted-foreground">+ <ApiKeyIcon class="mx-auto mb-2 size-8 opacity-40" />+ {m.api_keys_empty()}+ </div>+ {:else}+ <ul class="divide-y divide-border/60">+ {#each apiKeys as key (key.id)}+ <li class="px-4 py-3">+ <div class="flex items-start justify-between gap-2">+ <div class="min-w-0 flex-1">+ <div class="truncate text-sm font-medium">{key.name}</div>+ {#if key.description}+ <div class="mt-0.5 truncate text-xs text-muted-foreground">{key.description}</div>+ {/if}+ </div>+ <ArcaneButton+ action="remove"+ tone="ghost"+ size="sm"+ icon={TrashIcon}+ customLabel={m.common_delete()}+ showLabel={false}+ loading={deletingKeyId === key.id}+ disabled={deletingKeyId !== null}+ class="shrink-0 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"+ onclick={() => deleteApiKey(key.id, key.name)}+ />+ </div>+ <div class="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">+ <code class="rounded bg-muted/40 px-1.5 py-0.5 font-mono">{key.keyPrefix}…</code>+ {#if formatDate(key.createdAt)}+ <span>{m.common_created()} {formatDate(key.createdAt)}</span>+ <span aria-hidden="true">·</span>+ {/if}+ <span>{m.last_used()} {formatRelativeTime(key.lastUsedAt) || m.common_never()}</span>+ </div>+ </li>+ {/each}+ </ul>+ {/if}+ </div>+</section>++<ApiKeyFormSheet+ bind:open={showCreateKeyForm}+ apiKeyToEdit={null}+ mode="personal"+ onSubmit={createApiKey}+ isLoading={creatingKey}+/>diff --git a/frontend/src/routes/(app)/account/account-preferences-panel.svelte b/frontend/src/routes/(app)/account/account-preferences-panel.sveltenew file mode 100644index 000000000..b5380dd9e--- /dev/null+++ b/frontend/src/routes/(app)/account/account-preferences-panel.svelte@@ -0,0 +1,256 @@+<script lang="ts">+ import { mode } from 'mode-watcher';+ import ThemeModeSelector from '#lib/components/theme-mode/theme-mode-selector.svelte';+ import LocalePicker from '#lib/components/locale-picker.svelte';+ import TimeFormatPicker from '#lib/components/time-format-picker.svelte';+ import FontSizePicker from '#lib/components/font-size-picker.svelte';+ import SettingsRow from '#lib/components/settings/settings-row.svelte';+ import SelectWithLabel from '#lib/components/form/select-with-label.svelte';+ import AccentColorPicker from '#lib/components/accent-color/accent-color-picker.svelte';+ import ApplicationThemePicker from '#lib/components/application-theme/application-theme-picker.svelte';+ import { Switch } from '#lib/components/ui/switch';+ import { DEFAULT_LANDING_PAGE, getLandingPageNavItems } from '#lib/config/navigation-config';+ import { resetNavigationVisibility } from '#lib/utils/navigation';+ import { applyGlassEffects, applyInterfaceAnimations, applyOledMode, DEFAULT_ACCENT_COLOR } from '#lib/utils/theme';+ import { debounced } from '#lib/utils/ws';+ import { m } from '#lib/paraglide/messages';+ import { userService } from '#lib/services/user-service';+ import userStore from '#lib/stores/user-store';+ import type { UserPreferences } from '#lib/types/auth';+ import type { ApplicationTheme, IconCatalog } from '#lib/types/settings';+ import { DockIcon, MonitorSpeakerIcon } from '#lib/icons';+ import { cn } from '#lib/utils';+ import { toast } from 'svelte-sonner';++ const currentUser = $derived($userStore);+ const preferences = $derived(currentUser?.preferences ?? {});+ const applicationThemeValue = $derived<ApplicationTheme>(preferences.applicationTheme ?? 'default');+ const accentColorValue = $derived(+ preferences.accentColor && preferences.accentColor !== 'default' ? preferences.accentColor : DEFAULT_ACCENT_COLOR+ );+ const iconCatalogValue = $derived(preferences.iconCatalog ?? 'selfhst');+ const oledModeEnabled = $derived(preferences.oledMode ?? false);+ const glassEffectsEnabled = $derived(preferences.glassEffectsEnabled ?? true);+ const animationsEnabled = $derived(preferences.animationsEnabled ?? true);+ const sidebarHoverExpansionEnabled = $derived(preferences.sidebarHoverExpansion ?? true);+ const keyboardShortcutsEnabled = $derived(preferences.keyboardShortcutsEnabled ?? true);+ const mobileNavigationMode = $derived(preferences.mobileNavigationMode ?? 'floating');+ const mobileNavigationShowLabels = $derived(preferences.mobileNavigationShowLabels ?? true);+ const isDarkMode = $derived(mode.current === 'dark');+ const isDefaultApplicationTheme = $derived(applicationThemeValue === 'default');++ const iconCatalogOptions = $derived([+ { value: 'selfhst', label: m.icon_catalog_selfhst(), description: m.icon_catalog_selfhst_description() },+ {+ value: 'dashboard-icons',+ label: m.icon_catalog_dashboard_icons(),+ description: m.icon_catalog_dashboard_icons_description()+ }+ ]);+ const landingPageOptions = $derived(getLandingPageNavItems().map((item) => ({ value: item.url, label: item.title })));+ const landingValue = $derived.by(() => {+ const current = preferences.defaultLandingPage ?? DEFAULT_LANDING_PAGE;+ return landingPageOptions.some((option) => option.value === current) ? current : DEFAULT_LANDING_PAGE;+ });++ async function savePreferences(patch: Partial<UserPreferences>) {+ const previous = currentUser;+ if (!previous) return;+ try {+ const updated = await userService.updateMyProfile({ preferences: patch });+ await userStore.setUser(updated);+ } catch (error) {+ toast.error(error instanceof Error ? error.message : m.common_update_failed({ resource: m.account_preferences() }));+ await userStore.setUser(previous);+ }+ }++ let pendingPreferences: Partial<UserPreferences> = {};+ const flushPreferences = debounced(() => {+ const patch = pendingPreferences;+ pendingPreferences = {};+ void savePreferences(patch);+ }, 400);++ function savePreferencesDebounced(patch: Partial<UserPreferences>) {+ pendingPreferences = { ...pendingPreferences, ...patch };+ flushPreferences();+ }++ function selectMobileNavigationMode(value: 'floating' | 'docked') {+ if (value === mobileNavigationMode) return;+ resetNavigationVisibility();+ void savePreferences({ mobileNavigationMode: value });+ }+</script>++<div class="space-y-10">+ <section>+ <h3 class="text-xs font-semibold tracking-wide text-muted-foreground uppercase">{m.general_title()}</h3>+ <div class="mt-4 divide-y divide-border/40 [&>*]:py-4 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0">+ <SettingsRow label={m.language()} description={m.account_language_desc()} layout="inline">+ <LocalePicker inline id="accountLocalePicker" />+ </SettingsRow>+ <SettingsRow label={m.time_format()} description={m.account_time_format_desc()} layout="inline">+ <TimeFormatPicker id="accountTimeFormatPicker" />+ </SettingsRow>+ </div>+ </section>++ <section>+ <h3 class="text-xs font-semibold tracking-wide text-muted-foreground uppercase">{m.appearance_title()}</h3>+ <div class="mt-4 divide-y divide-border/40 [&>*]:py-4 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0">+ <SettingsRow label={m.account_theme()} description={m.appearance_theme_current_user_description()} layout="inline">+ <ThemeModeSelector />+ </SettingsRow>+ <SettingsRow label={m.font_size()} description={m.font_size_description()} layout="inline">+ <FontSizePicker />+ </SettingsRow>+ <SettingsRow label={m.icon_catalog()} description={m.icon_catalog_description()} layout="inline">+ <div class="w-52">+ <SelectWithLabel+ id="account-icon-catalog"+ label={m.icon_catalog()}+ hideLabel+ triggerSize="sm"+ value={iconCatalogValue}+ options={iconCatalogOptions}+ onValueChange={(value) => void savePreferences({ iconCatalog: value as IconCatalog })}+ />+ </div>+ </SettingsRow>+ <SettingsRow label={m.application_theme()} description={m.application_theme_description()}>+ <ApplicationThemePicker+ selectedTheme={applicationThemeValue}+ accentColor={accentColorValue}+ onSelect={(value) => savePreferencesDebounced({ applicationTheme: value })}+ />+ </SettingsRow>+ <SettingsRow label={m.accent_color()} description={m.accent_color_description()}>+ <AccentColorPicker+ previousColor={accentColorValue}+ selectedColor={accentColorValue}+ onSelect={(value) => savePreferencesDebounced({ accentColor: value })}+ />+ </SettingsRow>+ <SettingsRow label={m.oled_mode()} description={m.oled_mode_description()} layout="inline">+ {#snippet helpText()}+ {#if !isDefaultApplicationTheme}+ <p class="mt-1 text-xs text-muted-foreground/70 italic">{m.oled_mode_requires_default_theme()}</p>+ {:else if !isDarkMode}+ <p class="mt-1 text-xs text-muted-foreground/70 italic">{m.oled_mode_requires_dark()}</p>+ {/if}+ {/snippet}+ <Switch+ id="account-oled-mode"+ checked={oledModeEnabled}+ disabled={!isDefaultApplicationTheme}+ onCheckedChange={(checked) => {+ applyOledMode(checked);+ void savePreferences({ oledMode: checked });+ }}+ />+ </SettingsRow>+ <SettingsRow label={m.glass_effects()} description={m.glass_effects_description()} layout="inline">+ <Switch+ id="account-glass-effects"+ checked={glassEffectsEnabled}+ onCheckedChange={(checked) => {+ applyGlassEffects(checked);+ void savePreferences({ glassEffectsEnabled: checked });+ }}+ />+ </SettingsRow>+ <SettingsRow label={m.interface_animations()} description={m.interface_animations_description()} layout="inline">+ <Switch+ id="account-animations"+ checked={animationsEnabled}+ onCheckedChange={(checked) => {+ applyInterfaceAnimations(checked);+ void savePreferences({ animationsEnabled: checked });+ }}+ />+ </SettingsRow>+ </div>+ </section>++ <section>+ <h3 class="text-xs font-semibold tracking-wide text-muted-foreground uppercase">{m.navigation_title()}</h3>+ <div class="mt-4 divide-y divide-border/40 [&>*]:py-4 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0">+ <SettingsRow+ label={m.navigation_default_landing_page_label()}+ description={m.navigation_default_landing_page_description()}+ layout="inline"+ >+ <div class="w-52">+ <SelectWithLabel+ id="account-default-landing-page"+ label={m.navigation_default_landing_page_label()}+ hideLabel+ triggerSize="sm"+ value={landingValue}+ options={landingPageOptions}+ onValueChange={(value) => void savePreferences({ defaultLandingPage: value })}+ />+ </div>+ </SettingsRow>+ <SettingsRow+ label={m.navigation_sidebar_hover_expansion_label()}+ description={m.navigation_sidebar_hover_expansion_description()}+ layout="inline"+ >+ <Switch+ id="account-sidebar-hover-expansion"+ checked={sidebarHoverExpansionEnabled}+ onCheckedChange={(checked) => void savePreferences({ sidebarHoverExpansion: checked })}+ />+ </SettingsRow>+ <SettingsRow+ label={m.navigation_keyboard_shortcuts_label()}+ description={m.navigation_keyboard_shortcuts_description()}+ layout="inline"+ >+ <Switch+ id="account-keyboard-shortcuts"+ checked={keyboardShortcutsEnabled}+ onCheckedChange={(checked) => void savePreferences({ keyboardShortcutsEnabled: checked })}+ />+ </SettingsRow>+ </div>+ </section>++ <section>+ <h3 class="text-xs font-semibold tracking-wide text-muted-foreground uppercase">+ {m.navigation_mobile_appearance_title()}+ </h3>+ <div class="mt-4 divide-y divide-border/40 [&>*]:py-4 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0">+ <SettingsRow label={m.navigation_mode_label()} description={m.navigation_mode_description()} layout="inline">+ <div class="inline-flex rounded-lg bg-muted/40 p-0.5">+ {#each [{ value: 'floating' as const, label: m.navigation_mode_floating(), icon: MonitorSpeakerIcon }, { value: 'docked' as const, label: m.navigation_mode_docked(), icon: DockIcon }] as option (option.value)}+ <button+ type="button"+ aria-pressed={mobileNavigationMode === option.value}+ onclick={() => selectMobileNavigationMode(option.value)}+ class={cn(+ 'inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors',+ mobileNavigationMode === option.value+ ? 'bg-background text-foreground shadow-sm'+ : 'text-muted-foreground hover:text-foreground'+ )}+ >+ <option.icon class="size-3.5" />+ {option.label}+ </button>+ {/each}+ </div>+ </SettingsRow>+ <SettingsRow label={m.navigation_show_labels_label()} description={m.navigation_show_labels_description()} layout="inline">+ <Switch+ id="account-mobile-nav-labels"+ checked={mobileNavigationShowLabels}+ onCheckedChange={(checked) => void savePreferences({ mobileNavigationShowLabels: checked })}+ />+ </SettingsRow>+ </div>+ </section>+</div>diff --git a/frontend/src/routes/(app)/account/account-security-panel.svelte b/frontend/src/routes/(app)/account/account-security-panel.sveltenew file mode 100644index 000000000..a81a1ba87--- /dev/null+++ b/frontend/src/routes/(app)/account/account-security-panel.svelte@@ -0,0 +1,143 @@+<script lang="ts">+ import { fromStore } from 'svelte/store';+ import { toast } from 'svelte-sonner';+ import PasskeySettings from '#lib/components/auth/passkey-settings.svelte';+ import { ArcaneButton } from '#lib/components/arcane-button';+ import TextInputWithLabel from '#lib/components/form/text-input-with-label.svelte';+ import { LogoutIcon, ShieldAlertIcon } from '#lib/icons';+ import { m } from '#lib/paraglide/messages';+ import { userService } from '#lib/services/user-service';+ import settingsStore from '#lib/stores/config-store';+ import userStore from '#lib/stores/user-store';++ const currentUser = $derived($userStore);+ const isOidcUser = $derived(Boolean(currentUser?.oidcSubjectId));+ const autoLogin = fromStore(settingsStore.autoLoginEnabled);+ const autoLoginEnabled = $derived(autoLogin.current);++ let currentPassword = $state('');+ let newPassword = $state('');+ let confirmPassword = $state('');+ let passwordSaving = $state(false);+ let revokingAll = $state(false);+ const passwordValid = $derived(currentPassword.length > 0 && newPassword.length >= 8 && newPassword === confirmPassword);++ async function changePassword() {+ if (!passwordValid || passwordSaving) return;+ passwordSaving = true;+ try {+ await userService.changePassword({ currentPassword, newPassword });+ toast.success(m.account_password_updated());+ currentPassword = '';+ newPassword = '';+ confirmPassword = '';+ } catch (error) {+ toast.error(error instanceof Error ? error.message : m.common_update_failed({ resource: m.common_password() }));+ } finally {+ passwordSaving = false;+ }+ }++ async function logoutAllOther() {+ if (revokingAll) return;+ revokingAll = true;+ try {+ await userService.logoutAllOtherSessions();+ toast.success(m.account_sessions_signed_out());+ } catch (error) {+ toast.error(error instanceof Error ? error.message : m.common_action_failed());+ } finally {+ revokingAll = false;+ }+ }+</script>++{#if !isOidcUser}+ <section class="space-y-5">+ <div>+ <h2 class="text-base font-semibold tracking-tight sm:text-lg">{m.common_password()}</h2>+ <p class="mt-1 text-xs text-muted-foreground sm:text-sm">{m.account_password_desc()}</p>+ </div>+ <TextInputWithLabel+ id="account-current-password"+ type="password"+ bind:value={currentPassword}+ label={m.account_current_password()}+ autocomplete="current-password"+ />+ <div class="grid gap-5 sm:grid-cols-2">+ <TextInputWithLabel+ id="account-new-password"+ type="password"+ bind:value={newPassword}+ label={m.account_new_password()}+ helpText={m.account_password_min_length()}+ autocomplete="new-password"+ />+ <TextInputWithLabel+ id="account-confirm-password"+ type="password"+ bind:value={confirmPassword}+ label={m.account_confirm_password()}+ error={confirmPassword.length > 0 && confirmPassword !== newPassword ? m.account_passwords_dont_match() : null}+ autocomplete="new-password"+ />+ </div>+ <div class="flex justify-end">+ <ArcaneButton+ action="save"+ customLabel={m.account_update_password()}+ onclick={changePassword}+ loading={passwordSaving}+ disabled={!passwordValid || passwordSaving}+ />+ </div>+ </section>+{/if}++<PasskeySettings />++{#if !autoLoginEnabled}+ <section class="space-y-5">+ <div class="flex items-center gap-2">+ <ShieldAlertIcon class="size-4 text-destructive" />+ <div>+ <h2 class="text-base font-semibold tracking-tight sm:text-lg">{m.account_danger_zone()}</h2>+ <p class="mt-1 text-xs text-muted-foreground sm:text-sm">{m.account_danger_zone_desc()}</p>+ </div>+ </div>+ <div class="rounded-xl border border-destructive/30 bg-destructive/5 p-4">+ <div class="grid gap-4 sm:grid-cols-2">+ <div class="space-y-2">+ <div class="text-sm font-medium">{m.account_signout_other()}</div>+ <p class="text-xs text-muted-foreground">{m.account_signout_other_desc()}</p>+ <ArcaneButton+ action="restart"+ tone="outline"+ size="sm"+ customLabel={m.account_signout_other()}+ onclick={logoutAllOther}+ loading={revokingAll}+ disabled={revokingAll}+ />+ </div>++ <div class="space-y-2">+ <div class="text-sm font-medium">{m.common_log_out()}</div>+ <p class="text-xs text-muted-foreground">{m.account_signout_this()}</p>+ <form action="/logout" method="POST">+ <ArcaneButton+ action="cancel"+ tone="outline"+ size="sm"+ customLabel={m.common_log_out()}+ icon={LogoutIcon}+ type="submit"+ class="border-destructive/30 text-destructive hover:bg-destructive/10 hover:text-destructive"+ />+ </form>+ </div>+ </div>+ </div>+ </section>+{/if}diff --git a/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte b/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelteindex f4d2cfc1e..abbca91a5 100644--- a/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte+++ b/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte@@ -147,13 +147,13 @@accessorKey: 'enabled',title: m.common_status(),sortable: true,- cell: enabledStatusCol+ cellComponent: EnabledStatusCell},{accessorKey: 'createdAt',title: m.common_created(),sortable: true,- cell: createdAtCol+ cellComponent: CreatedAtCell}] satisfies ColumnSpec<GitRepository>[];@@ -167,15 +167,6 @@];</script>-<!-- fallow-ignore-next-line code-duplication -- cell wrapper snippet around the shared EnabledStatusCell; arcane-table cell: API requires a per-table Snippet -->-{#snippet enabledStatusCol({ value }: { value: unknown })}- <EnabledStatusCell {value} />-{/snippet}--{#snippet createdAtCol({ value }: { value: unknown })}- <CreatedAtCell {value} />-{/snippet}-{#snippet NameCell({ value }: { value: unknown })}<div class="flex items-center gap-2"><GitBranchIcon class="size-4 text-muted-foreground" />@@ -202,7 +193,6 @@item,mobileFieldVisibility}: {- row: any;item: GitRepository;mobileFieldVisibility: FieldVisibility;})}diff --git a/frontend/src/routes/(app)/customize/registries/registry-table.svelte b/frontend/src/routes/(app)/customize/registries/registry-table.svelteindex 8be84ce9d..296e72f62 100644--- a/frontend/src/routes/(app)/customize/registries/registry-table.svelte+++ b/frontend/src/routes/(app)/customize/registries/registry-table.svelte@@ -3,10 +3,8 @@import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';import { Spinner } from '#lib/components/ui/spinner/index.js';- import { openConfirmDialog } from '#lib/components/confirm-dialog';import { toast } from 'svelte-sonner';- import { handleApiResultWithCallbacks } from '#lib/utils/api';- import { tryCatch } from '#lib/utils/api';+ import { handleApiResultWithCallbacks, tryCatch } from '#lib/utils/api';import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared';import type { ContainerRegistry, ContainerRegistryPullUsage } from '#lib/types/docker';import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '#lib/components/arcane-table';@@ -19,6 +17,7 @@import { hasPermission } from '#lib/utils/auth';import { getRegistryDisplayName } from '#lib/utils/registry';import IfPermitted from '#lib/components/if-permitted.svelte';+ import { bulkConfirmAndRun, confirmAndRun } from '#lib/utils/bulk-actions';let {registries = $bindable(),@@ -54,66 +53,49 @@return m.registries_observed_pulls_value({ count: usage.observedPulls });}- async function handleDeleteSelected(ids: string[]) {+ function handleDeleteSelected(ids: string[]) {if (!ids?.length) return;+ const selectedRegistryIds = [...ids];- openConfirmDialog({- title: m.registries_remove_selected_title({ count: ids.length }),- message: m.registries_remove_selected_message({ count: ids.length }),- confirm: {- label: m.common_remove(),- destructive: true,- action: async () => {- let successCount = 0;- let failureCount = 0;- for (const id of ids) {- removingId = id;- const reg = registries.data.find((r) => r.id === id);- const result = await tryCatch(containerRegistryService.deleteRegistry(id));- if (result.error) {- failureCount++;- toast.error(m.registries_delete_failed({ url: reg?.url ?? m.common_unknown() }));- } else {- successCount++;- }- }-- if (successCount > 0) {- toast.success(m.registries_bulk_remove_success({ count: successCount }));- registries = await containerRegistryService.getRegistries(requestOptions);- }- if (failureCount > 0) toast.error(m.registries_bulk_remove_failed({ count: failureCount }));-- selectedIds = [];- removingId = null;- }- }+ bulkConfirmAndRun({+ ids: selectedRegistryIds,+ title: m.registries_remove_selected_title({ count: selectedRegistryIds.length }),+ message: m.registries_remove_selected_message({ count: selectedRegistryIds.length }),+ confirmLabel: m.common_remove(),+ destructive: true,+ run: (id) => {+ removingId = id;+ return containerRegistryService.deleteRegistry(id);+ },+ messages: {+ success: (count) => m.registries_bulk_remove_success({ count }),+ partial: (success, total, failed) =>+ m.common_bulk_remove_partial({ success, total, failed, resource: m.registries_title() }),+ failure: () => m.registries_bulk_remove_failed({ count: selectedRegistryIds.length })+ },+ setLoading: (loading) => (isLoading.removing = loading),+ onComplete: async ({ success }) => {+ removingId = null;+ if (success > 0) registries = await containerRegistryService.getRegistries(requestOptions);+ },+ clearSelection: () => (selectedIds = []),+ sequential: true});}- async function handleDeleteOne(id: string, url: string) {+ function handleDeleteOne(id: string, url: string) {const safeUrl = url ?? m.common_unknown();- openConfirmDialog({+ confirmAndRun({title: m.common_remove_title({ resource: m.resource_registry() }),message: m.registries_remove_message({ url: safeUrl }),- confirm: {- label: m.common_remove(),- destructive: true,- action: async () => {- removingId = id;-- const result = await tryCatch(containerRegistryService.deleteRegistry(id));- handleApiResultWithCallbacks({- result,- message: m.registries_delete_failed({ url: safeUrl }),- setLoadingState: (value) => (value ? null : (removingId = null)),- onSuccess: async () => {- toast.success(m.common_delete_success({ resource: `${m.resource_registry()} "${safeUrl}"` }));- registries = await containerRegistryService.getRegistries(requestOptions);- removingId = null;- }- });- }+ confirmLabel: m.common_remove(),+ destructive: true,+ setLoading: (loading) => (removingId = loading ? id : null),+ run: () => containerRegistryService.deleteRegistry(id),+ failureMessage: m.registries_delete_failed({ url: safeUrl }),+ onSuccess: async () => {+ toast.success(m.common_delete_success({ resource: `${m.resource_registry()} "${safeUrl}"` }));+ registries = await containerRegistryService.getRegistries(requestOptions);}});}@@ -127,7 +109,8 @@message: m.registries_test_failed({ url: safeUrl }),setLoadingState: (value) => (value ? null : (testingId = null)),onSuccess: (resp) => {- const msg = (resp as any)?.message ?? m.common_unknown();+ const msg =+ resp && typeof resp === 'object' && 'message' in resp ? String(resp.message ?? m.common_unknown()) : m.common_unknown();toast.success(m.registries_test_success({ url: safeUrl, message: msg }));testingId = null;}@@ -158,7 +141,7 @@accessorKey: 'enabled',title: m.common_status(),sortable: true,- cell: enabledStatusCol+ cellComponent: EnabledStatusCell},{id: 'pullUsage',@@ -170,7 +153,7 @@accessorKey: 'createdAt',title: m.common_created(),sortable: true,- cell: createdAtCol+ cellComponent: CreatedAtCell}] satisfies ColumnSpec<ContainerRegistry>[];@@ -202,14 +185,6 @@let mobileFieldVisibility = $state<Record<string, boolean>>({});</script>-{#snippet enabledStatusCol({ value }: { value: unknown })}- <EnabledStatusCell {value} />-{/snippet}--{#snippet createdAtCol({ value }: { value: unknown })}- <CreatedAtCell {value} />-{/snippet}-{#snippet UrlCell({ item }: { item: ContainerRegistry })}<div class="flex flex-col"><span class="font-medium">{item.url || 'docker.io'}</span>diff --git a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelteindex ac4f370a2..bac069df5 100644--- a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte+++ b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte@@ -5,47 +5,38 @@import { type ActionButton } from '#lib/components/action-button-group/index.js';import { cn } from '#lib/utils';import { ArcaneButton } from '#lib/components/arcane-button/index.js';- import { Badge, badgeVariants } from '#lib/components/ui/badge';import PruneConfirmationDialog from '#lib/components/dialogs/prune-confirmation-dialog.svelte';import DockerInfoDialog from '#lib/components/dialogs/docker-info-dialog.svelte';import { Skeleton } from '#lib/components/ui/skeleton';- import * as Card from '#lib/components/ui/card/index.js';import { m } from '#lib/paraglide/messages';import { settingsService } from '#lib/services/settings-service';import { systemService } from '#lib/services/system-service';import { activityStore } from '#lib/stores/activity.store.svelte';import { dashboardStore } from '#lib/stores/dashboard.store.svelte';- import { environmentStore, LOCAL_DOCKER_ENVIRONMENT_ID } from '#lib/stores/environment.store.svelte';+ import { environmentStore } from '#lib/stores/environment.store.svelte';import userStore from '#lib/stores/user-store';import { hasAnyPermission, hasPermission } from '#lib/utils/auth';- import { formatDateTime, formatRelativeTime, parseInstant } from '#lib/utils/formatting';import type {DashboardActionItemKind,DashboardEnvironmentCardState,DashboardEnvironmentOverview,- DashboardOverviewSummary,- DashboardSnapshot,SystemStats} from '#lib/types/shared';import type { Environment } from '#lib/types/environment';import type { DockerInfo } from '#lib/types/docker';import type { PruneType, SystemPruneRequest } from '#lib/types/automation';- import type { Settings } from '#lib/types/settings';+ import type { AppVersionInformation, Settings } from '#lib/types/settings';import { extractApiErrorMessage, handleApiResultWithCallbacks } from '#lib/utils/api';import { tryCatch } from '#lib/utils/api';- import { isEnvironmentOnline, resolveEnvironmentStatus } from '#lib/utils/docker';+ import { isEnvironmentOnline } from '#lib/utils/docker';import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast';import { createStatsWebSocket, type ReconnectingWebSocket } from '#lib/utils/ws';- import { bytes } from '#lib/utils/formatting';import {ContainersIcon,- CpuIcon,EnvironmentsIcon,- GpuIcon,ImagesIcon,InfoIcon,InspectIcon,- MemoryStickIcon,RefreshIcon,TrashIcon,UpdateIcon,@@ -54,13 +45,21 @@LayoutGridIcon,LayoutListIcon} from '#lib/icons';- import DashboardMetricTile from './dash-metric-tile.svelte';- import DashboardEnvironmentUpgradeAction from './dashboard-environment-upgrade-action.svelte';import DashboardEnvironmentsTable, { type EnvironmentTableRow } from './dashboard-environments-table.svelte';+ import DashboardEnvironmentCard from './dashboard-environment-card.svelte';import { PersistedState } from 'runed';- import * as ArcaneTooltip from '#lib/components/arcane-tooltip';- import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';- import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';+ import {+ buildOverviewSummary,+ createBaseEnvironmentOverview,+ formatContainerOverviewLabel,+ formatImageOverviewLabel,+ formatVolumeOverviewLabel,+ getCpuMetric,+ getDiskMetric,+ getEnvironmentCardSortRank,+ getMemoryMetric,+ shouldLoadEnvironment+ } from './dashboard-overview';let {heroGreeting,@@ -72,7 +71,18 @@debugUpgrade?: boolean;} = $props();- const emptySnapshotSettings: DashboardSnapshot['settings'] = {};+ const DEBUG_VERSION_INFO: AppVersionInformation = {+ currentVersion: 'debug',+ displayVersion: 'debug',+ revision: 'debug',+ shortRevision: 'debug',+ goVersion: '',+ nodeVersion: '',+ svelteKitVersion: '',+ isSemverVersion: false,+ newestVersion: 'debug-v2',+ updateAvailable: true+ };type EnvironmentLiveStatsState = {stats: SystemStats | null;@@ -116,55 +126,6 @@return hasPermission('environments:update');}- function shouldLoadEnvironment(environment: Environment): boolean {- return environment.enabled && isEnvironmentOnline(environment);- }-- function createBaseEnvironmentOverview(environment: Environment): DashboardEnvironmentOverview {- return {- environment,- containers: { runningContainers: 0, stoppedContainers: 0, totalContainers: 0 },- imageUsageCounts: { imagesInuse: 0, imagesUnused: 0, totalImages: 0, totalImageSize: 0 },- actionItems: { items: [] },- settings: emptySnapshotSettings,- snapshotState: 'skipped'- };- }-- function getEnvironmentCardSortRank(environment: Environment): number {- if (shouldLoadEnvironment(environment)) {- return 0;- }-- if (environment.enabled) {- return 1;- }-- return 2;- }-- function buildOverviewSummaryFromItemsInternal(settledEnvironments: DashboardEnvironmentOverview[]): DashboardOverviewSummary {- return {- totalEnvironments: settledEnvironments.length,- reachableEnvironments: settledEnvironments.filter(- (item) => item.environment.enabled && isEnvironmentOnline(item.environment)- ).length,- unavailableEnvironments: settledEnvironments.filter(- (item) => item.environment.enabled && !isEnvironmentOnline(item.environment)- ).length,- disabledEnvironments: settledEnvironments.filter((item) => !item.environment.enabled).length,- totalContainers: settledEnvironments.reduce((total, item) => total + item.containers.totalContainers, 0),- runningContainers: settledEnvironments.reduce((total, item) => total + item.containers.runningContainers, 0),- stoppedContainers: settledEnvironments.reduce((total, item) => total + item.containers.stoppedContainers, 0),- totalImages: settledEnvironments.reduce((total, item) => total + item.imageUsageCounts.totalImages, 0),- imagesInUse: settledEnvironments.reduce((total, item) => total + item.imageUsageCounts.imagesInuse, 0),- imagesUnused: settledEnvironments.reduce((total, item) => total + item.imageUsageCounts.imagesUnused, 0),- totalVolumes: settledEnvironments.reduce((total, item) => total + (item.volumeUsageCounts?.total ?? 0), 0),- volumesInUse: settledEnvironments.reduce((total, item) => total + (item.volumeUsageCounts?.inuse ?? 0), 0),- volumesUnused: settledEnvironments.reduce((total, item) => total + (item.volumeUsageCounts?.unused ?? 0), 0)- };- }-function createEmptyLiveStatsState(): EnvironmentLiveStatsState {return {stats: null,@@ -332,7 +293,7 @@return {overviewById,- summary: buildOverviewSummaryFromItemsInternal(items)+ summary: buildOverviewSummary(items)};});@@ -434,119 +395,10 @@}}- function getRoleBadge(environment: Environment): { text: string; variant: 'primary' | 'gray' } {- return environment.id === LOCAL_DOCKER_ENVIRONMENT_ID- ? { text: m.manager(), variant: 'primary' }- : { text: m.agent(), variant: 'gray' };- }-- function getResolvedStatusLabel(environment: Environment): string {- switch (resolveEnvironmentStatus(environment)) {- case 'online':- return m.common_online();- case 'standby':- return m.common_standby();- case 'pending':- return m.common_pending();- case 'error':- return m.common_error();- default:- return m.common_offline();- }- }-- function getActivityMeta(environment: Environment): { label: string; value: string; title: string } {- if (!isEnvironmentOnline(environment)) {- const statusLabel = getResolvedStatusLabel(environment);- return {- label: m.activity(),- value: statusLabel,- title: statusLabel- };- }-- const labelAndValue = environment.lastHeartbeat- ? { label: m.environments_edge_last_heartbeat_label(), raw: environment.lastHeartbeat }- : environment.lastPollAt- ? { label: m.environments_edge_last_poll_label(), raw: environment.lastPollAt }- : environment.connectedAt- ? { label: m.environments_edge_connected_since_label(), raw: environment.connectedAt }- : environment.lastSeen- ? { label: m.dashboard_all_last_seen(), raw: environment.lastSeen }- : null;-- if (!labelAndValue?.raw) {- return { label: m.activity(), value: m.common_never(), title: m.common_never() };- }-- const parsed = parseInstant(labelAndValue.raw);- if (!parsed) {- return { label: labelAndValue.label, value: m.common_unknown(), title: m.common_unknown() };- }-- return {- label: labelAndValue.label,- value: formatRelativeTime(parsed),- title: formatDateTime(parsed)- };- }-- function formatPercent(value: number | null | undefined): string {- return value === null || value === undefined ? '--' : `${value.toFixed(1)}%`;- }-function getLiveStatsState(environmentId: string): EnvironmentLiveStatsState | null {return liveStatsByEnvironmentId[environmentId] ?? null;}- function getCpuMetric(stats: SystemStats | null): number | null {- return stats?.cpuUsage ?? null;- }-- function getMemoryMetric(stats: SystemStats | null): number | null {- if (stats?.memoryUsage === undefined || !stats.memoryTotal) {- return null;- }-- return (stats.memoryUsage / stats.memoryTotal) * 100;- }-- function getDiskMetric(stats: SystemStats | null): number | null {- if (stats?.diskUsage === undefined || !stats.diskTotal || stats.diskTotal <= 0) {- return null;- }-- return (stats.diskUsage / stats.diskTotal) * 100;- }-- function getCpuMetricLabel(stats: SystemStats | null): string {- if (!stats) {- return '--';- }-- return `${stats.cpuCount ?? 0} ${m.common_cpus()}`;- }-- function getCapacityLabel(used: number | undefined, total: number | undefined): string {- if (used === undefined || total === undefined || total <= 0) {- return '--';- }-- return `${bytes.format(used, { unitSeparator: ' ' }) ?? '-'} / ${bytes.format(total, { unitSeparator: ' ' }) ?? '-'}`;- }-- function getGpuMetric(stats: SystemStats | null): number | null {- const gpus = stats?.gpus?.filter((gpu) => gpu.memoryTotal > 0) ?? [];- if (gpus.length === 0) return null;- const totalPercent = gpus.reduce((sum, gpu) => sum + (gpu.memoryUsed / gpu.memoryTotal) * 100, 0);- return totalPercent / gpus.length;- }-- function getGpuMetricLabel(stats: SystemStats | null): string {- const count = stats?.gpuCount ?? 0;- return count > 0 ? `${count} ${count === 1 ? m.dashboard_meter_gpu_device() : m.dashboard_meter_gpu_devices()}` : '--';- }-function canPruneEnvironment(item: DashboardEnvironmentOverview): boolean {return (canPruneInEnvironment(item.environment.id) &&@@ -665,30 +517,6 @@return { pending, checking };});- function formatContainerOverviewLabel(summary: DashboardOverviewSummary): string {- if (summary.totalContainers === 0) {- return m.dashboard_all_no_containers();- }-- return m.dashboard_all_container_summary({ running: summary.runningContainers, stopped: summary.stoppedContainers });- }-- function formatImageOverviewLabel(summary: DashboardOverviewSummary): string {- if (summary.totalImages === 0) {- return m.dashboard_all_no_images();- }-- return m.dashboard_all_image_summary({ inUse: summary.imagesInUse, unused: summary.imagesUnused });- }-- function formatVolumeOverviewLabel(summary: DashboardOverviewSummary): string {- if (summary.totalVolumes === 0) {- return m.dashboard_all_no_volumes();- }-- return m.dashboard_all_volume_summary({ inUse: summary.volumesInUse, unused: summary.volumesUnused });- }-async function openPruneDialog(item: DashboardEnvironmentOverview) {if (!canPruneEnvironment(item) || pruneDefaultsLoadingId) {return;@@ -918,228 +746,27 @@{#each environmentCards as item (item.environment.id)}{@const baseItem = createBaseEnvironmentOverview(item.environment)}{@const environment = baseItem.environment}- {@const roleBadge = getRoleBadge(environment)}- {@const activity = getActivityMeta(environment)}+ {@const overview = boardState.overviewById.get(environment.id) ?? baseItem}{@const isCurrent = currentEnvironmentId === environment.id}{@const liveStatsState = getLiveStatsState(environment.id)}{@const systemStats = liveStatsState?.stats ?? null}{@const liveStatsLoading = liveStatsState?.loading ?? shouldLoadEnvironment(environment)}- {@const cpuMetric = getCpuMetric(systemStats)}- {@const memoryMetric = getMemoryMetric(systemStats)}- {@const diskMetric = getDiskMetric(systemStats)}- {@const gpuMetric = getGpuMetric(systemStats)}- {@const [useButton, ...menuButtons] = getEnvironmentActionButtons(- boardState.overviewById.get(environment.id) ?? baseItem,- isCurrent- )}-- <Card.Root- variant="outlined"- class={`dashboard-environment-card [container-type:inline-size] overflow-hidden border transition-[background-color,border-color,box-shadow] hover:shadow-[0_0_24px_-8px_color-mix(in_oklch,var(--primary)_40%,transparent)] ${isCurrent ? 'border-primary/40 bg-primary/5' : 'border-border/60 hover:border-primary/25'}`}- >- <Card.Content class="space-y-4 p-4 sm:p-5">- <div class="flex flex-col gap-3 border-b border-border/60 pb-4 sm:flex-row sm:items-start sm:justify-between">- <div class="min-w-0 space-y-2">- <div class="flex min-w-0 flex-wrap items-center gap-2">- <div class="max-w-full min-w-0 text-base font-semibold tracking-tight break-words">{environment.name}</div>- <Badge variant={roleBadge.variant} size="sm">{roleBadge.text}</Badge>- {#if boardState}- {@const loadedItem = boardState.overviewById.get(environment.id) ?? baseItem}- {@const vInfo =- loadedItem.versionInfo ||- (debugUpgrade- ? ({ displayVersion: 'debug', updateAvailable: true, newestVersion: 'debug-v2' } as any)- : null)}- {#if vInfo}- <div class="flex items-center">- {#if vInfo.updateAvailable || debugUpgrade}- <ArcaneTooltip.Root>- <ArcaneTooltip.Trigger- class={cn(badgeVariants({ variant: 'gray', size: 'sm' }), 'font-mono hover:text-foreground')}- >- {vInfo.displayVersion || vInfo.currentTag || vInfo.currentVersion || 'unknown'}- <span class="relative ml-1.5 flex h-2 w-2">- <span- class="absolute inline-flex h-full w-full animate-ping rounded-full bg-amber-400 opacity-75"- ></span>- <span class="relative inline-flex h-2 w-2 rounded-full bg-amber-500"></span>- </span>- </ArcaneTooltip.Trigger>- <ArcaneTooltip.Content class="flex flex-col items-start gap-2">- <span>- {m.sidebar_update_available()}{#if vInfo.newestVersion || vInfo.newestDigest}: {vInfo.newestVersion ||- vInfo.newestDigest.slice(0, 12)}{/if}- </span>- <DashboardEnvironmentUpgradeAction- {environment}- versionInfo={vInfo}- canUpgrade={canUpgradeEnvironment()}- debug={debugUpgrade}- onRefreshRequested={refreshOverview}- render="trigger"- bind:open={upgradeDialogOpenById[environment.id]}- bind:upgrading={upgradeDialogUpgradingById[environment.id]}- />- </ArcaneTooltip.Content>- </ArcaneTooltip.Root>- {:else}- <Badge variant="gray" size="sm" class="font-mono">- {vInfo.displayVersion || vInfo.currentTag || vInfo.currentVersion || 'unknown'}- </Badge>- {/if}- </div>- {#if vInfo.updateAvailable || debugUpgrade}- <DashboardEnvironmentUpgradeAction- {environment}- versionInfo={vInfo}- canUpgrade={canUpgradeEnvironment()}- debug={debugUpgrade}- onRefreshRequested={refreshOverview}- render="dialog"- bind:open={upgradeDialogOpenById[environment.id]}- bind:upgrading={upgradeDialogUpgradingById[environment.id]}- />- {/if}- {/if}- {/if}- </div>-- <div class="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-muted-foreground/70">- <span class="font-mono">{environment.apiUrl}</span>- <span>•</span>- <span title={activity.title}>{activity.label}: {activity.value}</span>- </div>- </div>-- <div class="flex shrink-0 items-center gap-1 pt-1 sm:pt-0">- {#if useButton}- <ArcaneButton- action="base"- size="sm"- tone="ghost"- icon={EnvironmentsIcon}- customLabel={isCurrent ? m.common_current() : useButton.label}- loading={useButton.loading}- disabled={useButton.disabled}- onclick={useButton.onclick}- class={cn(isCurrent && 'disabled:opacity-100 [&_svg]:text-primary!')}- />- {/if}- <RowActionsMenu>- {#each menuButtons as btn (btn.id)}- <DropdownMenu.Item- disabled={!!(btn.disabled || btn.loading)}- onclick={btn.onclick}- class={cn(btn.action === 'prune' && 'text-destructive data-highlighted:text-destructive')}- >- {#if btn.icon}- <btn.icon class="size-4" />- {/if}- {btn.label}- </DropdownMenu.Item>- {/each}- </RowActionsMenu>- </div>- </div>-- {#if shouldLoadEnvironment(environment) || isEnvironmentOnline(environment)}- {#if isEnvironmentSnapshotLoading(environment.id)}- <Skeleton class="h-4 w-64" />- {:else}- {@const loadedItem = boardState.overviewById.get(environment.id) ?? baseItem}- <div class="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-sm text-muted-foreground">- <span>- <span class="font-semibold text-foreground tabular-nums"- >{loadedItem.containers.runningContainers}/{loadedItem.containers.totalContainers}</span- >- {String(m.common_running()).toLowerCase()}- </span>- <span class="text-border">·</span>- <span>- <span class="font-semibold text-foreground tabular-nums">{loadedItem.imageUsageCounts.totalImages}</span>- {String(m.images()).toLowerCase()}- </span>- <span class="text-border">·</span>- <span>- <span class="font-semibold text-foreground tabular-nums">{loadedItem.actionItems.items.length}</span>- {String(m.dashboard_action_items_title()).toLowerCase()}- </span>- </div>- {/if}- {:else}- <div class="border-t border-border/60 pt-3 text-sm">- <p class="font-medium">{m.dashboard_all_environment_unavailable_title()}</p>- <p class="mt-1 text-muted-foreground">{m.dashboard_all_environment_unavailable_description()}</p>- </div>- {/if}-- {#if shouldLoadEnvironment(environment)}- <div class="border-t border-border/60 pt-3">- <div class="grid grid-cols-1 gap-1 {gpuMetric !== null ? 'sm:grid-cols-2 lg:grid-cols-4' : 'sm:grid-cols-3'}">- {#if liveStatsLoading}- {#each [1, 2, 3] as tile (tile)}- <div class="min-w-0 px-2.5 py-2.5">- <div class="flex items-start justify-between gap-2">- <Skeleton class="h-3 w-20" />- <Skeleton class="h-5 w-12" />- </div>- <Skeleton class="mt-2 h-3 w-24" />- <Skeleton class="mt-3 h-1.5 w-full" />- </div>- {/each}- {:else}- <DashboardMetricTile- title={m.cpu_usage()}- icon={CpuIcon}- value={formatPercent(cpuMetric)}- label={getCpuMetricLabel(systemStats)}- meterValue={cpuMetric}- />-- <DashboardMetricTile- title={m.memory_usage()}- icon={MemoryStickIcon}- value={formatPercent(memoryMetric)}- label={getCapacityLabel(systemStats?.memoryUsage, systemStats?.memoryTotal)}- labelClass="truncate"- meterValue={memoryMetric}- />-- <DashboardMetricTile- title={m.dashboard_meter_disk()}- icon={VolumesIcon}- value={formatPercent(diskMetric)}- label={getCapacityLabel(systemStats?.diskUsage, systemStats?.diskTotal)}- labelClass="truncate"- meterValue={diskMetric}- />-- {#if gpuMetric !== null}- <DashboardMetricTile- title={m.dashboard_meter_gpu()}- icon={GpuIcon}- value={formatPercent(gpuMetric)}- label={getGpuMetricLabel(systemStats)}- meterValue={gpuMetric}- />- {/if}- {/if}- </div>- </div>- {/if}-- {#if boardState}- {@const loadedItem = boardState.overviewById.get(environment.id) ?? baseItem}- {#if loadedItem.snapshotError}- <div- class="rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-xs text-red-700 dark:text-red-300"- >- {m.dashboard_all_summary_unavailable({ error: loadedItem.snapshotError })}- </div>- {/if}- {/if}- </Card.Content>- </Card.Root>+ {@const [useButton, ...menuButtons] = getEnvironmentActionButtons(overview, isCurrent)}+ <DashboardEnvironmentCard+ {overview}+ {isCurrent}+ {systemStats}+ {liveStatsLoading}+ snapshotLoading={isEnvironmentSnapshotLoading(environment.id)}+ {useButton}+ {menuButtons}+ {debugUpgrade}+ debugVersionInfo={DEBUG_VERSION_INFO}+ canUpgrade={canUpgradeEnvironment()}+ onRefreshRequested={refreshOverview}+ bind:upgradeOpen={upgradeDialogOpenById[environment.id]}+ bind:upgradeLoading={upgradeDialogUpgradingById[environment.id]}+ />{/each}</div></div>diff --git a/frontend/src/routes/(app)/dashboard/dashboard-environment-card.svelte b/frontend/src/routes/(app)/dashboard/dashboard-environment-card.sveltenew file mode 100644index 000000000..5599c6ff4--- /dev/null+++ b/frontend/src/routes/(app)/dashboard/dashboard-environment-card.svelte@@ -0,0 +1,260 @@+<script lang="ts">+ import type { ActionButton } from '#lib/components/action-button-group';+ import { ArcaneButton } from '#lib/components/arcane-button';+ import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';+ import DashboardEnvironmentUpgradeAction from './dashboard-environment-upgrade-action.svelte';+ import DashboardMetricTile from './dash-metric-tile.svelte';+ import * as ArcaneTooltip from '#lib/components/arcane-tooltip';+ import { Badge, badgeVariants } from '#lib/components/ui/badge';+ import * as Card from '#lib/components/ui/card';+ import * as DropdownMenu from '#lib/components/ui/dropdown-menu';+ import { Skeleton } from '#lib/components/ui/skeleton';+ import { CpuIcon, EnvironmentsIcon, GpuIcon, MemoryStickIcon, VolumesIcon } from '#lib/icons';+ import { m } from '#lib/paraglide/messages';+ import type { AppVersionInformation } from '#lib/types/settings';+ import type { DashboardEnvironmentOverview, SystemStats } from '#lib/types/shared';+ import { cn } from '#lib/utils';+ import { isEnvironmentOnline } from '#lib/utils/docker';+ import {+ formatPercent,+ getActivityMeta,+ getCapacityLabel,+ getCpuMetric,+ getCpuMetricLabel,+ getDiskMetric,+ getGpuMetric,+ getGpuMetricLabel,+ getMemoryMetric,+ getRoleBadge,+ shouldLoadEnvironment+ } from './dashboard-overview';++ // These bindings target record entries that start undefined; Svelte rejects a bindable fallback here.+ let {+ overview,+ isCurrent,+ systemStats,+ liveStatsLoading,+ snapshotLoading,+ useButton,+ menuButtons,+ debugUpgrade = false,+ debugVersionInfo,+ canUpgrade,+ upgradeOpen = $bindable(undefined),+ upgradeLoading = $bindable(undefined),+ onRefreshRequested+ }: {+ overview: DashboardEnvironmentOverview;+ isCurrent: boolean;+ systemStats: SystemStats | null;+ liveStatsLoading: boolean;+ snapshotLoading: boolean;+ useButton?: ActionButton;+ menuButtons: ActionButton[];+ debugUpgrade?: boolean;+ debugVersionInfo: AppVersionInformation;+ canUpgrade: boolean;+ upgradeOpen?: boolean;+ upgradeLoading?: boolean;+ onRefreshRequested: () => void | Promise<void>;+ } = $props();++ const environment = $derived(overview.environment);+ const roleBadge = $derived(getRoleBadge(environment));+ const activity = $derived(getActivityMeta(environment));+ const versionInfo = $derived(overview.versionInfo ?? (debugUpgrade ? debugVersionInfo : null));+ const newestVersionLabel = $derived(versionInfo?.newestVersion ?? versionInfo?.newestDigest?.slice(0, 12));+ const cpuMetric = $derived(getCpuMetric(systemStats));+ const memoryMetric = $derived(getMemoryMetric(systemStats));+ const diskMetric = $derived(getDiskMetric(systemStats));+ const gpuMetric = $derived(getGpuMetric(systemStats));+</script>++<Card.Root+ variant="outlined"+ class={`dashboard-environment-card [container-type:inline-size] overflow-hidden border transition-[background-color,border-color,box-shadow] hover:shadow-[0_0_24px_-8px_color-mix(in_oklch,var(--primary)_40%,transparent)] ${isCurrent ? 'border-primary/40 bg-primary/5' : 'border-border/60 hover:border-primary/25'}`}+>+ <Card.Content class="space-y-4 p-4 sm:p-5">+ <div class="flex flex-col gap-3 border-b border-border/60 pb-4 sm:flex-row sm:items-start sm:justify-between">+ <div class="min-w-0 space-y-2">+ <div class="flex min-w-0 flex-wrap items-center gap-2">+ <div class="max-w-full min-w-0 text-base font-semibold tracking-tight break-words">{environment.name}</div>+ <Badge variant={roleBadge.variant} size="sm">{roleBadge.text}</Badge>+ {#if versionInfo}+ <div class="flex items-center">+ {#if versionInfo.updateAvailable || debugUpgrade}+ <ArcaneTooltip.Root>+ <ArcaneTooltip.Trigger+ class={cn(badgeVariants({ variant: 'gray', size: 'sm' }), 'font-mono hover:text-foreground')}+ >+ {versionInfo.displayVersion || versionInfo.currentTag || versionInfo.currentVersion || m.common_unknown()}+ <span class="relative ml-1.5 flex h-2 w-2">+ <span class="absolute inline-flex h-full w-full animate-ping rounded-full bg-amber-400 opacity-75"></span>+ <span class="relative inline-flex h-2 w-2 rounded-full bg-amber-500"></span>+ </span>+ </ArcaneTooltip.Trigger>+ <ArcaneTooltip.Content class="flex flex-col items-start gap-2">+ <span+ >{m.sidebar_update_available()}{#if newestVersionLabel}: {newestVersionLabel}{/if}</span+ >+ <DashboardEnvironmentUpgradeAction+ {environment}+ {versionInfo}+ {canUpgrade}+ debug={debugUpgrade}+ {onRefreshRequested}+ render="trigger"+ bind:open={upgradeOpen}+ bind:upgrading={upgradeLoading}+ />+ </ArcaneTooltip.Content>+ </ArcaneTooltip.Root>+ {:else}+ <Badge variant="gray" size="sm" class="font-mono">+ {versionInfo.displayVersion || versionInfo.currentTag || versionInfo.currentVersion || m.common_unknown()}+ </Badge>+ {/if}+ </div>+ {#if versionInfo.updateAvailable || debugUpgrade}+ <DashboardEnvironmentUpgradeAction+ {environment}+ {versionInfo}+ {canUpgrade}+ debug={debugUpgrade}+ {onRefreshRequested}+ render="dialog"+ bind:open={upgradeOpen}+ bind:upgrading={upgradeLoading}+ />+ {/if}+ {/if}+ </div>++ <div class="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-muted-foreground/70">+ <span class="font-mono">{environment.apiUrl}</span>+ <span>•</span>+ <span title={activity.title}>{activity.label}: {activity.value}</span>+ </div>+ </div>++ <div class="flex shrink-0 items-center gap-1 pt-1 sm:pt-0">+ {#if useButton}+ <ArcaneButton+ action="base"+ size="sm"+ tone="ghost"+ icon={EnvironmentsIcon}+ customLabel={isCurrent ? m.common_current() : useButton.label}+ loading={useButton.loading}+ disabled={useButton.disabled}+ onclick={useButton.onclick}+ class={cn(isCurrent && 'disabled:opacity-100 [&_svg]:text-primary!')}+ />+ {/if}+ <RowActionsMenu>+ {#each menuButtons as button (button.id)}+ <DropdownMenu.Item+ disabled={!!(button.disabled || button.loading)}+ onclick={button.onclick}+ class={cn(button.action === 'prune' && 'text-destructive data-highlighted:text-destructive')}+ >+ {#if button.icon}+ <button.icon class="size-4" />+ {/if}+ {button.label}+ </DropdownMenu.Item>+ {/each}+ </RowActionsMenu>+ </div>+ </div>++ {#if shouldLoadEnvironment(environment) || isEnvironmentOnline(environment)}+ {#if snapshotLoading}+ <Skeleton class="h-4 w-64" />+ {:else}+ <div class="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-sm text-muted-foreground">+ <span>+ <span class="font-semibold text-foreground tabular-nums"+ >{overview.containers.runningContainers}/{overview.containers.totalContainers}</span+ >+ {String(m.common_running()).toLowerCase()}+ </span>+ <span class="text-border">·</span>+ <span>+ <span class="font-semibold text-foreground tabular-nums">{overview.imageUsageCounts.totalImages}</span>+ {String(m.images()).toLowerCase()}+ </span>+ <span class="text-border">·</span>+ <span>+ <span class="font-semibold text-foreground tabular-nums">{overview.actionItems.items.length}</span>+ {String(m.dashboard_action_items_title()).toLowerCase()}+ </span>+ </div>+ {/if}+ {:else}+ <div class="border-t border-border/60 pt-3 text-sm">+ <p class="font-medium">{m.dashboard_all_environment_unavailable_title()}</p>+ <p class="mt-1 text-muted-foreground">{m.dashboard_all_environment_unavailable_description()}</p>+ </div>+ {/if}++ {#if shouldLoadEnvironment(environment)}+ <div class="border-t border-border/60 pt-3">+ <div class="grid grid-cols-1 gap-1 {gpuMetric !== null ? 'sm:grid-cols-2 lg:grid-cols-4' : 'sm:grid-cols-3'}">+ {#if liveStatsLoading}+ {#each [1, 2, 3] as tile (tile)}+ <div class="min-w-0 px-2.5 py-2.5">+ <div class="flex items-start justify-between gap-2">+ <Skeleton class="h-3 w-20" />+ <Skeleton class="h-5 w-12" />+ </div>+ <Skeleton class="mt-2 h-3 w-24" />+ <Skeleton class="mt-3 h-1.5 w-full" />+ </div>+ {/each}+ {:else}+ <DashboardMetricTile+ title={m.cpu_usage()}+ icon={CpuIcon}+ value={formatPercent(cpuMetric)}+ label={getCpuMetricLabel(systemStats)}+ meterValue={cpuMetric}+ />+ <DashboardMetricTile+ title={m.memory_usage()}+ icon={MemoryStickIcon}+ value={formatPercent(memoryMetric)}+ label={getCapacityLabel(systemStats?.memoryUsage, systemStats?.memoryTotal)}+ labelClass="truncate"+ meterValue={memoryMetric}+ />+ <DashboardMetricTile+ title={m.dashboard_meter_disk()}+ icon={VolumesIcon}+ value={formatPercent(diskMetric)}+ label={getCapacityLabel(systemStats?.diskUsage, systemStats?.diskTotal)}+ labelClass="truncate"+ meterValue={diskMetric}+ />+ {#if gpuMetric !== null}+ <DashboardMetricTile+ title={m.dashboard_meter_gpu()}+ icon={GpuIcon}+ value={formatPercent(gpuMetric)}+ label={getGpuMetricLabel(systemStats)}+ meterValue={gpuMetric}+ />+ {/if}+ {/if}+ </div>+ </div>+ {/if}++ {#if overview.snapshotError}+ <div class="rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-xs text-red-700 dark:text-red-300">+ {m.dashboard_all_summary_unavailable({ error: overview.snapshotError })}+ </div>+ {/if}+ </Card.Content>+</Card.Root>diff --git a/frontend/src/routes/(app)/dashboard/dashboard-overview.ts b/frontend/src/routes/(app)/dashboard/dashboard-overview.tsnew file mode 100644index 000000000..5701551aa--- /dev/null+++ b/frontend/src/routes/(app)/dashboard/dashboard-overview.ts@@ -0,0 +1,143 @@+import * as m from '#lib/paraglide/messages.js';+import { LOCAL_DOCKER_ENVIRONMENT_ID } from '#lib/stores/environment.store.svelte';+import type { Environment } from '#lib/types/environment';+import type { DashboardEnvironmentOverview, DashboardOverviewSummary, SystemStats } from '#lib/types/shared';+import { bytes, formatDateTime, formatRelativeTime, parseInstant } from '#lib/utils/formatting';+import { isEnvironmentOnline, resolveEnvironmentStatus } from '#lib/utils/docker';++export function shouldLoadEnvironment(environment: Environment): boolean {+ return environment.enabled && isEnvironmentOnline(environment);+}++export function createBaseEnvironmentOverview(environment: Environment): DashboardEnvironmentOverview {+ return {+ environment,+ containers: { runningContainers: 0, stoppedContainers: 0, totalContainers: 0 },+ imageUsageCounts: { imagesInuse: 0, imagesUnused: 0, totalImages: 0, totalImageSize: 0 },+ actionItems: { items: [] },+ settings: {},+ snapshotState: 'skipped'+ };+}++export function getEnvironmentCardSortRank(environment: Environment): number {+ if (shouldLoadEnvironment(environment)) return 0;+ return environment.enabled ? 1 : 2;+}++export function buildOverviewSummary(items: DashboardEnvironmentOverview[]): DashboardOverviewSummary {+ return {+ totalEnvironments: items.length,+ reachableEnvironments: items.filter((item) => item.environment.enabled && isEnvironmentOnline(item.environment)).length,+ unavailableEnvironments: items.filter((item) => item.environment.enabled && !isEnvironmentOnline(item.environment)).length,+ disabledEnvironments: items.filter((item) => !item.environment.enabled).length,+ totalContainers: items.reduce((total, item) => total + item.containers.totalContainers, 0),+ runningContainers: items.reduce((total, item) => total + item.containers.runningContainers, 0),+ stoppedContainers: items.reduce((total, item) => total + item.containers.stoppedContainers, 0),+ totalImages: items.reduce((total, item) => total + item.imageUsageCounts.totalImages, 0),+ imagesInUse: items.reduce((total, item) => total + item.imageUsageCounts.imagesInuse, 0),+ imagesUnused: items.reduce((total, item) => total + item.imageUsageCounts.imagesUnused, 0),+ totalVolumes: items.reduce((total, item) => total + (item.volumeUsageCounts?.total ?? 0), 0),+ volumesInUse: items.reduce((total, item) => total + (item.volumeUsageCounts?.inuse ?? 0), 0),+ volumesUnused: items.reduce((total, item) => total + (item.volumeUsageCounts?.unused ?? 0), 0)+ };+}++export function getRoleBadge(environment: Environment): { text: string; variant: 'primary' | 'gray' } {+ return environment.id === LOCAL_DOCKER_ENVIRONMENT_ID+ ? { text: m.manager(), variant: 'primary' }+ : { text: m.agent(), variant: 'gray' };+}++export function getResolvedStatusLabel(environment: Environment): string {+ switch (resolveEnvironmentStatus(environment)) {+ case 'online':+ return m.common_online();+ case 'standby':+ return m.common_standby();+ case 'pending':+ return m.common_pending();+ case 'error':+ return m.common_error();+ default:+ return m.common_offline();+ }+}++export function getActivityMeta(environment: Environment): { label: string; value: string; title: string } {+ if (!isEnvironmentOnline(environment)) {+ const statusLabel = getResolvedStatusLabel(environment);+ return { label: m.activity(), value: statusLabel, title: statusLabel };+ }++ const labelAndValue = environment.lastHeartbeat+ ? { label: m.environments_edge_last_heartbeat_label(), raw: environment.lastHeartbeat }+ : environment.lastPollAt+ ? { label: m.environments_edge_last_poll_label(), raw: environment.lastPollAt }+ : environment.connectedAt+ ? { label: m.environments_edge_connected_since_label(), raw: environment.connectedAt }+ : environment.lastSeen+ ? { label: m.dashboard_all_last_seen(), raw: environment.lastSeen }+ : null;++ if (!labelAndValue?.raw) return { label: m.activity(), value: m.common_never(), title: m.common_never() };+ const parsed = parseInstant(labelAndValue.raw);+ if (!parsed) return { label: labelAndValue.label, value: m.common_unknown(), title: m.common_unknown() };+ return { label: labelAndValue.label, value: formatRelativeTime(parsed), title: formatDateTime(parsed) };+}++export function formatPercent(value: number | null | undefined): string {+ return value === null || value === undefined ? '--' : `${value.toFixed(1)}%`;+}++export function getCpuMetric(stats: SystemStats | null): number | null {+ return stats?.cpuUsage ?? null;+}++export function getMemoryMetric(stats: SystemStats | null): number | null {+ return stats?.memoryUsage === undefined || !stats.memoryTotal ? null : (stats.memoryUsage / stats.memoryTotal) * 100;+}++export function getDiskMetric(stats: SystemStats | null): number | null {+ return stats?.diskUsage === undefined || !stats.diskTotal || stats.diskTotal <= 0+ ? null+ : (stats.diskUsage / stats.diskTotal) * 100;+}++export function getCpuMetricLabel(stats: SystemStats | null): string {+ return stats ? `${stats.cpuCount ?? 0} ${m.common_cpus()}` : '--';+}++export function getCapacityLabel(used: number | undefined, total: number | undefined): string {+ if (used === undefined || total === undefined || total <= 0) return '--';+ return `${bytes.format(used, { unitSeparator: ' ' }) ?? '-'} / ${bytes.format(total, { unitSeparator: ' ' }) ?? '-'}`;+}++export function getGpuMetric(stats: SystemStats | null): number | null {+ const gpus = stats?.gpus?.filter((gpu) => gpu.memoryTotal > 0) ?? [];+ if (gpus.length === 0) return null;+ return gpus.reduce((sum, gpu) => sum + (gpu.memoryUsed / gpu.memoryTotal) * 100, 0) / gpus.length;+}++export function getGpuMetricLabel(stats: SystemStats | null): string {+ const count = stats?.gpuCount ?? 0;+ return count > 0 ? `${count} ${count === 1 ? m.dashboard_meter_gpu_device() : m.dashboard_meter_gpu_devices()}` : '--';+}++export function formatContainerOverviewLabel(summary: DashboardOverviewSummary): string {+ return summary.totalContainers === 0+ ? m.dashboard_all_no_containers()+ : m.dashboard_all_container_summary({ running: summary.runningContainers, stopped: summary.stoppedContainers });+}++export function formatImageOverviewLabel(summary: DashboardOverviewSummary): string {+ return summary.totalImages === 0+ ? m.dashboard_all_no_images()+ : m.dashboard_all_image_summary({ inUse: summary.imagesInUse, unused: summary.imagesUnused });+}++export function formatVolumeOverviewLabel(summary: DashboardOverviewSummary): string {+ return summary.totalVolumes === 0+ ? m.dashboard_all_no_volumes()+ : m.dashboard_all_volume_summary({ inUse: summary.volumesInUse, unused: summary.volumesUnused });+}diff --git a/frontend/src/routes/(app)/environments/+page.svelte b/frontend/src/routes/(app)/environments/+page.svelteindex b90af43a7..bfd67443c 100644--- a/frontend/src/routes/(app)/environments/+page.svelte+++ b/frontend/src/routes/(app)/environments/+page.svelte@@ -4,9 +4,6 @@import { page } from '$app/state';import NewEnvironmentSheet from '#lib/components/sheets/new-environment-sheet.svelte';import EnvironmentTable from './environment-table.svelte';- import { tryCatch } from '#lib/utils/api';- import { handleApiResultWithCallbacks } from '#lib/utils/api';- import { openConfirmDialog } from '#lib/components/confirm-dialog';import { m } from '#lib/paraglide/messages';import { environmentManagementService } from '#lib/services/env-mgmt-service';import { untrack } from 'svelte';@@ -16,6 +13,7 @@import { hasPermission } from '#lib/utils/auth';import { DownloadIcon, UpdateIcon } from '#lib/icons';import UpdateAllDialog from '#lib/components/dialogs/update-all-dialog.svelte';+ import { bulkConfirmAndRun } from '#lib/utils/bulk-actions';let { data } = $props();@@ -39,45 +37,31 @@const canDeleteEnvironment = $derived(hasPermission('environments:delete'));const canUpdateEnvironments = $derived(hasPermission('system:upgrade'));- async function handleBulkDelete() {- if (selectedIds.length === 0) return;+ function handleBulkDelete(ids: string[] = selectedIds) {+ if (ids.length === 0) return;+ const environmentIds = [...ids];- openConfirmDialog({- title: m.environments_remove_selected_title({ count: selectedIds.length }),+ bulkConfirmAndRun({+ ids: environmentIds,+ title: m.environments_remove_selected_title({ count: environmentIds.length }),message: m.environments_remove_selected_message(),- confirm: {- label: m.common_remove(),- destructive: true,- action: async () => {- isLoading.deleting = true;- let successCount = 0;- let failureCount = 0;-- for (const id of selectedIds) {- const result = await tryCatch(environmentManagementService.delete(id));- handleApiResultWithCallbacks({- result,- message: m.common_bulk_remove_failed({ count: selectedIds.length, resource: m.environments_title() }),- setLoadingState: () => {},- onSuccess: () => {- successCount += 1;- }- });- if (result.error) failureCount += 1;- }-- isLoading.deleting = false;- if (successCount > 0) {- toast.success(m.common_bulk_remove_success({ count: successCount, resource: m.environments_title() }));- await refresh();- await environmentStore.initialize(environments.data);- }- if (failureCount > 0) {- toast.error(m.common_bulk_remove_failed({ count: failureCount, resource: m.environments_title() }));- }- selectedIds = [];- }- }+ confirmLabel: m.common_remove(),+ destructive: true,+ run: (id) => environmentManagementService.delete(id),+ messages: {+ success: (count) => m.common_bulk_remove_success({ count, resource: m.environments_title() }),+ partial: (success, total, failed) =>+ m.common_bulk_remove_partial({ success, total, failed, resource: m.environments_title() }),+ failure: () => m.common_bulk_remove_failed({ count: environmentIds.length, resource: m.environments_title() })+ },+ setLoading: (loading) => (isLoading.deleting = loading),+ onComplete: async ({ success }) => {+ if (success === 0) return;+ await refresh();+ await environmentStore.initialize(environments.data);+ },+ clearSelection: () => (selectedIds = []),+ sequential: true});}@@ -155,7 +139,13 @@<ResourcePageLayout title={m.environments_title()} subtitle={m.environments_subtitle()} {actionButtons}>{#snippet mainContent()}- <EnvironmentTable bind:environments bind:selectedIds bind:requestOptions />+ <EnvironmentTable+ bind:environments+ bind:selectedIds+ bind:requestOptions+ onDeleteSelected={handleBulkDelete}+ bulkDeleteLoading={isLoading.deleting}+ />{/snippet}{#snippet additionalContent()}diff --git a/frontend/src/routes/(app)/environments/environment-table.svelte b/frontend/src/routes/(app)/environments/environment-table.svelteindex e1e028bc9..acb21b108 100644--- a/frontend/src/routes/(app)/environments/environment-table.svelte+++ b/frontend/src/routes/(app)/environments/environment-table.svelte@@ -41,11 +41,15 @@let {environments = $bindable(),selectedIds = $bindable(),- requestOptions = $bindable()+ requestOptions = $bindable(),+ onDeleteSelected,+ bulkDeleteLoading = false}: {environments: Paginated<Environment>;selectedIds: string[];requestOptions: SearchPaginationSortRequest;+ onDeleteSelected: (ids: string[]) => void;+ bulkDeleteLoading?: boolean;} = $props();let isLoading = $state({ removing: false, testing: false, upgrading: false, toggling: false });@@ -89,52 +93,6 @@easyJoinDialogOpen = true;}- async function handleDeleteSelected(ids: string[]) {- if (!ids?.length) return;-- openConfirmDialog({- title: m.environments_remove_selected_title({ count: ids.length }),- message: m.environments_remove_selected_message({ count: ids.length }),- confirm: {- label: m.common_remove(),- destructive: true,- action: async () => {- isLoading.removing = true;- let successCount = 0;- let failureCount = 0;-- for (const id of ids) {- const result = await tryCatch(environmentManagementService.delete(id));- handleApiResultWithCallbacks({- result,- message: m.common_bulk_remove_failed({ count: ids.length, resource: m.environments_title() }),- setLoadingState: () => {},- onSuccess: () => {- successCount++;- }- });- if (result.error) failureCount++;- }-- isLoading.removing = false;-- if (successCount > 0) {- const msg = m.common_bulk_remove_success({ count: successCount, resource: m.environments_title() });- toast.success(msg);- environments = await environmentManagementService.getEnvironments(requestOptions);- await environmentStore.initialize(environments.data);- }- if (failureCount > 0) {- const msg = m.common_bulk_remove_failed({ count: failureCount, resource: m.environments_title() });- toast.error(msg);- }-- selectedIds = [];- }- }- });- }-async function handleDeleteOne(id: string, hostname: string) {openConfirmDialog({title: m.common_delete_title({ resource: m.resource_environment() }),@@ -195,7 +153,7 @@try {const result = await systemUpgradeService.triggerUpgrade(envId);if (!result.success) {- throw new Error(result.error || m.upgrade_failed({ error: 'Unknown error' }));+ throw new Error(result.error || m.upgrade_failed({ error: m.common_unknown() }));}toast.success(m.upgrade_success());return { upToDate: result.upToDate };@@ -286,9 +244,9 @@id: 'remove',label: m.common_remove_selected_count({ count: selectedIds?.length ?? 0 }),action: 'remove',- onClick: handleDeleteSelected,- loading: isLoading.removing,- disabled: isLoading.removing,+ onClick: onDeleteSelected,+ loading: bulkDeleteLoading,+ disabled: bulkDeleteLoading || isLoading.removing,icon: TrashIcon}]);diff --git a/frontend/src/routes/(app)/events/+page.svelte b/frontend/src/routes/(app)/events/+page.svelteindex 310af4151..eb2396609 100644--- a/frontend/src/routes/(app)/events/+page.svelte+++ b/frontend/src/routes/(app)/events/+page.svelte@@ -1,21 +1,21 @@<script lang="ts">- import { toast } from 'svelte-sonner';import EventTable from './event-table.svelte';- import { openConfirmDialog } from '#lib/components/confirm-dialog';import { m } from '#lib/paraglide/messages';import { eventService } from '#lib/services/event-service';import { queryKeys } from '#lib/query/query-keys';import { untrack } from 'svelte';import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';- import { createMutation, createQuery, keepPreviousData } from '@tanstack/svelte-query';+ import { createQuery, keepPreviousData } from '@tanstack/svelte-query';import { AlertIcon, CheckIcon, CloseIcon, EventsIcon, InfoIcon } from '#lib/icons';import { hasPermission } from '#lib/utils/auth';+ import { bulkConfirmAndRun } from '#lib/utils/bulk-actions';let { data } = $props();let events = $state(untrack(() => data.events));let selectedIds = $state<string[]>([]);let requestOptions = $state(untrack(() => data.eventRequestOptions));+ let isDeleting = $state(false);const eventsQuery = createQuery(() => ({queryKey: queryKeys.events.listGlobal(requestOptions),@@ -30,35 +30,6 @@initialData: data.eventStats}));- const deleteSelectedMutation = createMutation(() => ({- mutationKey: queryKeys.events.deleteSelectedGlobal(),- mutationFn: async (ids: string[]) => {- let successCount = 0;- let failureCount = 0;-- for (const eventId of ids) {- try {- await eventService.delete(eventId);- successCount += 1;- } catch {- failureCount += 1;- }- }-- return { successCount, failureCount };- },- onSuccess: async ({ successCount, failureCount }) => {- if (successCount > 0) {- toast.success(m.common_bulk_delete_success({ count: successCount, resource: m.events_title() }));- await refresh();- }- if (failureCount > 0) {- toast.error(m.common_bulk_delete_failed({ count: failureCount, resource: m.events_title() }));- }- selectedIds = [];- }- }));-$effect(() => {if (eventsQuery.data) {events = eventsQuery.data;@@ -97,19 +68,28 @@};}- async function handleDeleteSelected() {+ function handleDeleteSelected() {if (selectedIds.length === 0) return;-- openConfirmDialog({- title: m.events_delete_selected_title({ count: selectedIds.length }),- message: m.events_delete_selected_message({ count: selectedIds.length }),- confirm: {- label: m.common_delete(),- destructive: true,- action: async () => {- await deleteSelectedMutation.mutateAsync([...selectedIds]);- }- }+ const ids = [...selectedIds];++ bulkConfirmAndRun({+ ids,+ title: m.events_delete_selected_title({ count: ids.length }),+ message: m.events_delete_selected_message({ count: ids.length }),+ confirmLabel: m.common_delete(),+ destructive: true,+ run: (eventId) => eventService.delete(eventId),+ messages: {+ success: (count) => m.common_bulk_delete_success({ count, resource: m.events_title() }),+ partial: (success, total, failed) => m.common_bulk_delete_partial({ success, total, failed, resource: m.events_title() }),+ failure: () => m.common_bulk_delete_failed({ count: ids.length, resource: m.events_title() })+ },+ setLoading: (loading) => (isDeleting = loading),+ onComplete: async ({ success }) => {+ if (success > 0) await refresh();+ },+ clearSelection: () => (selectedIds = []),+ sequential: true});}@@ -123,8 +103,8 @@action: 'remove' as const,label: m.common_remove_selected(),onclick: handleDeleteSelected,- loading: deleteSelectedMutation.isPending,- disabled: deleteSelectedMutation.isPending+ loading: isDeleting,+ disabled: isDeleting}]: []),diff --git a/frontend/src/routes/(app)/events/event-table.svelte b/frontend/src/routes/(app)/events/event-table.svelteindex 0474ba78c..cdfb898a1 100644--- a/frontend/src/routes/(app)/events/event-table.svelte+++ b/frontend/src/routes/(app)/events/event-table.svelte@@ -112,7 +112,7 @@accessorKey: 'timestamp',title: m.events_col_time(),sortable: true,- cell: TimeCell+ cellComponent: RelativeTimeCell}] satisfies ColumnSpec<Event>[];@@ -165,16 +165,12 @@{#snippet UserCell({ value }: { value: unknown })}{#if String(value ?? '') === 'System'}- <span class="text-sm text-muted-foreground italic">System</span>+ <span class="text-sm text-muted-foreground italic">{m.system()}</span>{:else}<span class="text-sm">{String(value ?? '—')}</span>{/if}{/snippet}-{#snippet TimeCell({ value }: { value: unknown })}- <RelativeTimeCell {value} />-{/snippet}-{#snippet ExpandedEvent({ item }: { item: Event })}<EventDetailPanel event={item} />{/snippet}diff --git a/frontend/src/routes/(app)/images/builds/+page.svelte b/frontend/src/routes/(app)/images/builds/+page.svelteindex 762b91ec6..22d7bcfc3 100644--- a/frontend/src/routes/(app)/images/builds/+page.svelte+++ b/frontend/src/routes/(app)/images/builds/+page.svelte@@ -1,9 +1,7 @@<script lang="ts">import { onMount } from 'svelte';import { z } from 'zod/v4';- import { ArcaneButton } from '#lib/components/arcane-button/index.js';import * as Tabs from '#lib/components/ui/tabs/index.js';- import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';import { m } from '#lib/paraglide/messages';import settingsStore from '#lib/stores/config-store';import { createForm } from '#lib/utils/settings';@@ -13,42 +11,31 @@import { ResourceDetailLayout } from '#lib/layouts/index.js';import TabbedPageLayout from '#lib/layouts/tabbed-page-layout.svelte';import { sanitizeLogText } from '#lib/utils/formatting';- import { formatDateTimeShort } from '#lib/utils/formatting';- import IfPermitted from '#lib/components/if-permitted.svelte';- import {- CodeIcon,- TerminalIcon,- ArrowDownIcon,- ClockIcon,- TagIcon,- SettingsIcon,- InfoIcon,- EllipsisIcon,- RedeployIcon- } from '#lib/icons';+ import { CodeIcon, TerminalIcon } from '#lib/icons';import * as Card from '#lib/components/ui/card';- import { Spinner } from '#lib/components/ui/spinner/index.js';- import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';- import type { ColumnSpec, MobileFieldVisibility } from '#lib/components/arcane-table';- import { UniversalMobileCard } from '#lib/components/arcane-table';- import { Badge } from '#lib/components/ui/badge';- import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog/index.js';import { extractErrorMessage } from '#lib/utils/docker';import ResizableSplit from '#lib/components/resizable-split.svelte';import BuildControls from './components/build-controls.svelte';import BuildWorkspacePanel from './components/build-workspace-panel.svelte';import BuildConfigPanel from './components/build-config-panel.svelte';import BuildOutputPanel from './components/build-output-panel.svelte';+ import ImageBuildHistoryPanel from './components/image-build-history-panel.svelte';import type { BuildProviderOption, SelectOption } from './components/build-form.types';- import { imageService } from '#lib/services/image-service';import { containerRegistryService } from '#lib/services/container-registry-service';import { buildImageReference, getRegistryDisplayName } from '#lib/utils/registry';import { parseList } from '#lib/utils/form-parsers';- import type { ImageBuildRecord, ImageBuildStatus } from '#lib/types/docker';- import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared';+ import type { ImageBuildRecord } from '#lib/types/docker';+ import type { SearchPaginationSortRequest } from '#lib/types/shared';import { queryKeys } from '#lib/query/query-keys';import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';import { useUrlTab } from '#lib/hooks/use-url-tab.svelte';+ import {+ formatBuildArgs,+ formatKeyValueMap,+ formatStringList,+ getContextPathFromBuild,+ isGitBuildContextSource+ } from './image-build-history';let {}: PageProps = $props();@@ -160,30 +147,9 @@let buildTab = $state('workspace');let rightPanelTab = $state<'config' | 'output'>('config');let showAdvanced = $state(false);- const EMPTY_BUILD_HISTORY: Paginated<ImageBuildRecord> = {- data: [],- pagination: { totalPages: 1, totalItems: 0, currentPage: 1, itemsPerPage: 20 }- };-- let buildHistoryRequestOptions = $state<SearchPaginationSortRequest>({- pagination: { page: 1, limit: 20 },- sort: { column: 'createdAt', direction: 'desc' }- });- let buildHistorySelectedIds = $state<string[]>([]);- let buildHistoryMobileFieldVisibility = $state<Record<string, boolean>>({});- let buildHistorySelectedOptimistic = $state<ImageBuildRecord | null>(null);- let buildHistorySelectedId = $state<string | null>(null);- let buildHistoryDetailsOpen = $state(false);const selectedEnvId = $derived(environmentStore.selected?.id || '0');const queryClient = useQueryClient();-- const buildHistoryQuery = createQuery(() => ({- queryKey: queryKeys.images.buildsList(selectedEnvId, buildHistoryRequestOptions),- queryFn: () => imageService.getImageBuilds(buildHistoryRequestOptions)- }));-- const buildHistoryItems = $derived<Paginated<ImageBuildRecord>>(buildHistoryQuery.data ?? EMPTY_BUILD_HISTORY);const resolvedProvider = $derived(depotAvailable ? $inputs.provider.value : 'local');const isPushMode = $derived(resolvedProvider === 'depot' ? true : $inputs.push.value);@@ -235,41 +201,6 @@}});- let buildHistoryQueryLastError: string | null = null;-- $effect(() => {- const err = buildHistoryQuery.error as any;- if (!err) return;- const message = err?.message ? String(err.message) : m.common_error();- if (message && message !== buildHistoryQueryLastError) {- buildHistoryQueryLastError = message;- toast.error(message);- }- });-- const buildHistoryDetailQuery = createQuery(() => ({- queryKey: buildHistorySelectedId- ? queryKeys.images.buildRecord(selectedEnvId, buildHistorySelectedId)- : (['images', selectedEnvId, 'builds', 'none'] as const),- queryFn: () => imageService.getImageBuild(buildHistorySelectedId!),- enabled: !!buildHistorySelectedId && buildHistoryDetailsOpen- }));-- const buildHistorySelected = $derived<ImageBuildRecord | null>(buildHistoryDetailQuery.data ?? buildHistorySelectedOptimistic);-- let buildHistoryDetailLastError: string | null = null;-- $effect(() => {- const err = buildHistoryDetailQuery.error as any;- if (!err) return;- const message = err?.message ? String(err.message) : m.common_error();- if (message && message !== buildHistoryDetailLastError) {- buildHistoryDetailLastError = message;- toast.error(message);- }- });- const buildHistoryDetailsLoading = $derived(buildHistoryDetailQuery.isPending || buildHistoryDetailQuery.isFetching);-type ImageBuildRequest = { envId: string; provider: 'local' | 'depot' } & Pick<ImageBuildRecord,| 'contextDir'@@ -404,57 +335,6 @@{ value: 'history', label: m.builds() }]);- type BuildOutputEntry = {- text: string;- isError: boolean;- };-- const buildHistoryOutputEntries = $derived.by(() => parseBuildOutput(buildHistorySelected?.output ?? ''));-- function getBuildTitle(build: ImageBuildRecord) {- return build.tags?.[0] || buildContextDisplayName(build.contextDir) || build.contextDir;- }-- const buildHistoryColumns = [- {- accessorKey: 'status',- title: m.common_status(),- sortable: true,- cell: BuildHistoryStatusCell- },- {- id: 'tags',- title: m.common_tags(),- cell: BuildHistoryTagsCell- },- {- accessorKey: 'provider',- title: m.build_provider(),- sortable: true,- cell: BuildHistoryProviderCell- },- {- accessorKey: 'createdAt',- title: m.common_created(),- sortable: true,- cell: BuildHistoryTimeCell- },- {- accessorKey: 'durationMs',- title: m.duration(),- cell: BuildHistoryDurationCell- }- ] satisfies ColumnSpec<ImageBuildRecord>[];-- const buildHistoryMobileFields = [- { id: 'status', label: m.common_status(), defaultVisible: true },- { id: 'tags', label: m.common_tags(), defaultVisible: true },- { id: 'context', label: m.build_context(), defaultVisible: true },- { id: 'provider', label: m.build_provider(), defaultVisible: true },- { id: 'createdAt', label: m.common_created(), defaultVisible: true },- { id: 'durationMs', label: m.duration(), defaultVisible: false }- ];-onMount(() => {const mq = window.matchMedia('(min-width: 1024px)');const update = () => {@@ -573,148 +453,6 @@return null;}- function formatKeyValueMap(values?: Record<string, string>) {- if (!values || Object.keys(values).length === 0) return '';- return Object.entries(values)- .map(([key, value]) => `${key}=${value}`)- .join('\n');- }-- function formatStringList(values?: string[]) {- if (!values || values.length === 0) return '';- return values.join('\n');- }-- function formatTimestamp(value?: string) {- if (!value) return '-';- return formatDateTimeShort(value) || value;- }-- function formatDuration(ms?: number) {- if (!ms || ms <= 0) return '-';- const totalSeconds = Math.round(ms / 1000);- const minutes = Math.floor(totalSeconds / 60);- const seconds = totalSeconds % 60;- if (minutes > 0) return `${minutes}m ${seconds}s`;- return `${seconds}s`;- }-- function formatBuildArgs(buildArgs?: Record<string, string>) {- return formatKeyValueMap(buildArgs);- }-- function isGitBuildContextSource(value?: string): boolean {- const trimmed = value?.trim();- if (!trimmed) return false;- const base = trimmed.split('#', 1)[0]?.trim() ?? '';- if (!base) return false;- if (base.startsWith('git@')) return true;- try {- const parsed = new URL(base);- const protocol = parsed.protocol.toLowerCase();- if (protocol === 'ssh:' || protocol === 'git:') return true;- if (protocol === 'http:' || protocol === 'https:') {- return parsed.pathname !== '/';- }- } catch {- return false;- }- return false;- }-- function buildContextDisplayName(value?: string): string {- const trimmed = value?.trim();- if (!trimmed) return '';- if (!isGitBuildContextSource(trimmed)) {- return trimmed.split('/').pop() || trimmed;- }-- const withoutFragment = trimmed.split('#', 1)[0] ?? trimmed;- const normalized = withoutFragment.endsWith('/') ? withoutFragment.slice(0, -1) : withoutFragment;- const repoName = normalized.split('/').pop() || normalized;- return repoName.replace(/\.git$/i, '');- }-- function getContextPathFromBuild(build: ImageBuildRecord) {- if (isGitBuildContextSource(build.contextDir)) return '/';- const root = buildsRoot.endsWith('/') ? buildsRoot.slice(0, -1) : buildsRoot;- if (!build.contextDir || build.contextDir === root) return '/';- if (build.contextDir.startsWith(`${root}/`)) {- return build.contextDir.slice(root.length);- }- return '/';- }-- // Build history output is the raw docker CLI text of the build. Records- // written before the raw-output change contain NDJSON progress events; pull- // their text out so old history stays readable.- function parseBuildOutput(output: string): BuildOutputEntry[] {- if (!output) return [];- return output- .split('\n')- .map((line) => line.trim())- .filter(Boolean)- .map((line) => {- try {- const data = JSON.parse(line) as Record<string, unknown>;- if (data && typeof data === 'object') {- const error = data['error'];- if (error) {- const message =- typeof error === 'object' && error !== null ? ((error as { message?: string }).message ?? line) : String(error);- return { text: sanitizeLogText(message), isError: true } satisfies BuildOutputEntry;- }- const text = data['log'] ?? data['status'] ?? data['stream'];- if (typeof text === 'string') {- return { text: sanitizeLogText(text), isError: false } satisfies BuildOutputEntry;- }- }- } catch {- // Raw text line.- }- return { text: sanitizeLogText(line), isError: false } satisfies BuildOutputEntry;- })- .filter((entry) => entry.text.trim() !== '');- }-- function buildHistoryStatusLabel(status?: ImageBuildStatus) {- switch (status) {- case 'running':- return m.common_running();- case 'success':- return m.common_success();- case 'failed':- return m.common_failed();- default:- return m.common_unknown();- }- }-- function getStatusBadgeVariant(status?: ImageBuildStatus) {- switch (status) {- case 'success':- return 'green';- case 'failed':- return 'red';- case 'running':- return 'blue';- default:- return 'gray';- }- }-- async function loadBuildHistory(options: SearchPaginationSortRequest = buildHistoryRequestOptions) {- buildHistoryRequestOptions = options;- const result = await buildHistoryQuery.refetch();- return result.data ?? buildHistoryQuery.data ?? EMPTY_BUILD_HISTORY;- }-- function openBuildDetails(build: ImageBuildRecord) {- buildHistorySelectedId = build.id;- buildHistorySelectedOptimistic = build;- buildHistoryDetailsOpen = true;- }-function applyBuildConfig(build: ImageBuildRecord) {form.setValue('tags', build.tags?.join(', ') ?? '');form.setValue('dockerfile', build.dockerfile ?? '');@@ -761,12 +499,11 @@} else {contextMode = 'workspace';remoteContextSource = '';- selectedContextPath = getContextPathFromBuild(build);+ selectedContextPath = getContextPathFromBuild(build, buildsRoot);}mainUrlTab.select('build');rightPanelTab = 'config';buildTab = 'configuration';- buildHistoryDetailsOpen = false;}async function handleSubmit() {@@ -853,8 +590,8 @@const resolvedEnvId = await environmentStore.getCurrentEnvironmentId();await buildMutation.mutateAsync({ envId: resolvedEnvId, ...payload });toast.success(m.build_completed());- } catch (error: any) {- const message = sanitizeLogText(String(error?.message || m.build_failed()));+ } catch (error) {+ const message = sanitizeLogText(error instanceof Error ? error.message : m.build_failed());buildError = message;buildStatusText = message.toLowerCase().startsWith(m.build_failed().toLowerCase())? message@@ -904,343 +641,9 @@/>{/snippet}-{#snippet BuildHistoryStatusCell({ value }: { value: unknown })}- <Badge variant={getStatusBadgeVariant(value as ImageBuildStatus)} size="sm" minWidth="20"- >{buildHistoryStatusLabel(value as ImageBuildStatus)}</Badge- >-{/snippet}--{#snippet BuildHistoryTagsCell({ item }: { item: ImageBuildRecord })}- <div class="space-y-1">- <div class="text-sm font-medium">{getBuildTitle(item)}</div>- <div class="truncate text-xs text-muted-foreground">{item.contextDir}</div>- </div>-{/snippet}--{#snippet BuildHistoryProviderCell({ value }: { value: unknown })}- <span class="text-sm">{String(value ?? '-') || '-'}</span>-{/snippet}--{#snippet BuildHistoryTimeCell({ value }: { value: unknown })}- <span class="text-sm">{formatTimestamp(String(value ?? ''))}</span>-{/snippet}--{#snippet BuildHistoryDurationCell({ value }: { value: unknown })}- <span class="text-sm">{formatDuration(Number(value ?? 0))}</span>-{/snippet}--{#snippet BuildHistoryRowActions({ item }: { item: ImageBuildRecord })}- <DropdownMenu.Root>- <DropdownMenu.Trigger data-row-select-ignore>- <ArcaneButton action="inspect" tone="ghost" size="icon" showLabel={false} icon={EllipsisIcon} />- </DropdownMenu.Trigger>- <DropdownMenu.Content align="end">- <DropdownMenu.Item onclick={() => openBuildDetails(item)}>- <InfoIcon class="size-4" />- {m.common_view_details()}- </DropdownMenu.Item>- </DropdownMenu.Content>- </DropdownMenu.Root>-{/snippet}--{#snippet BuildHistoryMobileCard({- item,- mobileFieldVisibility-}: {- item: ImageBuildRecord;- mobileFieldVisibility: MobileFieldVisibility;-})}- <UniversalMobileCard- {item}- icon={(item: ImageBuildRecord) => ({- component: TerminalIcon,- variant:- item.status === 'success' ? 'emerald' : item.status === 'failed' ? 'red' : item.status === 'running' ? 'blue' : 'gray'- })}- title={(item: ImageBuildRecord) => getBuildTitle(item)}- subtitle={(item: ImageBuildRecord) => ((mobileFieldVisibility['context'] ?? true) ? item.contextDir : null)}- badges={[- (item: ImageBuildRecord) => ({- variant: getStatusBadgeVariant(item.status),- text: buildHistoryStatusLabel(item.status)- })- ]}- fields={[- {- label: m.common_tags(),- getValue: (item: ImageBuildRecord) => item.tags?.join(', ') || '-',- icon: TagIcon,- iconVariant: 'gray' as const,- show: mobileFieldVisibility['tags'] ?? true- },- {- label: m.build_provider(),- getValue: (item: ImageBuildRecord) => item.provider || '-',- icon: SettingsIcon,- iconVariant: 'gray' as const,- show: mobileFieldVisibility['provider'] ?? true- },- {- label: m.common_created(),- getValue: (item: ImageBuildRecord) => formatTimestamp(item.createdAt),- icon: ClockIcon,- iconVariant: 'gray' as const,- show: mobileFieldVisibility['createdAt'] ?? true- },- {- label: m.duration(),- getValue: (item: ImageBuildRecord) => formatDuration(item.durationMs ?? 0),- icon: ArrowDownIcon,- iconVariant: 'gray' as const,- show: mobileFieldVisibility['durationMs'] ?? false- }- ]}- onclick={(item: ImageBuildRecord) => openBuildDetails(item)}- />-{/snippet}-{#snippet historyContent()}- <div class="flex h-full flex-col p-6">- <ArcaneTable- persistKey="arcane-build-history-table"- items={buildHistoryItems}- bind:requestOptions={buildHistoryRequestOptions}- bind:selectedIds={buildHistorySelectedIds}- bind:mobileFieldVisibility={buildHistoryMobileFieldVisibility}- onRefresh={loadBuildHistory}- selectionDisabled={true}- columns={buildHistoryColumns}- mobileFields={buildHistoryMobileFields}- rowActions={BuildHistoryRowActions}- mobileCard={BuildHistoryMobileCard}- />-- <ResponsiveDialog- bind:open={buildHistoryDetailsOpen}- title={buildHistorySelected ? (buildHistorySelected.tags?.[0] ?? m.build_output()) : m.build_output()}- description={buildHistorySelected ? buildHistorySelected.contextDir : undefined}- contentClass="sm:max-w-[1100px]"- class="min-h-0 lg:overflow-hidden"- >- <div class="space-y-4 pb-4">- {#if buildHistorySelected}- <div class="flex flex-wrap items-center justify-between gap-3 text-sm">- <div class="flex flex-wrap items-center gap-2">- <Badge variant={getStatusBadgeVariant(buildHistorySelected.status)} size="sm" minWidth="20"- >{buildHistoryStatusLabel(buildHistorySelected.status)}</Badge- >- {#if buildHistorySelected.provider}- <span class="text-muted-foreground">{buildHistorySelected.provider}</span>- {/if}- {#if buildHistorySelected.durationMs}- <span class="text-muted-foreground">{formatDuration(buildHistorySelected.durationMs)}</span>- {/if}- <span class="text-muted-foreground">{formatTimestamp(buildHistorySelected.createdAt)}</span>- </div>- <IfPermitted perm="images:build">- <ArcaneButton- action="base"- tone="outline"- size="sm"- icon={RedeployIcon}- customLabel={m.build_rebuild()}- onclick={() => buildHistorySelected && applyBuildConfig(buildHistorySelected)}- />- </IfPermitted>- </div>- {#if buildHistorySelected.errorMessage}- <div class="rounded-lg border border-destructive/20 bg-destructive/10 p-3 text-sm text-destructive">- {buildHistorySelected.errorMessage}- </div>- {/if}- {/if}-- <div class="grid gap-4 lg:h-[70vh] lg:grid-cols-[360px_minmax(0,1fr)] lg:items-stretch">- <div class="min-h-0 space-y-3 lg:overflow-auto lg:overscroll-contain lg:pr-1">- {#if buildHistorySelected}- <div class="grid gap-3">- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.build_context()}- </div>- <div class="mt-2 font-mono text-xs break-all">{buildHistorySelected.contextDir}</div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.common_tags()}- </div>- <div class="mt-2 text-xs">- {buildHistorySelected.tags?.join(', ') || '-'}- </div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.dockerfile()}- </div>- <div class="mt-2 text-xs">{buildHistorySelected.dockerfile || '-'}</div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.target()}- </div>- <div class="mt-2 text-xs">{buildHistorySelected.target || '-'}</div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.platforms_label()}- </div>- <div class="mt-2 text-xs">{buildHistorySelected.platforms?.join(', ') || '-'}</div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.build_provider()}- </div>- <div class="mt-2 text-xs">{buildHistorySelected.provider || '-'}</div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.push()} / {m.load()}- </div>- <div class="mt-2 text-xs">- {buildHistorySelected.push ? m.common_yes() : m.common_no()} / {buildHistorySelected.load- ? m.common_yes()- : m.common_no()}- </div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.build_no_cache_pull_base_label()}- </div>- <div class="mt-2 text-xs">- {buildHistorySelected.noCache ? m.common_yes() : m.common_no()} / {buildHistorySelected.pull- ? m.common_yes()- : m.common_no()}- </div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.resource_network_cap()}- </div>- <div class="mt-2 text-xs">{buildHistorySelected.network || '-'}</div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.build_args()}- </div>- {#if buildHistorySelected.buildArgs && Object.keys(buildHistorySelected.buildArgs).length > 0}- <pre class="mt-2 font-mono text-[11px] wrap-break-word whitespace-pre-wrap">- {formatBuildArgs(buildHistorySelected.buildArgs)}- </pre>- {:else}- <div class="mt-2 text-xs">-</div>- {/if}- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.common_labels()}- </div>- {#if buildHistorySelected.labels && Object.keys(buildHistorySelected.labels).length > 0}- <pre class="mt-2 font-mono text-[11px] wrap-break-word whitespace-pre-wrap">- {formatKeyValueMap(buildHistorySelected.labels)}- </pre>- {:else}- <div class="mt-2 text-xs">-</div>- {/if}- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.build_cache_from_label()}- </div>- <div class="mt-2 text-xs">{buildHistorySelected.cacheFrom?.join(', ') || '-'}</div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.build_cache_to_label()}- </div>- <div class="mt-2 text-xs">{buildHistorySelected.cacheTo?.join(', ') || '-'}</div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.isolation()}- </div>- <div class="mt-2 text-xs">{buildHistorySelected.isolation || '-'}</div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.build_shm_size_short_label()}- </div>- <div class="mt-2 text-xs">- {buildHistorySelected.shmSize ? m.build_bytes({ size: String(buildHistorySelected.shmSize) }) : '-'}- </div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.build_ulimits_label()}- </div>- {#if buildHistorySelected.ulimits && Object.keys(buildHistorySelected.ulimits).length > 0}- <pre class="mt-2 font-mono text-[11px] wrap-break-word whitespace-pre-wrap">- {formatKeyValueMap(buildHistorySelected.ulimits)}- </pre>- {:else}- <div class="mt-2 text-xs">-</div>- {/if}- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.build_entitlements_label()}- </div>- <div class="mt-2 text-xs">{buildHistorySelected.entitlements?.join(', ') || '-'}</div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.build_privileged_heading_label()}- </div>- <div class="mt-2 text-xs">{buildHistorySelected.privileged ? m.common_yes() : m.common_no()}</div>- </div>- <div class="rounded-lg border border-border/60 bg-zinc-950/40 p-3">- <div class="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase">- {m.build_extra_hosts_label()}- </div>- <div class="mt-2 text-xs">{buildHistorySelected.extraHosts?.join(', ') || '-'}</div>- </div>- </div>- {/if}- </div>- <div class="flex min-h-0 flex-col overflow-hidden rounded-xl border border-border/60 bg-card/30">- <div class="flex items-center justify-between border-b border-border/60 px-4 py-3">- <div class="text-sm font-medium">{m.build_output()}</div>- {#if buildHistorySelected?.outputTruncated}- <span class="text-xs text-amber-400">{m.build_output_truncated()}</span>- {/if}- </div>- <div class="max-h-[60vh] min-h-[260px] overflow-auto overscroll-contain p-4 lg:max-h-none lg:min-h-0 lg:flex-1">- {#if buildHistoryDetailsLoading}- <div class="flex h-full items-center justify-center">- <Spinner class="size-6 text-muted-foreground" />- </div>- {:else if buildHistorySelected?.output}- {#if buildHistoryOutputEntries.length > 0}- <div class="rounded-lg border border-border/50 bg-zinc-950/40 p-3 font-mono text-xs leading-relaxed">- {#each buildHistoryOutputEntries as entry, entryIndex (entry.text + entryIndex)}- <div class={`break-words whitespace-pre-wrap ${entry.isError ? 'text-destructive' : 'text-foreground'}`}>- {entry.text}- </div>- {/each}- </div>- {:else}- <div class="text-sm text-muted-foreground">{m.build_output_placeholder()}</div>- {/if}- {:else}- <div class="text-sm text-muted-foreground">{m.build_output_placeholder()}</div>- {/if}- </div>- </div>- </div>- </div>- </ResponsiveDialog>- </div>+ <ImageBuildHistoryPanel environmentId={selectedEnvId} onApplyBuild={applyBuildConfig} />{/snippet}-<!-- Right panel with tabs (config + output) -->{#snippet rightPanel()}<div class="flex h-full flex-col">diff --git a/frontend/src/routes/(app)/images/builds/components/image-build-history-panel.svelte b/frontend/src/routes/(app)/images/builds/components/image-build-history-panel.sveltenew file mode 100644index 000000000..4247fb297--- /dev/null+++ b/frontend/src/routes/(app)/images/builds/components/image-build-history-panel.svelte@@ -0,0 +1,359 @@+<script lang="ts">+ import { createQuery } from '@tanstack/svelte-query';+ import { toast } from 'svelte-sonner';+ import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';+ import type { ColumnSpec, MobileFieldVisibility } from '#lib/components/arcane-table';+ import { UniversalMobileCard } from '#lib/components/arcane-table';+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';+ import IfPermitted from '#lib/components/if-permitted.svelte';+ import { KeyValueCard } from '#lib/components/resource-detail';+ import { Badge } from '#lib/components/ui/badge';+ import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';+ import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog/index.js';+ import { Spinner } from '#lib/components/ui/spinner/index.js';+ import {+ ArrowDownIcon,+ ClockIcon,+ EllipsisIcon,+ InfoIcon,+ RedeployIcon,+ SettingsIcon,+ TagIcon,+ TerminalIcon+ } from '#lib/icons';+ import { m } from '#lib/paraglide/messages';+ import { queryKeys } from '#lib/query/query-keys';+ import { imageService } from '#lib/services/image-service';+ import type { ImageBuildRecord, ImageBuildStatus } from '#lib/types/docker';+ import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared';+ import {+ buildHistoryStatusLabel,+ formatBuildDuration,+ formatBuildTimestamp,+ getBuildDetailItems,+ getBuildStatusBadgeVariant,+ getBuildTitle,+ parseBuildOutput+ } from '../image-build-history';++ interface Props {+ environmentId: string;+ onApplyBuild: (build: ImageBuildRecord) => void;+ }++ let { environmentId, onApplyBuild }: Props = $props();++ const EMPTY_BUILD_HISTORY: Paginated<ImageBuildRecord> = {+ data: [],+ pagination: { totalPages: 1, totalItems: 0, currentPage: 1, itemsPerPage: 20 }+ };++ let requestOptions = $state<SearchPaginationSortRequest>({+ pagination: { page: 1, limit: 20 },+ sort: { column: 'createdAt', direction: 'desc' }+ });+ let selectedIds = $state<string[]>([]);+ let mobileFieldVisibility = $state<Record<string, boolean>>({});+ let selectedOptimistic = $state<ImageBuildRecord | null>(null);+ let selectedId = $state<string | null>(null);+ let detailsOpen = $state(false);++ const historyQuery = createQuery(() => ({+ queryKey: queryKeys.images.buildsList(environmentId, requestOptions),+ queryFn: () => imageService.getImageBuilds(requestOptions)+ }));++ const historyItems = $derived<Paginated<ImageBuildRecord>>(historyQuery.data ?? EMPTY_BUILD_HISTORY);++ let historyLastError: string | null = null;+ $effect(() => {+ const error = historyQuery.error;+ if (!error) return;+ const message = error instanceof Error ? error.message : m.common_error();+ if (message && message !== historyLastError) {+ historyLastError = message;+ toast.error(message);+ }+ });++ const detailQuery = createQuery(() => ({+ queryKey: selectedId+ ? queryKeys.images.buildRecord(environmentId, selectedId)+ : (['images', environmentId, 'builds', 'none'] as const),+ queryFn: () => imageService.getImageBuild(selectedId!),+ enabled: !!selectedId && detailsOpen+ }));++ const selectedBuild = $derived<ImageBuildRecord | null>(detailQuery.data ?? selectedOptimistic);+ const detailsLoading = $derived(detailQuery.isPending || detailQuery.isFetching);+ const outputEntries = $derived.by(() => parseBuildOutput(selectedBuild?.output ?? ''));++ let detailLastError: string | null = null;+ $effect(() => {+ const error = detailQuery.error;+ if (!error) return;+ const message = error instanceof Error ? error.message : m.common_error();+ if (message && message !== detailLastError) {+ detailLastError = message;+ toast.error(message);+ }+ });++ const detailItems = $derived(selectedBuild ? getBuildDetailItems(selectedBuild) : []);++ const columns = [+ {+ accessorKey: 'status',+ title: m.common_status(),+ sortable: true,+ cell: BuildHistoryStatusCell+ },+ {+ id: 'tags',+ title: m.common_tags(),+ cell: BuildHistoryTagsCell+ },+ {+ accessorKey: 'provider',+ title: m.build_provider(),+ sortable: true,+ cell: BuildHistoryProviderCell+ },+ {+ accessorKey: 'createdAt',+ title: m.common_created(),+ sortable: true,+ cell: BuildHistoryTimeCell+ },+ {+ accessorKey: 'durationMs',+ title: m.duration(),+ cell: BuildHistoryDurationCell+ }+ ] satisfies ColumnSpec<ImageBuildRecord>[];++ const mobileFields = [+ { id: 'status', label: m.common_status(), defaultVisible: true },+ { id: 'tags', label: m.common_tags(), defaultVisible: true },+ { id: 'context', label: m.build_context(), defaultVisible: true },+ { id: 'provider', label: m.build_provider(), defaultVisible: true },+ { id: 'createdAt', label: m.common_created(), defaultVisible: true },+ { id: 'durationMs', label: m.duration(), defaultVisible: false }+ ];++ async function loadHistory(options: SearchPaginationSortRequest = requestOptions) {+ requestOptions = options;+ const result = await historyQuery.refetch();+ return result.data ?? historyQuery.data ?? EMPTY_BUILD_HISTORY;+ }++ function openDetails(build: ImageBuildRecord) {+ selectedId = build.id;+ selectedOptimistic = build;+ detailsOpen = true;+ }++ function applySelectedBuild() {+ if (!selectedBuild) return;+ onApplyBuild(selectedBuild);+ detailsOpen = false;+ }+</script>++{#snippet BuildHistoryStatusCell({ value }: { value: unknown })}+ <Badge variant={getBuildStatusBadgeVariant(value as ImageBuildStatus)} size="sm" minWidth="20"+ >{buildHistoryStatusLabel(value as ImageBuildStatus)}</Badge+ >+{/snippet}++{#snippet BuildHistoryTagsCell({ item }: { item: ImageBuildRecord })}+ <div class="space-y-1">+ <div class="text-sm font-medium">{getBuildTitle(item)}</div>+ <div class="truncate text-xs text-muted-foreground">{item.contextDir}</div>+ </div>+{/snippet}++{#snippet BuildHistoryProviderCell({ value }: { value: unknown })}+ <span class="text-sm">{String(value ?? '-') || '-'}</span>+{/snippet}++{#snippet BuildHistoryTimeCell({ value }: { value: unknown })}+ <span class="text-sm">{formatBuildTimestamp(String(value ?? ''))}</span>+{/snippet}++{#snippet BuildHistoryDurationCell({ value }: { value: unknown })}+ <span class="text-sm">{formatBuildDuration(Number(value ?? 0))}</span>+{/snippet}++{#snippet BuildHistoryRowActions({ item }: { item: ImageBuildRecord })}+ <DropdownMenu.Root>+ <DropdownMenu.Trigger data-row-select-ignore>+ <ArcaneButton action="inspect" tone="ghost" size="icon" showLabel={false} icon={EllipsisIcon} />+ </DropdownMenu.Trigger>+ <DropdownMenu.Content align="end">+ <DropdownMenu.Item onclick={() => openDetails(item)}>+ <InfoIcon class="size-4" />+ {m.common_view_details()}+ </DropdownMenu.Item>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+{/snippet}++{#snippet BuildHistoryMobileCard({+ item,+ mobileFieldVisibility: fieldVisibility+}: {+ item: ImageBuildRecord;+ mobileFieldVisibility: MobileFieldVisibility;+})}+ <UniversalMobileCard+ {item}+ icon={(item: ImageBuildRecord) => ({+ component: TerminalIcon,+ variant:+ item.status === 'success' ? 'emerald' : item.status === 'failed' ? 'red' : item.status === 'running' ? 'blue' : 'gray'+ })}+ title={(item: ImageBuildRecord) => getBuildTitle(item)}+ subtitle={(item: ImageBuildRecord) => ((fieldVisibility['context'] ?? true) ? item.contextDir : null)}+ badges={[+ (item: ImageBuildRecord) => ({+ variant: getBuildStatusBadgeVariant(item.status),+ text: buildHistoryStatusLabel(item.status)+ })+ ]}+ fields={[+ {+ label: m.common_tags(),+ getValue: (item: ImageBuildRecord) => item.tags?.join(', ') || '-',+ icon: TagIcon,+ iconVariant: 'gray' as const,+ show: fieldVisibility['tags'] ?? true+ },+ {+ label: m.build_provider(),+ getValue: (item: ImageBuildRecord) => item.provider || '-',+ icon: SettingsIcon,+ iconVariant: 'gray' as const,+ show: fieldVisibility['provider'] ?? true+ },+ {+ label: m.common_created(),+ getValue: (item: ImageBuildRecord) => formatBuildTimestamp(item.createdAt),+ icon: ClockIcon,+ iconVariant: 'gray' as const,+ show: fieldVisibility['createdAt'] ?? true+ },+ {+ label: m.duration(),+ getValue: (item: ImageBuildRecord) => formatBuildDuration(item.durationMs ?? 0),+ icon: ArrowDownIcon,+ iconVariant: 'gray' as const,+ show: fieldVisibility['durationMs'] ?? false+ }+ ]}+ onclick={(item: ImageBuildRecord) => openDetails(item)}+ />+{/snippet}++<div class="flex h-full flex-col p-6">+ <ArcaneTable+ persistKey="arcane-build-history-table"+ items={historyItems}+ bind:requestOptions+ bind:selectedIds+ bind:mobileFieldVisibility+ onRefresh={loadHistory}+ selectionDisabled={true}+ {columns}+ {mobileFields}+ rowActions={BuildHistoryRowActions}+ mobileCard={BuildHistoryMobileCard}+ />++ <ResponsiveDialog+ bind:open={detailsOpen}+ title={selectedBuild ? (selectedBuild.tags?.[0] ?? m.build_output()) : m.build_output()}+ description={selectedBuild ? selectedBuild.contextDir : undefined}+ contentClass="sm:max-w-[1100px]"+ class="min-h-0 lg:overflow-hidden"+ >+ <div class="space-y-4 pb-4">+ {#if selectedBuild}+ <div class="flex flex-wrap items-center justify-between gap-3 text-sm">+ <div class="flex flex-wrap items-center gap-2">+ <Badge variant={getBuildStatusBadgeVariant(selectedBuild.status)} size="sm" minWidth="20"+ >{buildHistoryStatusLabel(selectedBuild.status)}</Badge+ >+ {#if selectedBuild.provider}+ <span class="text-muted-foreground">{selectedBuild.provider}</span>+ {/if}+ {#if selectedBuild.durationMs}+ <span class="text-muted-foreground">{formatBuildDuration(selectedBuild.durationMs)}</span>+ {/if}+ <span class="text-muted-foreground">{formatBuildTimestamp(selectedBuild.createdAt)}</span>+ </div>+ <IfPermitted perm="images:build">+ <ArcaneButton+ action="base"+ tone="outline"+ size="sm"+ icon={RedeployIcon}+ customLabel={m.build_rebuild()}+ onclick={applySelectedBuild}+ />+ </IfPermitted>+ </div>+ {#if selectedBuild.errorMessage}+ <div class="rounded-lg border border-destructive/20 bg-destructive/10 p-3 text-sm text-destructive">+ {selectedBuild.errorMessage}+ </div>+ {/if}+ {/if}++ <div class="grid gap-4 lg:h-[70vh] lg:grid-cols-[360px_minmax(0,1fr)] lg:items-stretch">+ <div class="min-h-0 space-y-3 lg:overflow-auto lg:overscroll-contain lg:pr-1">+ {#each detailItems as detail (detail.label)}+ <KeyValueCard+ label={detail.label}+ variant="outlined"+ contentClass="flex flex-col gap-2 p-3"+ labelClass="text-[10px] font-semibold tracking-[0.12em] text-muted-foreground uppercase"+ valueClass="text-xs break-all whitespace-pre-wrap"+ >+ {detail.value}+ </KeyValueCard>+ {/each}+ </div>+ <div class="flex min-h-0 flex-col overflow-hidden rounded-xl border border-border/60 bg-card/30">+ <div class="flex items-center justify-between border-b border-border/60 px-4 py-3">+ <div class="text-sm font-medium">{m.build_output()}</div>+ {#if selectedBuild?.outputTruncated}+ <span class="text-xs text-amber-400">{m.build_output_truncated()}</span>+ {/if}+ </div>+ <div class="max-h-[60vh] min-h-[260px] overflow-auto overscroll-contain p-4 lg:max-h-none lg:min-h-0 lg:flex-1">+ {#if detailsLoading}+ <div class="flex h-full items-center justify-center">+ <Spinner class="size-6 text-muted-foreground" />+ </div>+ {:else if selectedBuild?.output}+ {#if outputEntries.length > 0}+ <div class="rounded-lg border border-border/50 bg-zinc-950/40 p-3 font-mono text-xs leading-relaxed">+ {#each outputEntries as entry, entryIndex (entry.text + entryIndex)}+ <div class={`break-words whitespace-pre-wrap ${entry.isError ? 'text-destructive' : 'text-foreground'}`}>+ {entry.text}+ </div>+ {/each}+ </div>+ {:else}+ <div class="text-sm text-muted-foreground">{m.build_output_placeholder()}</div>+ {/if}+ {:else}+ <div class="text-sm text-muted-foreground">{m.build_output_placeholder()}</div>+ {/if}+ </div>+ </div>+ </div>+ </div>+ </ResponsiveDialog>+</div>diff --git a/frontend/src/routes/(app)/images/builds/image-build-history.ts b/frontend/src/routes/(app)/images/builds/image-build-history.tsnew file mode 100644index 000000000..a64f9d8cc--- /dev/null+++ b/frontend/src/routes/(app)/images/builds/image-build-history.ts@@ -0,0 +1,167 @@+import * as m from '#lib/paraglide/messages.js';+import type { ImageBuildRecord, ImageBuildStatus } from '#lib/types/docker';+import { formatDateTimeShort, sanitizeLogText } from '#lib/utils/formatting';++export type BuildOutputEntry = {+ text: string;+ isError: boolean;+};++export function formatKeyValueMap(values?: Record<string, string>): string {+ if (!values || Object.keys(values).length === 0) return '';+ return Object.entries(values)+ .map(([key, value]) => `${key}=${value}`)+ .join('\n');+}++export const formatBuildArgs = formatKeyValueMap;++export function formatStringList(values?: string[]): string {+ return values?.length ? values.join('\n') : '';+}++export function formatBuildTimestamp(value?: string): string {+ if (!value) return '-';+ return formatDateTimeShort(value) || value;+}++export function formatBuildDuration(ms?: number): string {+ if (!ms || ms <= 0) return '-';+ const totalSeconds = Math.round(ms / 1000);+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;+ return minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`;+}++function formatBuildDetailValue(value?: string | null): string {+ return value || '-';+}++function formatBuildDetailList(values?: string[]): string {+ return formatBuildDetailValue(values?.join(', '));+}++function formatBuildDetailBoolean(value?: boolean): string {+ return value ? m.common_yes() : m.common_no();+}++function formatBuildDetailBytes(value?: number): string {+ return value ? m.build_bytes({ size: String(value) }) : '-';+}++export function getBuildDetailItems(build: ImageBuildRecord): Array<{ label: string; value: string }> {+ return [+ { label: m.build_context(), value: build.contextDir },+ { label: m.common_tags(), value: formatBuildDetailList(build.tags) },+ { label: m.dockerfile(), value: formatBuildDetailValue(build.dockerfile) },+ { label: m.target(), value: formatBuildDetailValue(build.target) },+ { label: m.platforms_label(), value: formatBuildDetailList(build.platforms) },+ { label: m.build_provider(), value: formatBuildDetailValue(build.provider) },+ {+ label: `${m.push()} / ${m.load()}`,+ value: `${formatBuildDetailBoolean(build.push)} / ${formatBuildDetailBoolean(build.load)}`+ },+ {+ label: m.build_no_cache_pull_base_label(),+ value: `${formatBuildDetailBoolean(build.noCache)} / ${formatBuildDetailBoolean(build.pull)}`+ },+ { label: m.resource_network_cap(), value: formatBuildDetailValue(build.network) },+ { label: m.build_args(), value: formatBuildDetailValue(formatBuildArgs(build.buildArgs)) },+ { label: m.common_labels(), value: formatBuildDetailValue(formatKeyValueMap(build.labels)) },+ { label: m.build_cache_from_label(), value: formatBuildDetailList(build.cacheFrom) },+ { label: m.build_cache_to_label(), value: formatBuildDetailList(build.cacheTo) },+ { label: m.isolation(), value: formatBuildDetailValue(build.isolation) },+ { label: m.build_shm_size_short_label(), value: formatBuildDetailBytes(build.shmSize) },+ { label: m.build_ulimits_label(), value: formatBuildDetailValue(formatKeyValueMap(build.ulimits)) },+ { label: m.build_entitlements_label(), value: formatBuildDetailList(build.entitlements) },+ { label: m.build_privileged_heading_label(), value: formatBuildDetailBoolean(build.privileged) },+ { label: m.build_extra_hosts_label(), value: formatBuildDetailList(build.extraHosts) }+ ];+}++export function isGitBuildContextSource(value?: string): boolean {+ const trimmed = value?.trim();+ if (!trimmed) return false;+ const base = trimmed.split('#', 1)[0]?.trim() ?? '';+ if (!base) return false;+ if (base.startsWith('git@')) return true;+ try {+ const parsed = new URL(base);+ const protocol = parsed.protocol.toLowerCase();+ if (protocol === 'ssh:' || protocol === 'git:') return true;+ return (protocol === 'http:' || protocol === 'https:') && parsed.pathname !== '/';+ } catch {+ return false;+ }+}++export function buildContextDisplayName(value?: string): string {+ const trimmed = value?.trim();+ if (!trimmed) return '';+ if (!isGitBuildContextSource(trimmed)) return trimmed.split('/').pop() || trimmed;+ const withoutFragment = trimmed.split('#', 1)[0] ?? trimmed;+ const normalized = withoutFragment.endsWith('/') ? withoutFragment.slice(0, -1) : withoutFragment;+ return (normalized.split('/').pop() || normalized).replace(/\.git$/i, '');+}++export function getBuildTitle(build: ImageBuildRecord): string {+ return build.tags?.[0] || buildContextDisplayName(build.contextDir) || build.contextDir;+}++export function getContextPathFromBuild(build: ImageBuildRecord, buildsRoot: string): string {+ if (isGitBuildContextSource(build.contextDir)) return '/';+ const root = buildsRoot.endsWith('/') ? buildsRoot.slice(0, -1) : buildsRoot;+ if (!build.contextDir || build.contextDir === root) return '/';+ return build.contextDir.startsWith(`${root}/`) ? build.contextDir.slice(root.length) : '/';+}++export function parseBuildOutput(output: string): BuildOutputEntry[] {+ if (!output) return [];+ return output+ .split('\n')+ .map((line) => line.trim())+ .filter(Boolean)+ .map((line) => {+ try {+ const data = JSON.parse(line) as Record<string, unknown>;+ const error = data['error'];+ if (error) {+ const message =+ typeof error === 'object' && error !== null ? ((error as { message?: string }).message ?? line) : String(error);+ return { text: sanitizeLogText(message), isError: true } satisfies BuildOutputEntry;+ }+ const text = data['log'] ?? data['status'] ?? data['stream'];+ if (typeof text === 'string') return { text: sanitizeLogText(text), isError: false } satisfies BuildOutputEntry;+ } catch {+ // Raw text line.+ }+ return { text: sanitizeLogText(line), isError: false } satisfies BuildOutputEntry;+ })+ .filter((entry) => entry.text.trim() !== '');+}++export function buildHistoryStatusLabel(status?: ImageBuildStatus): string {+ switch (status) {+ case 'running':+ return m.common_running();+ case 'success':+ return m.common_success();+ case 'failed':+ return m.common_failed();+ default:+ return m.common_unknown();+ }+}++export function getBuildStatusBadgeVariant(status?: ImageBuildStatus): 'green' | 'red' | 'blue' | 'gray' {+ switch (status) {+ case 'success':+ return 'green';+ case 'failed':+ return 'red';+ case 'running':+ return 'blue';+ default:+ return 'gray';+ }+}diff --git a/frontend/src/routes/(app)/images/image-table.svelte b/frontend/src/routes/(app)/images/image-table.svelteindex 8c0d72271..d760b9475 100644--- a/frontend/src/routes/(app)/images/image-table.svelte+++ b/frontend/src/routes/(app)/images/image-table.svelte@@ -416,7 +416,7 @@class: 'text-center'},{ accessorKey: 'size', title: m.common_size(), sortable: true, cell: SizeCell },- { accessorKey: 'created', title: m.common_created(), sortable: true, cell: CreatedCell }+ { accessorKey: 'created', title: m.common_created(), sortable: true, cellComponent: UnixCreatedCell }] satisfies ColumnSpec<ImageSummaryDto>[];const mobileFields = [@@ -475,10 +475,6 @@{bytes.format(Number(value ?? 0))}{/snippet}-{#snippet CreatedCell({ value }: { value: unknown })}- <UnixCreatedCell {value} />-{/snippet}-{#snippet StatusCell({ item }: { item: ImageSummaryDto })}<InUseStatus inUse={item.inUse} />{/snippet}diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte b/frontend/src/routes/(app)/projects/[projectId]/+page.svelteindex c50a23427..cd051464c 100644--- a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte@@ -67,7 +67,6 @@import { globalVariablesToMap } from '#lib/utils/template-load';import {planProjectWorkspaceFileCreate,- planProjectWorkspaceFileMove,planProjectWorkspaceFileRename,validateProjectWorkspaceFileName} from '../components/project-workspace-utils';@@ -75,6 +74,7 @@applyWorkspaceFileChangesForDisplay,buildWorkspaceMultipartUpdate,isWorkspaceFileSelectionUnder,+ planWorkspaceFileMove,workspaceFileBasename,workspaceFileLanguage,remapWorkspaceFileRecord,@@ -82,7 +82,7 @@removeWorkspaceFileRecord,readWorkspaceTextUpload,workspaceReadOnlyMessage,- type WorkspaceFileEntry+ type WorkspaceDisplayEntry} from '#lib/utils/workspace-files';import { composeTreeSplitProps, extractComposeYamlName } from '#lib/utils/compose-flow';@@ -936,7 +936,7 @@if (targetFile.content !== undefined) {if (kind === 'workspace') {- const workspaceTarget = targetFile as WorkspaceFileEntry;+ const workspaceTarget = targetFile as WorkspaceDisplayEntry;updateLoadedProjectWorkspaceFile(relativePath, workspaceTarget.content ?? '');return {path: workspaceTarget.path,@@ -1231,7 +1231,7 @@function moveProjectWorkspaceFile(relativePath: string, newParentPath: string) {const entry = projectWorkspaceEntries.find((file) => file.relativePath === relativePath);- const newPath = planProjectWorkspaceFileMove(entry, projectWorkspacePaths, relativePath, newParentPath);+ const newPath = planWorkspaceFileMove(entry, projectWorkspacePaths, relativePath, newParentPath);if (!newPath) return;projectWorkspaceChanges = [...projectWorkspaceChanges, { operation: 'move', relativePath, newParentPath }];remapProjectWorkspaceState(relativePath, newPath);diff --git a/frontend/src/routes/(app)/projects/components/project-workspace-utils.ts b/frontend/src/routes/(app)/projects/components/project-workspace-utils.tsindex fe39447e1..e3727524b 100644--- a/frontend/src/routes/(app)/projects/components/project-workspace-utils.ts+++ b/frontend/src/routes/(app)/projects/components/project-workspace-utils.ts@@ -3,13 +3,11 @@ import { m } from '#lib/paraglide/messages';import {joinWorkspaceFilePath,validateWorkspaceFileName,- workspaceFileBasename,workspaceFileParentPath,- workspaceFilePathMatches,- type WorkspaceFileEntry+ type WorkspaceDisplayEntry} from '#lib/utils/workspace-files';-export type ProjectWorkspaceEntry = WorkspaceFileEntry;+export type ProjectWorkspaceEntry = WorkspaceDisplayEntry;const reservedRootNames = new Set(['.env',@@ -77,23 +75,3 @@ export function planProjectWorkspaceFileRename(}return { newName: normalizedName, newPath };}--export function planProjectWorkspaceFileMove(- entry: Pick<WorkspaceFileEntry, 'isDirectory'> | undefined,- existingPaths: ReadonlySet<string>,- relativePath: string,- newParentPath: string-): string | null {- if (!entry) return null;- if (newParentPath === workspaceFileParentPath(relativePath)) return null;- if (entry.isDirectory && newParentPath && workspaceFilePathMatches(newParentPath, relativePath)) {- toast.error(m.workspace_file_invalid_move_destination());- return null;- }- const newPath = joinWorkspaceFilePath(newParentPath, workspaceFileBasename(relativePath));- if (newPath !== relativePath && existingPaths.has(newPath)) {- toast.error(m.workspace_file_duplicate_name());- return null;- }- return newPath;-}diff --git a/frontend/src/routes/(app)/projects/new/+page.svelte b/frontend/src/routes/(app)/projects/new/+page.svelteindex ab6fd99b6..c089d80b2 100644--- a/frontend/src/routes/(app)/projects/new/+page.svelte+++ b/frontend/src/routes/(app)/projects/new/+page.svelte@@ -24,7 +24,6 @@import DockerRunConverterDialog from '#lib/components/compose/docker-run-converter-dialog.svelte';import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast';import { globalVariablesToMap } from '#lib/utils/template-load';- import type { ProjectWorkspaceFileDraft } from '#lib/types/project-workspace';import type { ProjectTag } from '#lib/types/swarm';import ProjectTagEditor from '#lib/components/project-tag-editor.svelte';import { createQuery } from '@tanstack/svelte-query';@@ -32,22 +31,11 @@import settingsStore from '#lib/stores/config-store';import {planProjectWorkspaceFileCreate,- planProjectWorkspaceFileMove,planProjectWorkspaceFileRename,validateProjectWorkspaceFileName} from '../components/project-workspace-utils';- import {- isWorkspaceFileSelectionUnder,- workspaceFileBasename,- workspaceFileLanguage,- workspaceFilePathMatches,- remapWorkspaceFilePath,- remapWorkspaceFileRecord,- remapSelectedWorkspaceFileKey,- removeWorkspaceFileRecord,- readWorkspaceTextUpload,- type WorkspaceFileEntry- } from '#lib/utils/workspace-files';+ import { planWorkspaceFileMove, workspaceFileBasename, workspaceFileLanguage } from '#lib/utils/workspace-files';+ import { WorkspaceDraftState } from '#lib/components/workspace-editor/workspace-draft-state.svelte';import {composeTreeSplitProps,createComposeEditorSchema,@@ -98,18 +86,22 @@let composeOpen = $state(true);let envOpen = $state(true);let layoutMode = $state<'classic' | 'tree'>('classic');- let selectedEditorFile = $state<'compose' | 'env' | string>('compose');let treePaneWidth = $state(280);- let newProjectWorkspaceFiles = $state<ProjectWorkspaceFileDraft[]>([]);+ const workspaceDraft = new WorkspaceDraftState({+ fallbackTab: 'compose',+ initialOpenTabs: ['compose'],+ initialSelection: 'compose',+ isFixedTab: (key) => key === 'compose' || key === 'env',+ planCreate: planProjectWorkspaceFileCreate,+ planRename: planProjectWorkspaceFileRename,+ planMove: planWorkspaceFileMove+ });let newProjectTags = $state<ProjectTag[]>([]);const projectTagsQuery = createQuery(() => ({queryKey: queryKeys.projects.tags(currentEnvId),queryFn: () => projectService.getProjectTagsForEnvironment(currentEnvId)}));const availableProjectTags = $derived(projectTagsQuery.data ?? []);- let newProjectWorkspaceContents = $state<Record<string, string>>({});- let newProjectWorkspaceHasErrors = $state<Record<string, boolean>>({});- let newProjectWorkspaceValidationReady = $state<Record<string, boolean>>({});let validation = $state({composeHasErrors: false,envHasErrors: false,@@ -118,36 +110,16 @@});const globalVariableMap = $derived(globalVariablesToMap(data.globalVariables));- const newProjectWorkspaceEntries = $derived.by<WorkspaceFileEntry[]>(() =>- newProjectWorkspaceFiles.map((file) => ({- path: file.relativePath,- relativePath: file.relativePath,- name: workspaceFileBasename(file.relativePath),- isDirectory: !!file.isDirectory,- size: file.isDirectory ? 0 : (newProjectWorkspaceContents[file.relativePath]?.length ?? 0),- content: file.isDirectory ? undefined : (newProjectWorkspaceContents[file.relativePath] ?? ''),- pending: true- }))- );- const newProjectWorkspacePaths = $derived.by(() => new Set(newProjectWorkspaceEntries.map((file) => file.relativePath)));+ const newProjectWorkspaceEntries = $derived(workspaceDraft.entries);const newProjectWorkspaceLeadingRows = [{ key: 'compose', label: 'compose.yaml', iconClass: 'text-blue-500', locked: true },{ key: 'env', label: '.env', iconClass: 'text-green-500', locked: true }];- let openProjectTabs = $state<string[]>(['compose']);let treeOutlineOpen = $state(false);let treeDiffOpen = $state(false);let treeCommandPaletteOpen = $state(false);- const openTabs = $derived.by(() => {- const valid = openProjectTabs.filter((key) => {- if (key === 'compose' || key === 'env') return true;- if (!key.startsWith('file:')) return false;- const entry = newProjectWorkspaceEntries.find((file) => file.relativePath === key.slice(5));- return !!entry && !entry.isDirectory;- });- return valid.length > 0 ? valid : ['compose'];- });- const activeProjectTab = $derived(openTabs.includes(selectedEditorFile) ? selectedEditorFile : (openTabs[0] ?? 'compose'));+ const openTabs = $derived(workspaceDraft.validOpenTabs);+ const activeProjectTab = $derived(workspaceDraft.activeTab);const projectTabs = $derived(openTabs.map((key) => ({key,@@ -158,26 +130,6 @@})));- function isNewProjectDirectoryKey(key: string): boolean {- if (!key.startsWith('file:')) return false;- return newProjectWorkspaceEntries.find((file) => file.relativePath === key.slice(5))?.isDirectory === true;- }-- function openEditorFileTab(key: string) {- if (!isNewProjectDirectoryKey(key) && !openProjectTabs.includes(key)) {- openProjectTabs = [...openProjectTabs, key];- }- selectedEditorFile = key;- }-- function closeEditorFileTab(key: string) {- const index = openTabs.indexOf(key);- const remaining = openTabs.filter((tab) => tab !== key);- openProjectTabs = openProjectTabs.filter((tab) => tab !== key);- if (selectedEditorFile === key) {- selectedEditorFile = remaining[Math.min(Math.max(index - 1, 0), remaining.length - 1)] ?? 'compose';- }- }const validationState = $derived(getTemplateEditorValidationState(validation.composeValidationReady,@@ -225,7 +177,7 @@validate: () => validateTemplateEditorForm(validationState, form.validate),setLoading: (value) => (ui.saving = value),submit: ({ name, composeContent, envContent }) =>- projectService.createProject(name, composeContent, envContent, buildNewProjectWorkspacePayload(), newProjectTags),+ projectService.createProject(name, composeContent, envContent, workspaceDraft.toDrafts(), newProjectTags),failureMessage: (name) => m.common_create_failed({ resource: `${m.resource_project()} "${name}"` }),onSuccess: async (project, { name }) => {toast.success(@@ -258,94 +210,6 @@hasEditorErrors: () => hasEditorErrors});- function ensureNewProjectWorkspaceUiState(relativePath: string) {- if (newProjectWorkspaceHasErrors[relativePath] === undefined) {- newProjectWorkspaceHasErrors = {- ...newProjectWorkspaceHasErrors,- [relativePath]: false- };- }- if (newProjectWorkspaceValidationReady[relativePath] === undefined) {- newProjectWorkspaceValidationReady = {- ...newProjectWorkspaceValidationReady,- [relativePath]: true- };- }- }-- function createNewProjectWorkspaceFile(parentPath: string, name: string, content = '') {- const relativePath = planProjectWorkspaceFileCreate(newProjectWorkspacePaths, parentPath, name);- if (!relativePath) return;- newProjectWorkspaceFiles = [...newProjectWorkspaceFiles, { relativePath, isDirectory: false }];- newProjectWorkspaceContents = { ...newProjectWorkspaceContents, [relativePath]: content };- ensureNewProjectWorkspaceUiState(relativePath);- openEditorFileTab(`file:${relativePath}`);- }-- async function uploadNewProjectWorkspaceFiles(parentPath: string, files: File[]): Promise<string | void> {- const file = files[0];- if (!file) return m.workspace_upload_file_required();- const result = await readWorkspaceTextUpload(file, projectWorkspaceMaxFileSizeMb);- if (result.error) return result.error;- createNewProjectWorkspaceFile(parentPath, file.name, result.content ?? '');- }-- function createNewProjectFolder(parentPath: string, name: string) {- const relativePath = planProjectWorkspaceFileCreate(newProjectWorkspacePaths, parentPath, name);- if (!relativePath) return;- newProjectWorkspaceFiles = [...newProjectWorkspaceFiles, { relativePath, isDirectory: true }];- selectedEditorFile = `file:${relativePath}`;- }-- function applyNewProjectWorkspacePathChange(oldPath: string, newPath: string) {- newProjectWorkspaceFiles = newProjectWorkspaceFiles.map((file) => ({- ...file,- relativePath: remapWorkspaceFilePath(file.relativePath, oldPath, newPath)- }));- newProjectWorkspaceContents = remapWorkspaceFileRecord(newProjectWorkspaceContents, oldPath, newPath);- newProjectWorkspaceHasErrors = remapWorkspaceFileRecord(newProjectWorkspaceHasErrors, oldPath, newPath);- newProjectWorkspaceValidationReady = remapWorkspaceFileRecord(newProjectWorkspaceValidationReady, oldPath, newPath);- openProjectTabs = openProjectTabs.map((tab) => remapSelectedWorkspaceFileKey(tab, oldPath, newPath) ?? tab);- const remappedSelection = remapSelectedWorkspaceFileKey(selectedEditorFile, oldPath, newPath);- if (remappedSelection) {- selectedEditorFile = remappedSelection;- }- }-- function renameNewProjectWorkspaceFile(relativePath: string, newName: string) {- const plan = planProjectWorkspaceFileRename(newProjectWorkspacePaths, relativePath, newName);- if (!plan) return;- applyNewProjectWorkspacePathChange(relativePath, plan.newPath);- }-- function moveNewProjectWorkspaceFile(relativePath: string, newParentPath: string) {- const entry = newProjectWorkspaceEntries.find((file) => file.relativePath === relativePath);- const newPath = planProjectWorkspaceFileMove(entry, newProjectWorkspacePaths, relativePath, newParentPath);- if (!newPath) return;- applyNewProjectWorkspacePathChange(relativePath, newPath);- }-- function deleteNewProjectWorkspaceFile(relativePath: string) {- newProjectWorkspaceFiles = newProjectWorkspaceFiles.filter(- (file) => !workspaceFilePathMatches(file.relativePath, relativePath)- );- newProjectWorkspaceContents = removeWorkspaceFileRecord(newProjectWorkspaceContents, relativePath);- newProjectWorkspaceHasErrors = removeWorkspaceFileRecord(newProjectWorkspaceHasErrors, relativePath);- newProjectWorkspaceValidationReady = removeWorkspaceFileRecord(newProjectWorkspaceValidationReady, relativePath);- openProjectTabs = openProjectTabs.filter((tab) => !isWorkspaceFileSelectionUnder(tab, relativePath));- if (isWorkspaceFileSelectionUnder(selectedEditorFile, relativePath)) {- selectedEditorFile = openTabs[0] ?? 'compose';- }- }-- function buildNewProjectWorkspacePayload(): ProjectWorkspaceFileDraft[] {- return newProjectWorkspaceFiles.map((file) => ({- relativePath: file.relativePath,- isDirectory: !!file.isDirectory,- content: file.isDirectory ? undefined : (newProjectWorkspaceContents[file.relativePath] ?? '')- }));- }-function composePanelProps() {return {title: m.compose_compose_file_title(),@@ -391,7 +255,7 @@variant="inline"error={$inputs.name.error ?? undefined}originalValue=""- placeholder={m.compose_project_name_placeholder?.() || 'Enter project name...'}+ placeholder={m.compose_project_name_placeholder()}canEdit={!ui.saving && !ui.isLoadingTemplateContent && !composeYamlName}disabledMessage={composeYamlName ? m.compose_project_name_defined_in_yaml() : undefined}class="hidden sm:block"@@ -476,7 +340,7 @@aria-label={m.project_view_description()}onCheckedChange={(checked) => {layoutMode = checked ? 'tree' : 'classic';- openEditorFileTab('compose');+ workspaceDraft.openTab('compose');}}/></div>@@ -495,16 +359,16 @@<WorkspaceFileTreePanelleadingRows={newProjectWorkspaceLeadingRows}entries={newProjectWorkspaceEntries}- selectedFile={selectedEditorFile}+ selectedFile={workspaceDraft.selectedKey}disabled={ui.saving || ui.isLoadingTemplateContent}- onSelect={openEditorFileTab}- onCreateFile={createNewProjectWorkspaceFile}- onCreateFolder={createNewProjectFolder}- onUpload={uploadNewProjectWorkspaceFiles}+ onSelect={workspaceDraft.openTab}+ onCreateFile={workspaceDraft.createFile}+ onCreateFolder={workspaceDraft.createFolder}+ onUpload={(parentPath, files) => workspaceDraft.uploadFile(parentPath, files, projectWorkspaceMaxFileSizeMb)}validateName={(name, parentPath) => validateProjectWorkspaceFileName(name, parentPath)}- onRename={renameNewProjectWorkspaceFile}- onMove={moveNewProjectWorkspaceFile}- onDelete={deleteNewProjectWorkspaceFile}+ onRename={workspaceDraft.rename}+ onMove={workspaceDraft.move}+ onDelete={workspaceDraft.remove}/>{/snippet}@@ -513,8 +377,8 @@<EditorTabStriptabs={projectTabs}activeKey={activeProjectTab}- onSelect={openEditorFileTab}- onClose={closeEditorFileTab}+ onSelect={workspaceDraft.openTab}+ onClose={workspaceDraft.closeTab}>{#snippet actions()}<ComposeFileEditorPanel@@ -563,9 +427,9 @@title={relativePath}language={workspaceFileLanguage(relativePath)}validationMode="none"- bind:value={newProjectWorkspaceContents[relativePath]}- bind:hasErrors={newProjectWorkspaceHasErrors[relativePath]}- bind:validationReady={newProjectWorkspaceValidationReady[relativePath]}+ bind:value={workspaceDraft.contents[relativePath]}+ bind:hasErrors={workspaceDraft.hasErrors[relativePath]}+ bind:validationReady={workspaceDraft.validationReady[relativePath]}fileId={`projects:new:file:${relativePath}`}originalValue=""enableDiff={true}diff --git a/frontend/src/routes/(app)/projects/projects-table.actions.ts b/frontend/src/routes/(app)/projects/projects-table.actions.tsindex 84ba9f182..6ee2336a4 100644--- a/frontend/src/routes/(app)/projects/projects-table.actions.ts+++ b/frontend/src/routes/(app)/projects/projects-table.actions.ts@@ -10,6 +10,7 @@ import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toaimport type { TableActionConfig, TableBulkActionConfig } from '#lib/utils/table-action-types';import { toast } from 'svelte-sonner';import type { ActionStatus } from './projects-table.helpers';+import { bulkConfirmAndRun } from '#lib/utils/bulk-actions';type BulkLoadingState = {up: boolean;@@ -114,7 +115,7 @@ export function createProjectActions({await refreshProjects();}});- } catch (error) {+ } catch {toast.error(m.common_action_failed());actionStatus[id] = '';}@@ -177,36 +178,23 @@ export function createProjectActions({async function runBulkAction(ids: string[], config: BulkActionConfig): Promise<void> {if (!ids || ids.length === 0) return;- openConfirmDialog({+ bulkConfirmAndRun({+ ids,title: config.title(ids.length),message: config.message(ids.length),- confirm: {- label: config.label,- destructive: config.destructive ?? false,- action: async () => {- isBulkLoading[config.loadingKey] = true;-- try {- const results = await Promise.allSettled(ids.map((id) => config.run(id)));-- const successCount = results.filter((result) => result.status === 'fulfilled').length;- const failureCount = results.length - successCount;-- if (successCount === ids.length) {- toast.success(config.success(successCount));- } else if (successCount > 0) {- toast.warning(config.partial(successCount, ids.length, failureCount));- } else {- toast.error(config.failure());- }-- await refreshProjects(getRequestOptions());- setSelectedIds([]);- } finally {- isBulkLoading[config.loadingKey] = false;- }- }- }+ confirmLabel: config.label,+ destructive: config.destructive ?? false,+ run: (id) => config.run(id),+ messages: {+ success: config.success,+ partial: config.partial,+ failure: config.failure+ },+ setLoading: (loading) => {+ isBulkLoading[config.loadingKey] = loading;+ },+ onComplete: () => refreshProjects(getRequestOptions()),+ clearSelection: () => setSelectedIds([])});}diff --git a/frontend/src/routes/(app)/settings/+layout.svelte b/frontend/src/routes/(app)/settings/+layout.svelteindex 9e10c2739..5979f19ba 100644--- a/frontend/src/routes/(app)/settings/+layout.svelte+++ b/frontend/src/routes/(app)/settings/+layout.svelte@@ -55,8 +55,12 @@// Set context so forms can update the header statesetContext('settingsFormState', formState);- // Reset form state before navigating to a new page- beforeNavigate(() => {+ // Query-only navigation keeps the same form mounted, so preserve its actions.+ beforeNavigate(({ from, to }) => {+ if (from?.url.pathname === to?.url.pathname) {+ return;+ }+formState.hasChanges = false;formState.isLoading = false;formState.saveFunction = null;diff --git a/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte b/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelteindex a4de1ff26..0d1261946 100644--- a/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte+++ b/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte@@ -5,10 +5,7 @@import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';import { CopyButton } from '#lib/components/ui/copy-button';import { toast } from 'svelte-sonner';- import { openConfirmDialog } from '#lib/components/confirm-dialog';import { Badge } from '#lib/components/ui/badge';- import { handleApiResultWithCallbacks } from '#lib/utils/api';- import { tryCatch } from '#lib/utils/api';import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared';import type { ApiKey } from '#lib/types/auth';import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '#lib/components/arcane-table';@@ -18,6 +15,7 @@import * as m from '#lib/paraglide/messages.js';import { ApiKeyIcon, TrashIcon, EditIcon } from '#lib/icons';import IfPermitted from '#lib/components/if-permitted.svelte';+ import { bulkConfirmAndRun, confirmAndRun } from '#lib/utils/bulk-actions';let {apiKeys = $bindable(),@@ -66,7 +64,7 @@.map((apiKey) => apiKey.id));- async function handleDeleteSelected() {+ function handleDeleteSelected() {if (selectedIds.length === 0) return;if (selectedDeletableApiKeyIds.length === 0) {toast.info(m.api_key_bulk_delete_static_only());@@ -75,71 +73,43 @@if (selectedStaticApiKeyCount > 0) {toast.info(m.api_key_bulk_delete_static_skipped({ count: selectedStaticApiKeyCount }));}+ const ids = [...selectedDeletableApiKeyIds];- openConfirmDialog({- title: m.api_key_delete_selected_title({ count: selectedDeletableApiKeyIds.length }),- message: m.api_key_delete_selected_message({ count: selectedDeletableApiKeyIds.length }),- confirm: {- label: m.common_delete(),- destructive: true,- action: async () => {- isLoading.removing = true;- let successCount = 0;- let failureCount = 0;-- for (const apiKeyId of selectedDeletableApiKeyIds) {- const result = await tryCatch(apiKeyService.delete(apiKeyId));- handleApiResultWithCallbacks({- result,- message: m.api_key_delete_failed({ name: apiKeyId }),- setLoadingState: () => {},- onSuccess: () => {- successCount++;- }- });-- if (result.error) {- failureCount++;- }- }-- isLoading.removing = false;-- if (successCount > 0) {- toast.success(m.api_key_bulk_delete_success({ count: successCount }));- await onApiKeysChanged();- }-- if (failureCount > 0) {- toast.error(m.api_key_bulk_delete_failed({ count: failureCount }));- }-- selectedIds = [];- }- }+ bulkConfirmAndRun({+ ids,+ title: m.api_key_delete_selected_title({ count: ids.length }),+ message: m.api_key_delete_selected_message({ count: ids.length }),+ confirmLabel: m.common_delete(),+ destructive: true,+ run: (apiKeyId) => apiKeyService.delete(apiKeyId),+ messages: {+ success: (count) => m.api_key_bulk_delete_success({ count }),+ partial: (success, total, failed) =>+ m.common_bulk_delete_partial({ success, total, failed, resource: m.api_key_page_title() }),+ failure: () => m.api_key_bulk_delete_failed({ count: ids.length })+ },+ setLoading: (loading) => (isLoading.removing = loading),+ onComplete: async ({ success }) => {+ if (success > 0) await onApiKeysChanged();+ },+ clearSelection: () => (selectedIds = []),+ sequential: true});}- async function handleDeleteApiKey(apiKeyId: string, name: string) {+ function handleDeleteApiKey(apiKeyId: string, name: string) {const safeName = name?.trim() || m.common_unknown();- openConfirmDialog({+ confirmAndRun({title: m.api_key_delete_title({ name: safeName }),message: m.api_key_delete_message({ name: safeName }),- confirm: {- label: m.common_delete(),- destructive: true,- action: async () => {- isLoading.removing = true;- handleApiResultWithCallbacks({- result: await tryCatch(apiKeyService.delete(apiKeyId)),- message: m.api_key_delete_failed({ name: safeName }),- setLoadingState: (value) => (isLoading.removing = value),- onSuccess: async () => {- toast.success(m.api_key_delete_success({ name: safeName }));- await onApiKeysChanged();- }- });- }+ confirmLabel: m.common_delete(),+ destructive: true,+ setLoading: (loading) => (isLoading.removing = loading),+ run: () => apiKeyService.delete(apiKeyId),+ failureMessage: m.api_key_delete_failed({ name: safeName }),+ onSuccess: async () => {+ toast.success(m.api_key_delete_success({ name: safeName }));+ await onApiKeysChanged();}});}diff --git a/frontend/src/routes/(app)/settings/authentication/federated-credential-table.svelte b/frontend/src/routes/(app)/settings/authentication/federated-credential-table.svelteindex f944e104a..dd30707ca 100644--- a/frontend/src/routes/(app)/settings/authentication/federated-credential-table.svelte+++ b/frontend/src/routes/(app)/settings/authentication/federated-credential-table.svelte@@ -4,9 +4,6 @@import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';import { Badge } from '#lib/components/ui/badge';import { toast } from 'svelte-sonner';- import { openConfirmDialog } from '#lib/components/confirm-dialog';- import { handleApiResultWithCallbacks } from '#lib/utils/api';- import { tryCatch } from '#lib/utils/api';import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared';import type { FederatedCredential } from '#lib/types/auth';import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '#lib/components/arcane-table';@@ -16,6 +13,7 @@import * as m from '#lib/paraglide/messages.js';import { LockIcon, TrashIcon, EditIcon } from '#lib/icons';import { isGlobalAdmin } from '#lib/utils/auth';+ import { bulkConfirmAndRun, confirmAndRun } from '#lib/utils/bulk-actions';let {federatedCredentials = $bindable(),@@ -57,73 +55,45 @@return `${role} / ${getScope(credential)}`;}- async function handleDeleteSelected() {+ function handleDeleteSelected() {if (selectedIds.length === 0) return;-- openConfirmDialog({- title: m.federated_credential_delete_selected_title({ count: selectedIds.length }),- message: m.federated_credential_delete_selected_message({ count: selectedIds.length }),- confirm: {- label: m.common_delete(),- destructive: true,- action: async () => {- isLoading.removing = true;- let successCount = 0;- let failureCount = 0;-- for (const credentialId of selectedIds) {- const result = await tryCatch(federatedCredentialService.delete(credentialId));- handleApiResultWithCallbacks({- result,- message: m.federated_credential_delete_failed({ name: credentialId }),- setLoadingState: () => {},- onSuccess: () => {- successCount++;- }- });-- if (result.error) {- failureCount++;- }- }-- isLoading.removing = false;-- if (successCount > 0) {- toast.success(m.federated_credential_bulk_delete_success({ count: successCount }));- await onFederatedCredentialsChanged();- }-- if (failureCount > 0) {- toast.error(m.federated_credential_bulk_delete_failed({ count: failureCount }));- }-- selectedIds = [];- }- }+ const ids = [...selectedIds];++ bulkConfirmAndRun({+ ids,+ title: m.federated_credential_delete_selected_title({ count: ids.length }),+ message: m.federated_credential_delete_selected_message({ count: ids.length }),+ confirmLabel: m.common_delete(),+ destructive: true,+ run: (credentialId) => federatedCredentialService.delete(credentialId),+ messages: {+ success: (count) => m.federated_credential_bulk_delete_success({ count }),+ partial: (success, total, failed) =>+ m.common_bulk_delete_partial({ success, total, failed, resource: m.federated_credential_page_title() }),+ failure: () => m.federated_credential_bulk_delete_failed({ count: ids.length })+ },+ setLoading: (loading) => (isLoading.removing = loading),+ onComplete: async ({ success }) => {+ if (success > 0) await onFederatedCredentialsChanged();+ },+ clearSelection: () => (selectedIds = []),+ sequential: true});}- async function handleDeleteFederatedCredential(credentialId: string, name: string) {+ function handleDeleteFederatedCredential(credentialId: string, name: string) {const safeName = name?.trim() || m.common_unknown();- openConfirmDialog({+ confirmAndRun({title: m.federated_credential_delete_title({ name: safeName }),message: m.federated_credential_delete_message({ name: safeName }),- confirm: {- label: m.common_delete(),- destructive: true,- action: async () => {- isLoading.removing = true;- handleApiResultWithCallbacks({- result: await tryCatch(federatedCredentialService.delete(credentialId)),- message: m.federated_credential_delete_failed({ name: safeName }),- setLoadingState: (value) => (isLoading.removing = value),- onSuccess: async () => {- toast.success(m.federated_credential_delete_success({ name: safeName }));- await onFederatedCredentialsChanged();- }- });- }+ confirmLabel: m.common_delete(),+ destructive: true,+ setLoading: (loading) => (isLoading.removing = loading),+ run: () => federatedCredentialService.delete(credentialId),+ failureMessage: m.federated_credential_delete_failed({ name: safeName }),+ onSuccess: async () => {+ toast.success(m.federated_credential_delete_success({ name: safeName }));+ await onFederatedCredentialsChanged();}});}diff --git a/frontend/src/routes/(app)/settings/backups/system-backup-table.svelte b/frontend/src/routes/(app)/settings/backups/system-backup-table.svelteindex 4549b8c95..fcbaa89f5 100644--- a/frontend/src/routes/(app)/settings/backups/system-backup-table.svelte+++ b/frontend/src/routes/(app)/settings/backups/system-backup-table.svelte@@ -40,7 +40,7 @@{ accessorKey: 'trigger', title: m.volume_backup_trigger(), sortable: true, cell: TriggerCell },{ accessorKey: 'destination', title: m.backups_destination_label(), sortable: true, cell: DestinationCell },{ accessorKey: 'size', title: m.common_size(), sortable: true, cell: SizeCell },- { accessorKey: 'createdAt', title: m.common_created(), sortable: true, cell: CreatedCell },+ { accessorKey: 'createdAt', title: m.common_created(), sortable: true, cellComponent: CreatedAtCell },{ accessorKey: 'error', title: m.common_error(), sortable: false, cell: ErrorCell }] satisfies ColumnSpec<SystemBackupRun>[];const mobileFields = [@@ -56,7 +56,6 @@{#snippet TriggerCell({ item }: { item: SystemBackupRun })}<BackupTriggerCell trigger={item.trigger} />{/snippet}{#snippet DestinationCell({ item }: { item: SystemBackupRun })}<BackupDestinationCell {item} />{/snippet}{#snippet SizeCell({ item }: { item: SystemBackupRun })}<BackupSizeCell size={item.size} />{/snippet}-{#snippet CreatedCell({ item }: { item: SystemBackupRun })}<CreatedAtCell value={item.createdAt} />{/snippet}{#snippet ErrorCell({ item }: { item: SystemBackupRun })}<span class="max-w-72 truncate text-red-500">{item.error || '-'}</span>{/snippet}diff --git a/frontend/src/routes/(app)/settings/notifications/+page.svelte b/frontend/src/routes/(app)/settings/notifications/+page.svelteindex e03c0fd36..ee9d0bd0e 100644--- a/frontend/src/routes/(app)/settings/notifications/+page.svelte+++ b/frontend/src/routes/(app)/settings/notifications/+page.svelte@@ -9,47 +9,21 @@import { m } from '#lib/paraglide/messages';import { useUrlTab } from '#lib/hooks/use-url-tab.svelte';import { notificationService } from '#lib/services/notification-service';- import type { NotificationSettings } from '#lib/types/notifications';- import {- type DiscordFormValues,- type EmailFormValues,- type TelegramFormValues,- type SignalFormValues,- type SlackFormValues,- type NtfyFormValues,- type PushoverFormValues,- type GotifyFormValues,- type MatrixFormValues,- type GoogleChatFormValues,- type GenericFormValues,- type NotificationProviderKey,- NOTIFICATION_PROVIDER_KEYS,- discordSettingsToFormValues,- emailSettingsToFormValues,- telegramSettingsToFormValues,- signalSettingsToFormValues,- slackSettingsToFormValues,- ntfySettingsToFormValues,- pushoverSettingsToFormValues,- gotifySettingsToFormValues,- matrixSettingsToFormValues,- googleChatSettingsToFormValues,- genericSettingsToFormValues,- discordFormValuesToSettings,- emailFormValuesToSettings,- telegramFormValuesToSettings,- signalFormValuesToSettings,- slackFormValuesToSettings,- ntfyFormValuesToSettings,- pushoverFormValuesToSettings,- gotifyFormValuesToSettings,- matrixFormValuesToSettings,- googleChatFormValuesToSettings,- genericFormValuesToSettings- } from '#lib/types/notifications';+ import { type NotificationProviderKey, NOTIFICATION_PROVIDER_KEYS } from '#lib/types/notifications';import { NotificationsIcon } from '#lib/icons';import { TabBar, type TabItem } from '#lib/components/tab-bar';import { BuiltInProviderForm } from './providers';+ import {+ cloneNotificationProviderFormState,+ createNotificationProviderFormState,+ createNotificationSettingsByProvider,+ getNotificationProviderDefinition,+ notificationProviderFormValuesToSettings,+ type NotificationProviderFormState,+ type NotificationSettingsByProvider,+ updateNotificationProviderFormState+ } from '#lib/utils/notification-providers';+ import { extractApiErrorMessage } from '#lib/utils/api';let { data } = $props();@@ -63,109 +37,37 @@defaultTab: () => 'email'});const providerTab = $derived(urlTab.value);- // Providers whose display name is not just a capitalised key.- const providerTabLabels: Partial<Record<NotificationProviderKey, string>> = {- googlechat: 'Google Chat'- };const providerTabItems = NOTIFICATION_PROVIDER_KEYS.map((provider) =>({value: provider,- label: providerTabLabels[provider] ?? provider.charAt(0).toUpperCase() + provider.slice(1)+ label: getNotificationProviderDefinition(provider).label()}) satisfies TabItem);const isReadOnly = $derived.by(() => $settingsStore.uiConfigDisabled);- // Settings form context- let formState: any = null;- try {- formState = getContext('settingsFormState') as any;- } catch {- // Context not available (shouldn't happen in settings routes)- }-- // Provider form references for validation- let emailFormRef: ReturnType<typeof BuiltInProviderForm>;- let discordFormRef: ReturnType<typeof BuiltInProviderForm>;- let telegramFormRef: ReturnType<typeof BuiltInProviderForm>;- let signalFormRef: ReturnType<typeof BuiltInProviderForm>;- let slackFormRef: ReturnType<typeof BuiltInProviderForm>;- let ntfyFormRef: ReturnType<typeof BuiltInProviderForm>;- let pushoverFormRef: ReturnType<typeof BuiltInProviderForm>;- let gotifyFormRef: ReturnType<typeof BuiltInProviderForm>;- let matrixFormRef: ReturnType<typeof BuiltInProviderForm>;- let googlechatFormRef: ReturnType<typeof BuiltInProviderForm>;- let genericFormRef: ReturnType<typeof BuiltInProviderForm>;-- // Saved settings from server (used to detect if settings exist)- let savedSettings = $state<Record<NotificationProviderKey, NotificationSettings | null>>({- email: null,- discord: null,- telegram: null,- signal: null,- slack: null,- ntfy: null,- pushover: null,- gotify: null,- matrix: null,- googlechat: null,- generic: null- });-- // Current form values - these are what the user edits- let emailValues = $state<EmailFormValues>(emailSettingsToFormValues());- let discordValues = $state<DiscordFormValues>(discordSettingsToFormValues());- let telegramValues = $state<TelegramFormValues>(telegramSettingsToFormValues());- let signalValues = $state<SignalFormValues>(signalSettingsToFormValues());- let slackValues = $state<SlackFormValues>(slackSettingsToFormValues());- let ntfyValues = $state<NtfyFormValues>(ntfySettingsToFormValues());- let pushoverValues = $state<PushoverFormValues>(pushoverSettingsToFormValues());- let gotifyValues = $state<GotifyFormValues>(gotifySettingsToFormValues());- let matrixValues = $state<MatrixFormValues>(matrixSettingsToFormValues());- let googlechatValues = $state<GoogleChatFormValues>(googleChatSettingsToFormValues());- let genericValues = $state<GenericFormValues>(genericSettingsToFormValues());-- // Baseline values - what was last saved (for change detection)- let emailBaseline = $state<EmailFormValues>(emailSettingsToFormValues());- let discordBaseline = $state<DiscordFormValues>(discordSettingsToFormValues());- let telegramBaseline = $state<TelegramFormValues>(telegramSettingsToFormValues());- let signalBaseline = $state<SignalFormValues>(signalSettingsToFormValues());- let slackBaseline = $state<SlackFormValues>(slackSettingsToFormValues());- let ntfyBaseline = $state<NtfyFormValues>(ntfySettingsToFormValues());- let pushoverBaseline = $state<PushoverFormValues>(pushoverSettingsToFormValues());- let gotifyBaseline = $state<GotifyFormValues>(gotifySettingsToFormValues());- let matrixBaseline = $state<MatrixFormValues>(matrixSettingsToFormValues());- let googlechatBaseline = $state<GoogleChatFormValues>(googleChatSettingsToFormValues());- let genericBaseline = $state<GenericFormValues>(genericSettingsToFormValues());-- // Change detection- const emailHasChanges = $derived(JSON.stringify(emailValues) !== JSON.stringify(emailBaseline));- const discordHasChanges = $derived(JSON.stringify(discordValues) !== JSON.stringify(discordBaseline));- const telegramHasChanges = $derived(JSON.stringify(telegramValues) !== JSON.stringify(telegramBaseline));- const signalHasChanges = $derived(JSON.stringify(signalValues) !== JSON.stringify(signalBaseline));- const slackHasChanges = $derived(JSON.stringify(slackValues) !== JSON.stringify(slackBaseline));- const ntfyHasChanges = $derived(JSON.stringify(ntfyValues) !== JSON.stringify(ntfyBaseline));- const pushoverHasChanges = $derived(JSON.stringify(pushoverValues) !== JSON.stringify(pushoverBaseline));- const gotifyHasChanges = $derived(JSON.stringify(gotifyValues) !== JSON.stringify(gotifyBaseline));- const matrixHasChanges = $derived(JSON.stringify(matrixValues) !== JSON.stringify(matrixBaseline));- const googlechatHasChanges = $derived(JSON.stringify(googlechatValues) !== JSON.stringify(googlechatBaseline));- const genericHasChanges = $derived(JSON.stringify(genericValues) !== JSON.stringify(genericBaseline));- const hasChanges = $derived(- emailHasChanges ||- discordHasChanges ||- telegramHasChanges ||- signalHasChanges ||- slackHasChanges ||- ntfyHasChanges ||- pushoverHasChanges ||- gotifyHasChanges ||- matrixHasChanges ||- googlechatHasChanges ||- genericHasChanges+ type SettingsFormState = {+ hasChanges: boolean;+ isLoading: boolean;+ saveFunction: (() => Promise<void>) | null;+ resetFunction: (() => void) | null;+ };+ type ProviderFormRef = { isValid: () => boolean };++ const formState = getContext<SettingsFormState | undefined>('settingsFormState');+ let providerFormRefs = $state<Partial<Record<NotificationProviderKey, ProviderFormRef>>>({});+ let savedSettings = $state<NotificationSettingsByProvider>(createNotificationSettingsByProvider());+ let providerValues = $state<NotificationProviderFormState>(createNotificationProviderFormState());+ let providerBaselines = $state<NotificationProviderFormState>(createNotificationProviderFormState());+ const changedProviders = $derived.by(() =>+ NOTIFICATION_PROVIDER_KEYS.filter(+ (provider) => JSON.stringify(providerValues[provider]) !== JSON.stringify(providerBaselines[provider])+ ));+ const hasChanges = $derived(changedProviders.length > 0);- function hasSavedCredential(settings: NotificationSettings | null, field: string) {+ function hasSavedCredential(settings: NotificationSettingsByProvider[NotificationProviderKey], field: string) {return settings?.config ? Object.prototype.hasOwnProperty.call(settings.config, field) : false;}@@ -179,78 +81,14 @@}});- // Load initial data- onMount(async () => {- // Load built-in provider settings- for (const provider of NOTIFICATION_PROVIDER_KEYS) {- const found = data?.notificationSettings?.find((s: NotificationSettings) => s.provider === provider);- savedSettings[provider] = found ?? null;- }-- // Apply saved values to form- emailValues = emailSettingsToFormValues(savedSettings.email ?? undefined);- emailBaseline = { ...emailValues };-- discordValues = discordSettingsToFormValues(savedSettings.discord ?? undefined);- discordBaseline = { ...discordValues };-- telegramValues = telegramSettingsToFormValues(savedSettings.telegram ?? undefined);- telegramBaseline = { ...telegramValues };-- signalValues = signalSettingsToFormValues(savedSettings.signal ?? undefined);- signalBaseline = { ...signalValues };-- slackValues = slackSettingsToFormValues(savedSettings.slack ?? undefined);- slackBaseline = { ...slackValues };-- ntfyValues = ntfySettingsToFormValues(savedSettings.ntfy ?? undefined);- ntfyBaseline = { ...ntfyValues };-- pushoverValues = pushoverSettingsToFormValues(savedSettings.pushover ?? undefined);- pushoverBaseline = { ...pushoverValues };-- gotifyValues = gotifySettingsToFormValues(savedSettings.gotify ?? undefined);- gotifyBaseline = { ...gotifyValues };-- matrixValues = matrixSettingsToFormValues(savedSettings.matrix ?? undefined);- matrixBaseline = { ...matrixValues };-- googlechatValues = googleChatSettingsToFormValues(savedSettings.googlechat ?? undefined);- googlechatBaseline = { ...googlechatValues };-- genericValues = genericSettingsToFormValues(savedSettings.generic ?? undefined);- genericBaseline = { ...genericValues };+ onMount(() => {+ savedSettings = createNotificationSettingsByProvider(data?.notificationSettings ?? []);+ providerValues = createNotificationProviderFormState(savedSettings);+ providerBaselines = cloneNotificationProviderFormState(providerValues);});async function onSubmit() {- // Validate all forms- const emailValid = emailFormRef?.isValid() ?? true;- const discordValid = discordFormRef?.isValid() ?? true;- const telegramValid = telegramFormRef?.isValid() ?? true;- const signalValid = signalFormRef?.isValid() ?? true;- const slackValid = slackFormRef?.isValid() ?? true;- const ntfyValid = ntfyFormRef?.isValid() ?? true;- const pushoverValid = pushoverFormRef?.isValid() ?? true;- const gotifyValid = gotifyFormRef?.isValid() ?? true;- const matrixValid = matrixFormRef?.isValid() ?? true;- const googlechatValid = googlechatFormRef?.isValid() ?? true;- const genericValid = genericFormRef?.isValid() ?? true;-- if (- !(- emailValid &&- discordValid &&- telegramValid &&- signalValid &&- slackValid &&- ntfyValid &&- pushoverValid &&- gotifyValid &&- matrixValid &&- googlechatValid &&- genericValid- )- ) {+ if (NOTIFICATION_PROVIDER_KEYS.some((provider) => providerFormRefs[provider]?.isValid() === false)) {toast.error(m.common_form_errors());return;}@@ -259,146 +97,19 @@try {const errors: string[] = [];-- // Save Email settings if changed- if (emailHasChanges) {- try {- const settings = emailFormValuesToSettings(emailValues);- await notificationService.updateSettings('email', settings);- savedSettings.email = settings;- emailBaseline = { ...emailValues };- } catch (error: any) {- const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';- errors.push(m.notifications_saved_failed({ provider: 'Email', error: errorMsg }));- }- }-- // Save Discord settings if changed- if (discordHasChanges) {- try {- const settings = discordFormValuesToSettings(discordValues);- await notificationService.updateSettings('discord', settings);- savedSettings.discord = settings;- discordBaseline = { ...discordValues };- } catch (error: any) {- const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';- errors.push(m.notifications_saved_failed({ provider: 'Discord', error: errorMsg }));- }- }-- // Save Telegram settings if changed- if (telegramHasChanges) {- try {- const settings = telegramFormValuesToSettings(telegramValues);- await notificationService.updateSettings('telegram', settings);- savedSettings.telegram = settings;- telegramBaseline = { ...telegramValues };- } catch (error: any) {- const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';- errors.push(m.notifications_saved_failed({ provider: 'Telegram', error: errorMsg }));- }- }-- // Save Signal settings if changed- if (signalHasChanges) {- try {- const settings = signalFormValuesToSettings(signalValues);- savedSettings.signal = await notificationService.updateSettings('signal', settings);- signalBaseline = { ...signalValues };- } catch (error: any) {- const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';- errors.push(m.notifications_saved_failed({ provider: 'Signal', error: errorMsg }));- }- }-- // Save Slack settings if changed- if (slackHasChanges) {- try {- const settings = slackFormValuesToSettings(slackValues);- await notificationService.updateSettings('slack', settings);- savedSettings.slack = settings;- slackBaseline = { ...slackValues };- } catch (error: any) {- const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';- errors.push(m.notifications_saved_failed({ provider: 'Slack', error: errorMsg }));- }- }-- // Save Ntfy settings if changed- if (ntfyHasChanges) {- try {- const settings = ntfyFormValuesToSettings(ntfyValues);- await notificationService.updateSettings('ntfy', settings);- savedSettings.ntfy = settings;- ntfyBaseline = { ...ntfyValues };- } catch (error: any) {- const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';- errors.push(m.notifications_saved_failed({ provider: 'Ntfy', error: errorMsg }));- }- }-- // Save Pushover settings if changed- if (pushoverHasChanges) {- try {- const settings = pushoverFormValuesToSettings(pushoverValues);- await notificationService.updateSettings('pushover', settings);- savedSettings.pushover = settings;- pushoverBaseline = { ...pushoverValues };- } catch (error: any) {- const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';- errors.push(m.notifications_saved_failed({ provider: 'Pushover', error: errorMsg }));- }- }-- // Save Gotify settings if changed- if (gotifyHasChanges) {- try {- const settings = gotifyFormValuesToSettings(gotifyValues);- await notificationService.updateSettings('gotify', settings);- savedSettings.gotify = settings;- gotifyBaseline = { ...gotifyValues };- } catch (error: any) {- const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';- errors.push(m.notifications_saved_failed({ provider: 'Gotify', error: errorMsg }));- }- }-- // Save Matrix settings if changed- if (matrixHasChanges) {+ for (const provider of changedProviders) {try {- const settings = matrixFormValuesToSettings(matrixValues);- await notificationService.updateSettings('matrix', settings);- savedSettings.matrix = settings;- matrixBaseline = { ...matrixValues };- } catch (error: any) {- const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';- errors.push(m.notifications_saved_failed({ provider: 'Matrix', error: errorMsg }));- }- }-- // Save Google Chat settings if changed- if (googlechatHasChanges) {- try {- const settings = googleChatFormValuesToSettings(googlechatValues);- await notificationService.updateSettings('googlechat', settings);- savedSettings.googlechat = settings;- googlechatBaseline = { ...googlechatValues };- } catch (error: any) {- const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';- errors.push(m.notifications_saved_failed({ provider: 'Google Chat', error: errorMsg }));- }- }-- // Save Generic settings if changed- if (genericHasChanges) {- try {- const settings = genericFormValuesToSettings(genericValues);- await notificationService.updateSettings('generic', settings);- savedSettings.generic = settings;- genericBaseline = { ...genericValues };- } catch (error: any) {- const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';- errors.push(m.notifications_saved_failed({ provider: 'Generic', error: errorMsg }));+ const settings = notificationProviderFormValuesToSettings(provider, providerValues[provider]);+ const saved = await notificationService.updateSettings(provider, settings);+ savedSettings = { ...savedSettings, [provider]: saved };+ providerBaselines = updateNotificationProviderFormState(providerBaselines, provider, providerValues[provider]);+ } catch (error) {+ errors.push(+ m.notifications_saved_failed({+ provider: getNotificationProviderDefinition(provider).label(),+ error: extractApiErrorMessage(error)+ })+ );}}@@ -416,17 +127,7 @@}function resetForm() {- emailValues = { ...emailBaseline };- discordValues = { ...discordBaseline };- telegramValues = { ...telegramBaseline };- signalValues = { ...signalBaseline };- slackValues = { ...slackBaseline };- ntfyValues = { ...ntfyBaseline };- pushoverValues = { ...pushoverBaseline };- gotifyValues = { ...gotifyBaseline };- matrixValues = { ...matrixBaseline };- googlechatValues = { ...googlechatBaseline };- genericValues = { ...genericBaseline };+ providerValues = cloneNotificationProviderFormState(providerBaselines);}async function testNotification(provider: NotificationProviderKey, testType: string = 'simple') {@@ -445,11 +146,10 @@if (result?.data?.warning) {toast.warning(m.notifications_test_warning({ warning: result.data.warning }));} else {- toast.success(m.notifications_test_success({ provider: provider.charAt(0).toUpperCase() + provider.slice(1) }));+ toast.success(m.notifications_test_success({ provider: getNotificationProviderDefinition(provider).label() }));}- } catch (error: any) {- const errorMsg = error?.response?.data?.error || error.message || m.common_unknown();- toast.error(m.notifications_test_failed({ error: errorMsg }));+ } catch (error) {+ toast.error(m.notifications_test_failed({ error: extractApiErrorMessage(error) }));} finally {isTesting = false;}@@ -477,139 +177,21 @@<Tabs.Root value={providerTab} class="flex min-h-0 w-full min-w-0 flex-col"><TabBar items={providerTabItems} value={providerTab} onValueChange={urlTab.select} class="self-start" />- <Tabs.Content value="email" class="mt-4 space-y-4">- <BuiltInProviderForm- bind:this={emailFormRef}- provider="email"- bind:values={emailValues}- disabled={isReadOnly}- {isTesting}- hasExistingCredentials={savedSettings.email !== null}- onTest={(testType) => testNotification('email', testType)}- />- </Tabs.Content>-- <Tabs.Content value="discord" class="mt-4 space-y-4">- <BuiltInProviderForm- bind:this={discordFormRef}- provider="discord"- bind:values={discordValues}- disabled={isReadOnly}- {isTesting}- hasExistingCredentials={savedSettings.discord !== null}- onTest={(testType) => testNotification('discord', testType)}- />- </Tabs.Content>-- <Tabs.Content value="telegram" class="mt-4 space-y-4">- <BuiltInProviderForm- bind:this={telegramFormRef}- provider="telegram"- bind:values={telegramValues}- disabled={isReadOnly}- {isTesting}- hasExistingCredentials={savedSettings.telegram !== null}- onTest={(testType) => testNotification('telegram', testType)}- />- </Tabs.Content>-- <Tabs.Content value="signal" class="mt-4 space-y-4">- <BuiltInProviderForm- bind:this={signalFormRef}- provider="signal"- bind:values={signalValues}- disabled={isReadOnly}- {isTesting}- hasExistingCredentials={savedSettings.signal !== null}- hasExistingPassword={hasSavedCredential(savedSettings.signal, 'password')}- hasExistingToken={hasSavedCredential(savedSettings.signal, 'token')}- onTest={(testType) => testNotification('signal', testType)}- />- </Tabs.Content>-- <Tabs.Content value="slack" class="mt-4 space-y-4">- <BuiltInProviderForm- bind:this={slackFormRef}- provider="slack"- bind:values={slackValues}- disabled={isReadOnly}- {isTesting}- hasExistingCredentials={savedSettings.slack !== null}- onTest={(testType) => testNotification('slack', testType)}- />- </Tabs.Content>-- <Tabs.Content value="ntfy" class="mt-4 space-y-4">- <BuiltInProviderForm- bind:this={ntfyFormRef}- provider="ntfy"- bind:values={ntfyValues}- disabled={isReadOnly}- {isTesting}- hasExistingCredentials={savedSettings.ntfy !== null}- onTest={(testType) => testNotification('ntfy', testType)}- />- </Tabs.Content>-- <Tabs.Content value="pushover" class="mt-4 space-y-4">- <BuiltInProviderForm- bind:this={pushoverFormRef}- provider="pushover"- bind:values={pushoverValues}- disabled={isReadOnly}- {isTesting}- hasExistingCredentials={savedSettings.pushover !== null}- onTest={(testType) => testNotification('pushover', testType)}- />- </Tabs.Content>-- <Tabs.Content value="gotify" class="mt-4 space-y-4">- <BuiltInProviderForm- bind:this={gotifyFormRef}- provider="gotify"- bind:values={gotifyValues}- disabled={isReadOnly}- {isTesting}- hasExistingCredentials={savedSettings.gotify !== null}- onTest={(testType) => testNotification('gotify', testType)}- />- </Tabs.Content>-- <Tabs.Content value="matrix" class="mt-4 space-y-4">- <BuiltInProviderForm- bind:this={matrixFormRef}- provider="matrix"- bind:values={matrixValues}- disabled={isReadOnly}- {isTesting}- hasExistingCredentials={savedSettings.matrix !== null}- onTest={(testType) => testNotification('matrix', testType)}- />- </Tabs.Content>-- <Tabs.Content value="googlechat" class="mt-4 space-y-4">- <BuiltInProviderForm- bind:this={googlechatFormRef}- provider="googlechat"- bind:values={googlechatValues}- disabled={isReadOnly}- {isTesting}- hasExistingCredentials={savedSettings.googlechat !== null}- onTest={(testType) => testNotification('googlechat', testType)}- />- </Tabs.Content>-- <Tabs.Content value="generic" class="mt-4 space-y-4">- <BuiltInProviderForm- bind:this={genericFormRef}- provider="generic"- bind:values={genericValues}- disabled={isReadOnly}- {isTesting}- hasExistingCredentials={savedSettings.generic !== null}- onTest={(testType) => testNotification('generic', testType)}- />- </Tabs.Content>+ {#each NOTIFICATION_PROVIDER_KEYS as provider (provider)}+ <Tabs.Content value={provider} class="mt-4 space-y-4">+ <BuiltInProviderForm+ bind:this={providerFormRefs[provider]}+ {provider}+ bind:values={providerValues[provider]}+ disabled={isReadOnly}+ {isTesting}+ hasExistingCredentials={savedSettings[provider] !== null}+ hasExistingPassword={provider === 'signal' && hasSavedCredential(savedSettings.signal, 'password')}+ hasExistingToken={provider === 'signal' && hasSavedCredential(savedSettings.signal, 'token')}+ onTest={(testType) => testNotification(provider, testType)}+ />+ </Tabs.Content>+ {/each}</Tabs.Root></fieldset>{/snippet}diff --git a/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelteindex 0cb8da8eb..9680b550b 100644--- a/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte+++ b/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte@@ -11,6 +11,7 @@} from './NotificationProviderTestMenu.svelte';import { mapZodFieldErrors } from './provider-form-validation';import type { ProviderFormSchema } from './provider-form-schema';+ import { getNotificationProviderDefinition } from '#lib/utils/notification-providers';type AnyBuiltInValues = ProviderFormValuesMap[NotificationProviderKey];@@ -43,53 +44,6 @@onTest}: Props = $props();- const providerMeta: Record<NotificationProviderKey, { title: string; description: string }> = {- discord: {- title: m.notifications_discord_title(),- description: m.notifications_discord_description()- },- email: {- title: m.common_email(),- description: m.notifications_email_description()- },- telegram: {- title: m.notifications_telegram_title(),- description: m.notifications_telegram_description()- },- signal: {- title: m.notifications_signal_title(),- description: m.notifications_signal_description()- },- slack: {- title: m.notifications_slack_title(),- description: m.notifications_slack_description()- },- ntfy: {- title: m.notifications_ntfy_title(),- description: m.notifications_ntfy_description()- },- pushover: {- title: m.notifications_pushover_title(),- description: m.notifications_pushover_description()- },- gotify: {- title: m.notifications_gotify_title(),- description: m.notifications_gotify_description()- },- matrix: {- title: m.notifications_matrix_title(),- description: m.notifications_matrix_description()- },- googlechat: {- title: m.notifications_googlechat_title(),- description: m.notifications_googlechat_description()- },- generic: {- title: m.notifications_generic_title(),- description: m.notifications_generic_description()- }- };-const eventSubscriptionSchemaFields = {eventImageUpdate: z.boolean(),eventContainerUpdate: z.boolean(),@@ -126,8 +80,8 @@}).superRefine((d, ctx) => {if (!d.enabled) return;- addRequiredTrimmedFieldIssue(ctx, d.webhookId, 'webhookId', 'Webhook ID is required when Discord is enabled');- addRequiredCredentialIssue(ctx, d.token, 'token', 'Webhook Token is required when Discord is enabled');+ addRequiredTrimmedFieldIssue(ctx, d.webhookId, 'webhookId', m.common_required());+ addRequiredCredentialIssue(ctx, d.token, 'token', m.common_required());}),email: z.object({@@ -145,20 +99,20 @@.superRefine((d, ctx) => {if (!d.enabled) return;if (!d.smtpHost.trim()) {- ctx.addIssue({ code: 'custom', message: 'SMTP host is required when email is enabled', path: ['smtpHost'] });+ ctx.addIssue({ code: 'custom', message: m.common_required(), path: ['smtpHost'] });}if (!d.fromAddress.trim()) {- ctx.addIssue({ code: 'custom', message: 'From address is required when email is enabled', path: ['fromAddress'] });+ ctx.addIssue({ code: 'custom', message: m.common_required(), path: ['fromAddress'] });} else {const v = z.string().email().safeParse(d.fromAddress.trim());if (!v.success) {- ctx.addIssue({ code: 'custom', message: 'Invalid email address format', path: ['fromAddress'] });+ ctx.addIssue({ code: 'custom', message: m.common_invalid_email(), path: ['fromAddress'] });}}if (!d.toAddresses.trim()) {ctx.addIssue({code: 'custom',- message: 'At least one recipient address is required when email is enabled',+ message: m.common_required(),path: ['toAddresses']});} else {@@ -174,7 +128,7 @@if (invalid.length > 0) {ctx.addIssue({code: 'custom',- message: `Invalid email addresses: ${invalid.join(', ')}`,+ message: m.notifications_email_invalid_addresses({ addresses: invalid.join(', ') }),path: ['toAddresses']});}@@ -192,11 +146,11 @@}).superRefine((d, ctx) => {if (!d.enabled) return;- addRequiredCredentialIssue(ctx, d.botToken, 'botToken', 'Bot Token is required when Telegram is enabled');+ addRequiredCredentialIssue(ctx, d.botToken, 'botToken', m.common_required());if (!d.chatIds.trim()) {ctx.addIssue({code: 'custom',- message: 'At least one Chat ID is required when Telegram is enabled',+ message: m.common_required(),path: ['chatIds']});}@@ -296,9 +250,9 @@}).superRefine((d, ctx) => {if (!d.enabled) return;- addRequiredTrimmedFieldIssue(ctx, d.topic, 'topic', 'Topic is required when Ntfy is enabled');+ addRequiredTrimmedFieldIssue(ctx, d.topic, 'topic', m.common_required());if (d.port > 0 && (d.port < 1 || d.port > 65535)) {- addCustomFieldIssue(ctx, 'port', 'Port must be between 1 and 65535');+ addCustomFieldIssue(ctx, 'port', m.notifications_signal_port_invalid());}}),pushover: z@@ -358,7 +312,7 @@}).superRefine((d, ctx) => {if (!d.enabled) return;- addRequiredTrimmedFieldIssue(ctx, d.webhookUrl, 'webhookUrl', 'Webhook URL is required when Google Chat is enabled');+ addRequiredTrimmedFieldIssue(ctx, d.webhookUrl, 'webhookUrl', m.common_required());}),generic: z.object({@@ -375,7 +329,7 @@}).superRefine((d, ctx) => {if (!d.enabled) return;- addRequiredTrimmedFieldIssue(ctx, d.webhookUrl, 'webhookUrl', 'Webhook URL is required when Generic Webhook is enabled');+ addRequiredTrimmedFieldIssue(ctx, d.webhookUrl, 'webhookUrl', m.common_required());})};@@ -489,9 +443,9 @@placeholder: m.notifications_email_tls_mode_placeholder(),description: m.notifications_email_tls_mode_description(),options: [- { value: 'none', label: 'None' },- { value: 'starttls', label: 'StartTLS' },- { value: 'ssl', label: 'SSL/TLS' }+ { value: 'none', label: m.notifications_email_tls_none() },+ { value: 'starttls', label: m.notifications_email_tls_starttls() },+ { value: 'ssl', label: m.notifications_email_tls_ssl() }]},{@@ -504,9 +458,9 @@options: [{ value: 'auto', label: m.notifications_email_auth_mode_option_auto() },{ value: 'none', label: m.notifications_email_auth_mode_option_none() },- { value: 'plain', label: 'PLAIN' },- { value: 'login', label: 'LOGIN' },- { value: 'crammd5', label: 'CRAM-MD5' }+ { value: 'plain', label: m.notifications_email_auth_plain() },+ { value: 'login', label: m.notifications_email_auth_login() },+ { value: 'crammd5', label: m.notifications_email_auth_cram_md5() }]}],@@ -515,27 +469,27 @@kind: 'input',key: 'botToken',id: 'telegram-bot-token',- label: 'Bot Token',- placeholder: '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11',- helpText: 'The bot token from @BotFather',+ label: m.notifications_telegram_bot_token_label(),+ placeholder: m.notifications_telegram_bot_token_placeholder(),+ helpText: m.notifications_telegram_bot_token_help(),inputType: 'password'},{kind: 'textarea',key: 'chatIds',id: 'telegram-chat-ids',- label: 'Chat IDs',- placeholder: '@channel, 123456789, @another_channel',- helpText: 'Comma-separated list of chat IDs or @channel names',+ label: m.notifications_telegram_chat_ids_label(),+ placeholder: m.notifications_telegram_chat_ids_placeholder(),+ helpText: m.notifications_telegram_chat_ids_help(),rows: 2},{kind: 'input',key: 'title',id: 'telegram-title',- label: 'Title (Optional)',- placeholder: 'Arcane Notifications',- helpText: 'Custom title for notifications'+ label: m.notifications_telegram_title_label(),+ placeholder: m.notifications_telegram_title_placeholder(),+ helpText: m.notifications_telegram_title_help()},{kind: 'row',@@ -545,15 +499,15 @@kind: 'switch',key: 'preview',id: 'telegram-preview',- label: 'Enable Link Previews',- description: 'Show web page previews for URLs in messages'+ label: m.notifications_telegram_preview_label(),+ description: m.notifications_telegram_preview_description()},{kind: 'switch',key: 'notification',id: 'telegram-notification',- label: 'Enable Notification Sound',- description: 'Play notification sound when messages are received'+ label: m.notifications_telegram_sound_label(),+ description: m.notifications_telegram_sound_description()}]}@@ -774,11 +728,11 @@label: m.priority(),description: m.notifications_ntfy_priority_help(),options: [- { value: 'min', label: 'Min (1)' },- { value: 'low', label: 'Low (2)' },- { value: 'default', label: 'Default (3)' },- { value: 'high', label: 'High (4)' },- { value: 'max', label: 'Max/Urgent (5)' }+ { value: 'min', label: `${m.notifications_priority_min()} (1)` },+ { value: 'low', label: `${m.notifications_priority_low()} (2)` },+ { value: 'default', label: `${m.notifications_priority_default()} (3)` },+ { value: 'high', label: `${m.notifications_priority_high()} (4)` },+ { value: 'max', label: `${m.notifications_priority_max_urgent()} (5)` }]},{@@ -935,19 +889,19 @@description: m.notifications_gotify_priority_help(),valueType: 'number',options: [- { value: '-2', label: '-2 (Min)' },- { value: '-1', label: '-1 (Low)' },- { value: '0', label: '0 (None)' },- { value: '1', label: '1 (Low)' },+ { value: '-2', label: `-2 (${m.notifications_priority_min()})` },+ { value: '-1', label: `-1 (${m.notifications_priority_low()})` },+ { value: '0', label: `0 (${m.none()})` },+ { value: '1', label: `1 (${m.notifications_priority_low()})` },{ value: '2', label: '2' },{ value: '3', label: '3' },- { value: '4', label: '4 (Normal)' },+ { value: '4', label: `4 (${m.notifications_priority_normal()})` },{ value: '5', label: '5' },{ value: '6', label: '6' },- { value: '7', label: '7 (High)' },+ { value: '7', label: `7 (${m.notifications_priority_high()})` },{ value: '8', label: '8' },{ value: '9', label: '9' },- { value: '10', label: '10 (Max)' }+ { value: '10', label: `10 (${m.notifications_priority_max()})` }]},{@@ -1125,7 +1079,7 @@mapZodFieldErrors<AnyBuiltInValues>(validation as z.ZodSafeParseResult<AnyBuiltInValues>));const selectedSchema = $derived(providerFormSchemas[provider] as ProviderFormSchema<AnyBuiltInValues>);- const selectedMeta = $derived(providerMeta[provider]);+ const selectedMeta = $derived(getNotificationProviderDefinition(provider));export function isValid(): boolean {return validation.success;@@ -1134,8 +1088,8 @@<ProviderFormWrapperid={provider}- title={selectedMeta.title}- description={selectedMeta.description}+ title={selectedMeta.label()}+ description={selectedMeta.description()}bind:enabled={values.enabled}{disabled}>diff --git a/frontend/src/routes/(app)/settings/roles/roles-table.svelte b/frontend/src/routes/(app)/settings/roles/roles-table.svelteindex 1d12b3368..249922594 100644--- a/frontend/src/routes/(app)/settings/roles/roles-table.svelte+++ b/frontend/src/routes/(app)/settings/roles/roles-table.svelte@@ -4,10 +4,7 @@import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';import * as ArcaneTooltip from '#lib/components/arcane-tooltip';- import { openConfirmDialog } from '#lib/components/confirm-dialog';import { Badge } from '#lib/components/ui/badge';- import { handleApiResultWithCallbacks } from '#lib/utils/api';- import { tryCatch } from '#lib/utils/api';import { goto } from '$app/navigation';import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared';import type { Role } from '#lib/types/auth';@@ -19,6 +16,7 @@import { ShieldAlertIcon, TrashIcon, EditIcon } from '#lib/icons';import userStore from '#lib/stores/user-store';import IfPermitted from '#lib/components/if-permitted.svelte';+ import { bulkConfirmAndRun, confirmAndRun } from '#lib/utils/bulk-actions';let {roles = $bindable(),@@ -69,75 +67,46 @@const deletableSelectedIds = $derived.by(() => selectedRoles.filter((role) => !role.builtIn).map((role) => role.id));const hasBuiltInSelection = $derived.by(() => selectedRoles.some((role) => role.builtIn));- async function handleDeleteSelected() {+ function handleDeleteSelected() {if (deletableSelectedIds.length === 0) return;+ const ids = [...deletableSelectedIds];- openConfirmDialog({- title: m.roles_delete_selected_title({ count: deletableSelectedIds.length }),+ bulkConfirmAndRun({+ ids,+ title: m.roles_delete_selected_title({ count: ids.length }),message: m.roles_delete_message({ name: m.common_unknown() }),- confirm: {- label: m.common_delete(),- destructive: true,- action: async () => {- isLoading.removing = true;- let successCount = 0;- let failureCount = 0;-- for (const roleId of deletableSelectedIds) {- const result = await tryCatch(roleService.delete(roleId));- handleApiResultWithCallbacks({- result,- message: m.common_delete_failed({ resource: `${m.resource_role()} "${roleId}"` }),- setLoadingState: () => {},- onSuccess: () => {- successCount++;- }- });-- if (result.error) {- failureCount++;- }- }-- isLoading.removing = false;-- if (successCount > 0) {- toast.success(m.common_bulk_delete_success({ count: successCount, resource: m.roles_title() }));- await onRolesChanged();- }-- if (failureCount > 0) {- toast.error(m.common_bulk_delete_failed({ count: failureCount, resource: m.roles_title() }));- }-- selectedIds = [];- }- }+ confirmLabel: m.common_delete(),+ destructive: true,+ run: (roleId) => roleService.delete(roleId),+ messages: {+ success: (count) => m.common_bulk_delete_success({ count, resource: m.roles_title() }),+ partial: (success, total, failed) => m.common_bulk_delete_partial({ success, total, failed, resource: m.roles_title() }),+ failure: () => m.common_bulk_delete_failed({ count: ids.length, resource: m.roles_title() })+ },+ setLoading: (loading) => (isLoading.removing = loading),+ onComplete: async ({ success }) => {+ if (success > 0) await onRolesChanged();+ },+ clearSelection: () => (selectedIds = []),+ sequential: true});}- async function handleDeleteRole(role: Role) {+ function handleDeleteRole(role: Role) {if (role.builtIn) return;const safeName = role.name?.trim() || m.common_unknown();- openConfirmDialog({+ confirmAndRun({title: m.roles_delete_title({ name: safeName }),message: m.roles_delete_message({ name: safeName }),- confirm: {- label: m.common_delete(),- destructive: true,- action: async () => {- isLoading.removing = true;- handleApiResultWithCallbacks({- result: await tryCatch(roleService.delete(role.id)),- message: m.common_delete_failed({ resource: `${m.resource_role()} "${safeName}"` }),- setLoadingState: (value) => (isLoading.removing = value),- onSuccess: async () => {- toast.success(m.common_delete_success({ resource: `${m.resource_role()} "${safeName}"` }));- await onRolesChanged();- }- });- }+ confirmLabel: m.common_delete(),+ destructive: true,+ setLoading: (loading) => (isLoading.removing = loading),+ run: () => roleService.delete(role.id),+ failureMessage: m.common_delete_failed({ resource: `${m.resource_role()} "${safeName}"` }),+ onSuccess: async () => {+ toast.success(m.common_delete_success({ resource: `${m.resource_role()} "${safeName}"` }));+ await onRolesChanged();}});}diff --git a/frontend/src/routes/(app)/settings/users/user-table.svelte b/frontend/src/routes/(app)/settings/users/user-table.svelteindex 970b96cb0..867f7aeab 100644--- a/frontend/src/routes/(app)/settings/users/user-table.svelte+++ b/frontend/src/routes/(app)/settings/users/user-table.svelte@@ -3,11 +3,8 @@import { toast } from 'svelte-sonner';import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';- import { openConfirmDialog } from '#lib/components/confirm-dialog';import { Badge } from '#lib/components/ui/badge';import * as ArcaneTooltip from '#lib/components/arcane-tooltip';- import { handleApiResultWithCallbacks } from '#lib/utils/api';- import { tryCatch } from '#lib/utils/api';import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared';import type { User } from '#lib/types/auth';import type { Role } from '#lib/types/auth';@@ -18,6 +15,7 @@import { userService } from '#lib/services/user-service';import { UserIcon, TrashIcon, EditIcon } from '#lib/icons';import IfPermitted from '#lib/components/if-permitted.svelte';+ import { bulkConfirmAndRun, confirmAndRun } from '#lib/utils/bulk-actions';let {users = $bindable(),@@ -51,77 +49,46 @@const hasProtectedSelection = $derived.by(() => selectedUsers.some((user) => !canDeleteUser(user)));- async function handleDeleteSelected() {+ function handleDeleteSelected() {if (selectedIds.length === 0 || hasProtectedSelection) return;-- openConfirmDialog({- title: m.users_delete_selected_title({ count: selectedIds.length }),- message: m.users_delete_selected_message({ count: selectedIds.length, users: selectedIds.length }),- confirm: {- label: m.common_delete(),- destructive: true,- action: async () => {- isLoading.removing = true;- let successCount = 0;- let failureCount = 0;-- for (const userId of selectedIds) {- const result = await tryCatch(userService.delete(userId));- handleApiResultWithCallbacks({- result,- message: m.users_delete_selected_item_failed({ id: userId }),- setLoadingState: () => {},- onSuccess: () => {- successCount++;- }- });-- if (result.error) {- failureCount++;- }- }-- isLoading.removing = false;-- if (successCount > 0) {- const msg = m.common_bulk_delete_success({ count: successCount, resource: m.users_title() });- toast.success(msg);- await onUsersChanged();- }-- if (failureCount > 0) {- const msg = m.common_bulk_delete_failed({ count: failureCount, resource: m.users_title() });- toast.error(msg);- }-- selectedIds = [];- }- }+ const ids = [...selectedIds];++ bulkConfirmAndRun({+ ids,+ title: m.users_delete_selected_title({ count: ids.length }),+ message: m.users_delete_selected_message({ count: ids.length, users: ids.length }),+ confirmLabel: m.common_delete(),+ destructive: true,+ run: (userId) => userService.delete(userId),+ messages: {+ success: (count) => m.common_bulk_delete_success({ count, resource: m.users_title() }),+ partial: (success, total, failed) => m.common_bulk_delete_partial({ success, total, failed, resource: m.users_title() }),+ failure: () => m.common_bulk_delete_failed({ count: ids.length, resource: m.users_title() })+ },+ setLoading: (loading) => (isLoading.removing = loading),+ onComplete: async ({ success }) => {+ if (success > 0) await onUsersChanged();+ },+ clearSelection: () => (selectedIds = []),+ sequential: true});}- async function handleDeleteUser(user: User) {+ function handleDeleteUser(user: User) {if (!canDeleteUser(user)) return;const safeName = user.username?.trim() || m.common_unknown();- openConfirmDialog({+ confirmAndRun({title: m.users_delete_user_title({ username: safeName }),message: m.users_delete_user_message({ username: safeName }),- confirm: {- label: m.common_delete(),- destructive: true,- action: async () => {- isLoading.removing = true;- handleApiResultWithCallbacks({- result: await tryCatch(userService.delete(user.id)),- message: m.users_delete_user_failed({ username: safeName }),- setLoadingState: (value) => (isLoading.removing = value),- onSuccess: async () => {- toast.success(m.users_delete_user_success({ username: safeName }));- await onUsersChanged();- }- });- }+ confirmLabel: m.common_delete(),+ destructive: true,+ setLoading: (loading) => (isLoading.removing = loading),+ run: () => userService.delete(user.id),+ failureMessage: m.users_delete_user_failed({ username: safeName }),+ onSuccess: async () => {+ toast.success(m.users_delete_user_success({ username: safeName }));+ await onUsersChanged();}});}diff --git a/frontend/src/routes/(app)/swarm/nodes/+page.svelte b/frontend/src/routes/(app)/swarm/nodes/+page.svelteindex e31dfcc50..39a25c124 100644--- a/frontend/src/routes/(app)/swarm/nodes/+page.svelte+++ b/frontend/src/routes/(app)/swarm/nodes/+page.svelte@@ -4,12 +4,13 @@import { m } from '#lib/paraglide/messages';import { swarmService } from '#lib/services/swarm-service';import { untrack } from 'svelte';- import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';+ import { ResourcePageLayout, type StatCardConfig } from '#lib/layouts/index.js';import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte';- import { parallelRefresh } from '#lib/utils/api';+ import { simpleRefresh } from '#lib/utils/api';import SwarmNodesTable from './nodes-table.svelte';import { hasPermission } from '#lib/utils/auth';import { environmentStore } from '#lib/stores/environment.store.svelte';+ import { createRefreshActionButtons } from '#lib/utils/resource-actions';let { data } = $props();@@ -21,17 +22,11 @@const canManageNodes = $derived(hasPermission('swarm:nodes', currentEnvironmentId ?? undefined));async function refresh() {- await parallelRefresh(- {- nodes: {- fetch: () => swarmService.getNodes(requestOptions),- onSuccess: (data) => {- nodes = data;- },- errorMessage: m.common_refresh_failed({ resource: m.nodes() })- }- },- (v) => (isLoading.refresh = v)+ await simpleRefresh(+ () => swarmService.getNodes(requestOptions),+ (data) => (nodes = data),+ m.common_refresh_failed({ resource: m.nodes() }),+ (loading) => (isLoading.refresh = loading));}@@ -53,16 +48,13 @@);const uncoveredNodeCount = $derived(uncoveredNodes.length);- const actionButtons: ActionButton[] = $derived([- {- id: 'refresh',- action: 'restart',- label: m.common_refresh(),- onclick: refresh,- loading: isLoading.refresh,- disabled: isLoading.refresh- }- ]);+ const actionButtons = $derived(+ createRefreshActionButtons({+ refreshLabel: m.common_refresh(),+ onRefresh: refresh,+ refreshing: isLoading.refresh+ })+ );const statCards: StatCardConfig[] = $derived([{diff --git a/frontend/src/routes/(app)/swarm/services/+page.svelte b/frontend/src/routes/(app)/swarm/services/+page.svelteindex 654597607..5f31c4849 100644--- a/frontend/src/routes/(app)/swarm/services/+page.svelte+++ b/frontend/src/routes/(app)/swarm/services/+page.svelte@@ -8,7 +8,7 @@import { handleApiResultWithCallbacks } from '#lib/utils/api';import { ResourcePageLayout, type StatCardConfig } from '#lib/layouts/index.js';import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte';- import { parallelRefresh } from '#lib/utils/api';+ import { simpleRefresh } from '#lib/utils/api';import { createRefreshActionButtons } from '#lib/utils/resource-actions';import type { SwarmServiceCreateSpec } from '#lib/types/swarm';import SwarmServicesTable from './services-table.svelte';@@ -24,17 +24,11 @@let showCreateDialog = $state(false);async function refresh() {- await parallelRefresh(- {- services: {- fetch: () => swarmService.getServices(requestOptions),- onSuccess: (data) => {- services = data;- },- errorMessage: m.common_refresh_failed({ resource: m.services() })- }- },- (v) => (isLoading.refresh = v)+ await simpleRefresh(+ () => swarmService.getServices(requestOptions),+ (data) => (services = data),+ m.common_refresh_failed({ resource: m.services() }),+ (loading) => (isLoading.refresh = loading));}@@ -61,9 +55,11 @@const actionButtons = $derived.by(() =>createRefreshActionButtons({- canCreate: canCreateService,- createLabel: m.common_create_button({ resource: m.swarm_service() }),- onCreate: () => (showCreateDialog = true),+ create: {+ allowed: canCreateService,+ label: m.common_create_button({ resource: m.swarm_service() }),+ onclick: () => (showCreateDialog = true)+ },refreshLabel: m.common_refresh(),onRefresh: refresh,refreshing: isLoading.refreshdiff --git a/frontend/src/routes/(app)/swarm/stacks/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/+page.svelteindex 1386b5265..4674bebfc 100644--- a/frontend/src/routes/(app)/swarm/stacks/+page.svelte+++ b/frontend/src/routes/(app)/swarm/stacks/+page.svelte@@ -5,7 +5,7 @@import { untrack } from 'svelte';import { ResourcePageLayout, type StatCardConfig } from '#lib/layouts/index.js';import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte';- import { parallelRefresh } from '#lib/utils/api';+ import { simpleRefresh } from '#lib/utils/api';import { createRefreshActionButtons } from '#lib/utils/resource-actions';import SwarmStacksTable from './stacks-table.svelte';import { goto } from '$app/navigation';@@ -19,17 +19,11 @@let isLoading = $state({ refresh: false });async function refresh() {- await parallelRefresh(- {- stacks: {- fetch: () => swarmService.getStacks(requestOptions),- onSuccess: (data) => {- stacks = data;- },- errorMessage: m.common_refresh_failed({ resource: m.swarm_stacks_title() })- }- },- (v) => (isLoading.refresh = v)+ await simpleRefresh(+ () => swarmService.getStacks(requestOptions),+ (data) => (stacks = data),+ m.common_refresh_failed({ resource: m.swarm_stacks_title() }),+ (loading) => (isLoading.refresh = loading));}@@ -42,9 +36,11 @@const actionButtons = $derived.by(() =>createRefreshActionButtons({- canCreate: canCreateStack,- createLabel: m.common_create_button({ resource: m.swarm_stack() }),- onCreate: () => goto('/swarm/stacks/new'),+ create: {+ allowed: canCreateStack,+ label: m.common_create_button({ resource: m.swarm_stack() }),+ onclick: () => goto('/swarm/stacks/new')+ },refreshLabel: m.common_refresh(),onRefresh: refresh,refreshing: isLoading.refreshdiff --git a/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/new/+page.svelteindex 4e024b3ca..6cdb8bd3a 100644--- a/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte+++ b/frontend/src/routes/(app)/swarm/stacks/new/+page.svelte@@ -21,24 +21,16 @@import { environmentStore } from '#lib/stores/environment.store.svelte';import DockerRunConverterDialog from '#lib/components/compose/docker-run-converter-dialog.svelte';import { globalVariablesToMap } from '#lib/utils/template-load';- import type { WorkspaceFileDraft } from '#lib/types/workspace';import type { SwarmSyncFile } from '#lib/types/swarm';import {- isWorkspaceFileSelectionUnder,planWorkspaceFileCreate,planWorkspaceFileMove,planWorkspaceFileRename,- readWorkspaceTextUpload,- remapWorkspaceFilePath,- remapWorkspaceFileRecord,- remapSelectedWorkspaceFileKey,- removeWorkspaceFileRecord,validateWorkspaceFileName,workspaceFileBasename,- workspaceFileLanguage,- workspaceFilePathMatches,- type WorkspaceFileEntry+ workspaceFileLanguage} from '#lib/utils/workspace-files';+ import { WorkspaceDraftState } from '#lib/components/workspace-editor/workspace-draft-state.svelte';import settingsStore from '#lib/stores/config-store';import {createComposeEditorSchema,@@ -116,26 +108,24 @@return btoa(encoded);}- let stackFiles = $state<WorkspaceFileDraft[]>(- untrack(() => (data.sourceFiles ?? []).map((file) => ({ relativePath: file.relativePath, isDirectory: false })))- );- let stackFileContents = $state<Record<string, string>>(- untrack(() =>+ const stackWorkspace = new WorkspaceDraftState({+ initialFiles: untrack(() =>+ (data.sourceFiles ?? []).map((file) => ({ relativePath: file.relativePath, isDirectory: false }))+ ),+ initialContents: untrack(() =>Object.fromEntries((data.sourceFiles ?? []).map((file) => [file.relativePath, decodeStackFileContent(file.content)]))- )- );- const stackFileEntries = $derived.by<WorkspaceFileEntry[]>(() =>- stackFiles.map((file) => ({- path: file.relativePath,- relativePath: file.relativePath,- name: workspaceFileBasename(file.relativePath),- isDirectory: !!file.isDirectory,- size: file.isDirectory ? 0 : (stackFileContents[file.relativePath]?.length ?? 0),- content: file.isDirectory ? undefined : (stackFileContents[file.relativePath] ?? ''),- pending: false- }))- );- const stackFilePaths = $derived.by(() => new Set(stackFileEntries.map((file) => file.relativePath)));+ ),+ initialOpenTabs: ['compose'],+ initialSelection: 'compose',+ fallbackTab: 'compose',+ pendingEntries: false,+ isFixedTab: (key) => key === 'compose' || key === 'env' || key === 'override',+ isTabAvailable: (key) => key !== 'override' || overrideActive,+ planCreate: planWorkspaceFileCreate,+ planRename: planWorkspaceFileRename,+ planMove: planWorkspaceFileMove+ });+ const stackFileEntries = $derived(stackWorkspace.entries);const stackWorkspaceLeadingRows = $derived.by(() => [{ key: 'compose', label: 'compose.yaml', iconClass: 'text-blue-500', locked: true },...(overrideActive@@ -144,24 +134,11 @@{ key: 'env', label: '.env', iconClass: 'text-green-500', locked: true }]);- let selectedStackFile = $state('compose');- let openStackTabs = $state<string[]>(['compose']);let stackTreeWidth = $state<number | null>(null);let treeOutlineOpen = $state(false);let treeCommandPaletteOpen = $state(false);- const stackOpenTabs = $derived.by(() => {- const valid = openStackTabs.filter((key) => {- if (key === 'compose' || key === 'env') return true;- if (key === 'override') return overrideActive;- if (!key.startsWith('file:')) return false;- const entry = stackFileEntries.find((file) => file.relativePath === key.slice(5));- return !!entry && !entry.isDirectory;- });- return valid.length > 0 ? valid : ['compose'];- });- const activeStackTab = $derived(- stackOpenTabs.includes(selectedStackFile) ? selectedStackFile : (stackOpenTabs[0] ?? 'compose')- );+ const stackOpenTabs = $derived(stackWorkspace.validOpenTabs);+ const activeStackTab = $derived(stackWorkspace.activeTab);const stackTabs = $derived(stackOpenTabs.map((key) => ({key,@@ -187,102 +164,23 @@})));- function isStackDirectoryKey(key: string): boolean {- if (!key.startsWith('file:')) return false;- return stackFileEntries.find((file) => file.relativePath === key.slice(5))?.isDirectory === true;- }-- function openStackTab(key: string) {- if (!isStackDirectoryKey(key) && !openStackTabs.includes(key)) {- openStackTabs = [...openStackTabs, key];- }- selectedStackFile = key;- }-- function closeStackTab(key: string) {- const index = stackOpenTabs.indexOf(key);- const remaining = stackOpenTabs.filter((tab) => tab !== key);- openStackTabs = openStackTabs.filter((tab) => tab !== key);- if (selectedStackFile === key) {- selectedStackFile = remaining[Math.min(Math.max(index - 1, 0), remaining.length - 1)] ?? 'compose';- }- }-function addOverride() {overrideActive = true;- openStackTab('override');+ stackWorkspace.openTab('override');}function removeOverride() {overrideContent = '';overrideActive = false;- closeStackTab('override');- }-- function createStackFile(parentPath: string, name: string, content = '') {- const relativePath = planWorkspaceFileCreate(stackFilePaths, parentPath, name);- if (!relativePath) return;- stackFiles = [...stackFiles, { relativePath, isDirectory: false }];- stackFileContents = { ...stackFileContents, [relativePath]: content };- openStackTab(`file:${relativePath}`);- }-- async function uploadStackFile(parentPath: string, files: File[]): Promise<string | void> {- const file = files[0];- if (!file) return m.workspace_upload_file_required();- const result = await readWorkspaceTextUpload(file, workspaceMaxFileSizeMb);- if (result.error) return result.error;- createStackFile(parentPath, file.name, result.content ?? '');- }-- function createStackFolder(parentPath: string, name: string) {- const relativePath = planWorkspaceFileCreate(stackFilePaths, parentPath, name);- if (!relativePath) return;- stackFiles = [...stackFiles, { relativePath, isDirectory: true }];- selectedStackFile = `file:${relativePath}`;- }-- function applyStackFilePathChange(oldPath: string, newPath: string) {- stackFiles = stackFiles.map((file) => ({- ...file,- relativePath: remapWorkspaceFilePath(file.relativePath, oldPath, newPath)- }));- stackFileContents = remapWorkspaceFileRecord(stackFileContents, oldPath, newPath);- openStackTabs = openStackTabs.map((tab) => remapSelectedWorkspaceFileKey(tab, oldPath, newPath) ?? tab);- const remappedSelection = remapSelectedWorkspaceFileKey(selectedStackFile, oldPath, newPath);- if (remappedSelection) {- selectedStackFile = remappedSelection;- }- }-- function renameStackFile(relativePath: string, newName: string) {- const plan = planWorkspaceFileRename(stackFilePaths, relativePath, newName);- if (!plan) return;- applyStackFilePathChange(relativePath, plan.newPath);- }-- function moveStackFile(relativePath: string, newParentPath: string) {- const entry = stackFileEntries.find((file) => file.relativePath === relativePath);- const newPath = planWorkspaceFileMove(entry, stackFilePaths, relativePath, newParentPath);- if (!newPath) return;- applyStackFilePathChange(relativePath, newPath);- }-- function deleteStackFile(relativePath: string) {- stackFiles = stackFiles.filter((file) => !workspaceFilePathMatches(file.relativePath, relativePath));- stackFileContents = removeWorkspaceFileRecord(stackFileContents, relativePath);- openStackTabs = openStackTabs.filter((tab) => !isWorkspaceFileSelectionUnder(tab, relativePath));- if (isWorkspaceFileSelectionUnder(selectedStackFile, relativePath)) {- selectedStackFile = stackOpenTabs[0] ?? 'compose';- }+ stackWorkspace.closeTab('override');}function buildStackFilePayload(): SwarmSyncFile[] {- return stackFiles+ return stackWorkspace.files.filter((file) => !file.isDirectory).map((file) => ({relativePath: file.relativePath,- content: encodeStackFileContent(stackFileContents[file.relativePath] ?? '')+ content: encodeStackFileContent(stackWorkspace.contents[file.relativePath] ?? '')}));}@@ -377,7 +275,7 @@variant="inline"error={$inputs.name.error ?? undefined}originalValue={initialName}- placeholder={m.compose_project_name_placeholder?.() || 'Enter name...'}+ placeholder={m.compose_project_name_placeholder()}canEdit={!isEditMode && !ui.saving && !ui.isLoadingTemplateContent}class="hidden sm:block"/>@@ -487,22 +385,27 @@<WorkspaceFileTreePanelleadingRows={stackWorkspaceLeadingRows}entries={stackFileEntries}- selectedFile={selectedStackFile}+ selectedFile={stackWorkspace.selectedKey}disabled={ui.saving || ui.isLoadingTemplateContent}- onSelect={openStackTab}- onCreateFile={createStackFile}- onCreateFolder={createStackFolder}- onUpload={uploadStackFile}+ onSelect={stackWorkspace.openTab}+ onCreateFile={stackWorkspace.createFile}+ onCreateFolder={stackWorkspace.createFolder}+ onUpload={(parentPath, files) => stackWorkspace.uploadFile(parentPath, files, workspaceMaxFileSizeMb)}validateName={(name) => validateWorkspaceFileName(name)}- onRename={renameStackFile}- onMove={moveStackFile}- onDelete={deleteStackFile}+ onRename={stackWorkspace.rename}+ onMove={stackWorkspace.move}+ onDelete={stackWorkspace.remove}/>{/snippet}{#snippet second()}<div class="flex h-full min-h-0 flex-1 flex-col">- <EditorTabStrip tabs={stackTabs} activeKey={activeStackTab} onSelect={openStackTab} onClose={closeStackTab}>+ <EditorTabStrip+ tabs={stackTabs}+ activeKey={activeStackTab}+ onSelect={stackWorkspace.openTab}+ onClose={stackWorkspace.closeTab}+ >{#snippet actions()}<ComposeFileEditorPaneloutlineOpen={treeOutlineOpen}@@ -575,7 +478,7 @@title={relativePath}language={workspaceFileLanguage(relativePath)}validationMode="none"- bind:value={stackFileContents[relativePath]}+ bind:value={stackWorkspace.contents[relativePath]}fileId={`swarm:stacks:${isEditMode ? initialName : 'new'}:file:${relativePath}`}editorContext={stackEditorContext}bind:outlineOpen={treeOutlineOpen}diff --git a/frontend/src/routes/(app)/swarm/tasks/+page.svelte b/frontend/src/routes/(app)/swarm/tasks/+page.svelteindex 3cb472748..0fafba59c 100644--- a/frontend/src/routes/(app)/swarm/tasks/+page.svelte+++ b/frontend/src/routes/(app)/swarm/tasks/+page.svelte@@ -3,10 +3,11 @@import { m } from '#lib/paraglide/messages';import { swarmService } from '#lib/services/swarm-service';import { untrack } from 'svelte';- import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';+ import { ResourcePageLayout, type StatCardConfig } from '#lib/layouts/index.js';import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte';- import { parallelRefresh } from '#lib/utils/api';+ import { simpleRefresh } from '#lib/utils/api';import SwarmTasksTable from './tasks-table.svelte';+ import { createRefreshActionButtons } from '#lib/utils/resource-actions';let { data } = $props();@@ -23,17 +24,11 @@}async function refresh() {- await parallelRefresh(- {- tasks: {- fetch: () => fetchTasks(requestOptions),- onSuccess: (data) => {- tasks = data;- },- errorMessage: m.common_refresh_failed({ resource: m.tasks() })- }- },- (v) => (isLoading.refresh = v)+ await simpleRefresh(+ () => fetchTasks(requestOptions),+ (data) => (tasks = data),+ m.common_refresh_failed({ resource: m.tasks() }),+ (loading) => (isLoading.refresh = loading));}@@ -41,16 +36,13 @@const totalTasks = $derived(tasks?.pagination?.totalItems ?? tasks?.data?.length ?? 0);- const actionButtons: ActionButton[] = $derived([- {- id: 'refresh',- action: 'restart',- label: m.common_refresh(),- onclick: refresh,- loading: isLoading.refresh,- disabled: isLoading.refresh- }- ]);+ const actionButtons = $derived(+ createRefreshActionButtons({+ refreshLabel: m.common_refresh(),+ onRefresh: refresh,+ refreshing: isLoading.refresh+ })+ );const statCards: StatCardConfig[] = $derived([{diff --git a/frontend/src/routes/(app)/updates/container-updates-table.svelte b/frontend/src/routes/(app)/updates/container-updates-table.svelteindex 1734d232e..fe3bd0623 100644--- a/frontend/src/routes/(app)/updates/container-updates-table.svelte+++ b/frontend/src/routes/(app)/updates/container-updates-table.svelte@@ -91,9 +91,9 @@const columns = [{ accessorKey: 'name', title: m.common_name(), sortable: true, cell: NameCell },{ accessorKey: 'imageRef', title: m.common_image(), sortable: true, cell: ImageCell },- { accessorKey: 'currentValue', title: m.common_current(), sortable: false, cell: DigestCol },- { accessorKey: 'latestValue', title: m.image_update_latest_digest_label(), sortable: false, cell: DigestCol },- { accessorKey: 'checkedAt', title: m.common_updated(), sortable: false, cell: CheckedAtCol }+ { accessorKey: 'currentValue', title: m.common_current(), sortable: false, cellComponent: DigestCell },+ { accessorKey: 'latestValue', title: m.image_update_latest_digest_label(), sortable: false, cellComponent: DigestCell },+ { accessorKey: 'checkedAt', title: m.common_updated(), sortable: false, cellComponent: CheckedAtCell }] satisfies ColumnSpec<ContainerUpdateRow>[];const mobileFields = [@@ -196,14 +196,6 @@<code class="text-xs">{item.imageRef}</code>{/snippet}-{#snippet DigestCol({ value }: { value: unknown })}- <DigestCell {value} />-{/snippet}--{#snippet CheckedAtCol({ value }: { value: unknown })}- <CheckedAtCell {value} />-{/snippet}-{#snippet RowActions({ item }: { item: ContainerUpdateRow })}<IfPermitted perm="containers:autoupdate"><RowActionsMenu>diff --git a/frontend/src/routes/(app)/updates/project-updates-table.svelte b/frontend/src/routes/(app)/updates/project-updates-table.svelteindex 5e6549c53..a05de8215 100644--- a/frontend/src/routes/(app)/updates/project-updates-table.svelte+++ b/frontend/src/routes/(app)/updates/project-updates-table.svelte@@ -98,9 +98,9 @@const columns = [{ accessorKey: 'name', title: m.common_name(), sortable: true, cell: NameCell },{ accessorKey: 'imageSummary', title: m.common_image(), sortable: false, cell: ImageCell },- { accessorKey: 'currentValue', title: m.common_current(), sortable: false, cell: DigestCol },- { accessorKey: 'latestValue', title: m.image_update_latest_digest_label(), sortable: false, cell: DigestCol },- { accessorKey: 'checkedAt', title: m.common_updated(), sortable: false, cell: CheckedAtCol }+ { accessorKey: 'currentValue', title: m.common_current(), sortable: false, cellComponent: DigestCell },+ { accessorKey: 'latestValue', title: m.image_update_latest_digest_label(), sortable: false, cellComponent: DigestCell },+ { accessorKey: 'checkedAt', title: m.common_updated(), sortable: false, cellComponent: CheckedAtCell }] satisfies ColumnSpec<ProjectUpdateRow>[];const mobileFields = [@@ -183,14 +183,6 @@</div>{/snippet}-{#snippet DigestCol({ value }: { value: unknown })}- <DigestCell {value} />-{/snippet}--{#snippet CheckedAtCol({ value }: { value: unknown })}- <CheckedAtCell {value} />-{/snippet}-{#snippet RowActions({ item }: { item: ProjectUpdateRow })}<IfPermitted perm="image-updates:check"><RowActionsMenu>diff --git a/frontend/src/routes/(auth)/login/+page.ts b/frontend/src/routes/(auth)/login/+page.tsindex c8d95d7a4..eb83a0349 100644--- a/frontend/src/routes/(auth)/login/+page.ts+++ b/frontend/src/routes/(auth)/login/+page.ts@@ -23,9 +23,7 @@ export const load = async ({ parent, url }) => {settings: data.settings,redirectTo,error,- // fallow-ignore-next-line unused-load-data-key -- rendered in the sibling page's login error alertserrorMessage,- // fallow-ignore-next-line unused-load-data-key -- rendered in the sibling page's desktop and mobile version labelsversionInformation: data.versionInformation};};diff --git a/tests/spec/docker-runtime-identity.spec.ts b/tests/spec/docker-runtime-identity.spec.tsindex 8801f4d34..cb7701990 100644--- a/tests/spec/docker-runtime-identity.spec.ts+++ b/tests/spec/docker-runtime-identity.spec.ts@@ -126,6 +126,14 @@ function cleanupNetwork(name: string) {}}+function cleanupVolume(name: string) {+ try {+ docker(['volume', 'rm', '-f', name], { stdio: 'inherit' });+ } catch {+ // ignore cleanup failures+ }+}+async function waitForHealth(container: string) {const port = dockerPort(container);expect(port).not.toBe('');@@ -269,16 +277,17 @@ test.describe.serial('Docker runtime identity', () => {test('runs as the requested UID and GID without chowning a mounted projects directory', async () => {const containerName = uniqueName('arcane-puid');- const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcane-puid-data-'));+ const dataVolume = uniqueName('arcane-puid-data');const projectsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcane-puid-projects-'));const sentinelPath = path.join(projectsDir, 'sentinel.txt');fs.writeFileSync(sentinelPath, 'sentinel\n');+ docker(['volume', 'create', dataVolume]);const baselineProjectsStat = dockerFileStat(projectsDir, '/mnt/sentinel.txt');try {dockerRunContainer([- ...defaultRunArgs(containerName, dataDir),+ ...defaultRunArgs(containerName, dataVolume),'-e','PUID=1001','-e',@@ -331,20 +340,21 @@ test.describe.serial('Docker runtime identity', () => {expect(dockerLogs(containerName)).not.toContain('/root/.docker/config.json');} finally {cleanupContainer(containerName);- cleanupDir(dataDir);+ cleanupVolume(dataVolume);cleanupDir(projectsDir);}});test('default non-root runtime prepares mounted writable roots', async () => {const containerName = uniqueName('arcane-default-nonroot');- const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcane-default-nonroot-data-'));+ const dataVolume = uniqueName('arcane-default-nonroot-data');const projectsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcane-default-nonroot-projects-'));const buildsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcane-default-nonroot-builds-'));+ docker(['volume', 'create', dataVolume]);try {dockerRunContainer([- ...defaultRunArgs(containerName, dataDir),+ ...defaultRunArgs(containerName, dataVolume),'-v','/var/run/docker.sock:/var/run/docker.sock','-v',@@ -390,7 +400,7 @@ test.describe.serial('Docker runtime identity', () => {expect(buildsWrite).toBe('65532:65532');} finally {cleanupContainer(containerName);- cleanupDir(dataDir);+ cleanupVolume(dataVolume);cleanupDir(projectsDir);cleanupDir(buildsDir);}@@ -400,7 +410,8 @@ test.describe.serial('Docker runtime identity', () => {const networkName = uniqueName('arcane-proxy-net');const proxyName = uniqueName('arcane-proxy');const containerName = uniqueName('arcane-proxy-app');- const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'arcane-proxy-data-'));+ const dataVolume = uniqueName('arcane-proxy-data');+ docker(['volume', 'create', dataVolume]);try {docker(['network', 'create', networkName], { stdio: 'inherit' });@@ -437,7 +448,7 @@ test.describe.serial('Docker runtime identity', () => {await new Promise((resolve) => setTimeout(resolve, 2_000));dockerRunContainer([- ...defaultRunArgs(containerName, dataDir),+ ...defaultRunArgs(containerName, dataVolume),'--network',networkName,'-e',@@ -478,7 +489,7 @@ test.describe.serial('Docker runtime identity', () => {cleanupContainer(containerName);cleanupContainer(proxyName);cleanupNetwork(networkName);- cleanupDir(dataDir);+ cleanupVolume(dataVolume);}});});diff --git a/tests/spec/settings-notifications.spec.ts b/tests/spec/settings-notifications.spec.tsindex ae6db0a05..9dd3f38a2 100644--- a/tests/spec/settings-notifications.spec.ts+++ b/tests/spec/settings-notifications.spec.ts@@ -6,26 +6,34 @@ test.describe('Notification settings', () => {await tab.scrollIntoViewIfNeeded();await expect(tab).toBeVisible();await tab.click();- await expect(page.getByRole('tabpanel', { name, exact: true })).toBeVisible();+ await expect(page.getByRole('tabpanel').filter({ visible: true })).toBeVisible();};const enableCurrentProvider = async (page: Page) => {- const toggle = page.getByRole('switch').first();+ const providerPanel = page.getByRole('tabpanel').filter({ visible: true });+ const toggle = providerPanel.getByRole('switch').first();await expect(toggle).toBeVisible();await toggle.click();- await expect(page.locator('[data-dropdown-menu-trigger]').last()).toBeVisible({+ await expect(providerPanel.locator('[data-dropdown-menu-trigger]')).toBeVisible({timeout: 10000});};const openTestMenu = async (page: Page) => {- const trigger = page.locator('[data-dropdown-menu-trigger]').last();+ const trigger = page+ .getByRole('tabpanel')+ .filter({ visible: true })+ .locator('[data-dropdown-menu-trigger]');await expect(trigger).toBeVisible({ timeout: 10000 });await trigger.click();};// Shared setup for all notification tests- const setupNotificationTest = async (page: Page, provider: string) => {+ const setupNotificationTest = async (+ page: Page,+ provider: string,+ options: { failProviders?: ReadonlySet<string> } = {}+ ) => {const observedErrors: string[] = [];page.on('pageerror', (err) => {@@ -40,6 +48,8 @@ test.describe('Notification settings', () => {let saveEndpointCalled = false;let testEndpointCalled = false;+ const attemptedProviders: string[] = [];+ const savedProviders: string[] = [];// Saved settings are kept in memory and served back on GET so that a// reload round-trips them through the form like the real backend would.const persistedSettings: Array<Record<string, unknown>> = [];@@ -58,6 +68,17 @@ test.describe('Notification settings', () => {if (req.method() === 'POST') {saveEndpointCalled = true;const saved = req.postDataJSON() as Record<string, unknown>;+ const savedProvider = String(saved.provider ?? '');+ attemptedProviders.push(savedProvider);+ if (options.failProviders?.has(savedProvider)) {+ await route.fulfill({+ status: 500,+ contentType: 'application/json',+ body: JSON.stringify({ error: `${savedProvider} save failed` })+ });+ return;+ }+ savedProviders.push(savedProvider);const index = persistedSettings.findIndex((s) => s.provider === saved.provider);if (index >= 0) {persistedSettings[index] = saved;@@ -98,10 +119,43 @@ test.describe('Notification settings', () => {).toHaveLength(0);},wasTestEndpointCalled: () => testEndpointCalled,- wasSaveEndpointCalled: () => saveEndpointCalled+ wasSaveEndpointCalled: () => saveEndpointCalled,+ getAttemptedProviders: () => [...attemptedProviders],+ getSavedProviders: () => [...savedProviders]};};+ test('saves only changed providers and retains failed providers as dirty', async ({ page }) => {+ const { getAttemptedProviders, getSavedProviders } = await setupNotificationTest(+ page,+ 'discord',+ {+ failProviders: new Set(['email'])+ }+ );++ await openProviderTab(page, 'Discord');+ await enableCurrentProvider(page);+ await page.getByPlaceholder('Enter webhook ID').fill('123456789');+ await page.getByPlaceholder('Enter webhook token').fill('abc-def-ghi');++ await openProviderTab(page, 'Email');+ await enableCurrentProvider(page);+ await page.getByPlaceholder('smtp.example.com').fill('smtp.example.com');+ await page.getByPlaceholder('[email protected]').fill('[email protected]');++ const saveButton = page.getByRole('button', { name: 'Save', exact: true });+ await saveButton.click();+ await expect.poll(getAttemptedProviders).toEqual(['email', 'discord']);+ await expect.poll(getSavedProviders).toEqual(['discord']);+ await expect(page.getByText(/Failed to save Email settings:/)).toBeVisible();+ await expect(saveButton).toBeEnabled();++ await saveButton.click();+ await expect.poll(getAttemptedProviders).toEqual(['email', 'discord', 'email']);+ });+test('should persist the selected provider tab in the URL', async ({ page }) => {await setupNotificationTest(page, 'discord');await expect.poll(() => new URL(page.url()).searchParams.get('tab')).toBe('email');