Skip to content

Modern Docker Management, Designed for Everyone

refactor: cleanup effect usage and use proper svelte reactivity (#3904)

Kyle Mendell5df09ed475c4
diff --git a/frontend/src/lib/components/application-theme/application-theme-picker.svelte b/frontend/src/lib/components/application-theme/application-theme-picker.svelte
index 1285df38e..65f5da6ec 100644
--- a/frontend/src/lib/components/application-theme/application-theme-picker.svelte
+++ b/frontend/src/lib/components/application-theme/application-theme-picker.svelte
@@ -1,4 +1,5 @@
<script lang="ts">
+ import { onDestroy } from 'svelte';
import * as Card from '#lib/components/ui/card/index.js';
import * as Carousel from '#lib/components/ui/carousel/index.js';
import { Label } from '#lib/components/ui/label/index.js';
@@ -77,13 +78,17 @@
hasInitializedCarouselPosition = true;
});
- $effect(() => {
- if (!carouselApi) {
+ let releaseCarouselListeners: (() => void) | undefined;
+ onDestroy(() => releaseCarouselListeners?.());
+
+ function setCarouselApi(api: CarouselAPI | undefined) {
+ releaseCarouselListeners?.();
+ releaseCarouselListeners = undefined;
+ carouselApi = api;
+ if (!api) {
return;
}
- const api = carouselApi;
-
const syncCenteredTheme = () => {
const centeredTheme = APPLICATION_THEME_OPTIONS[api.selectedScrollSnap()]?.value;
@@ -99,11 +104,11 @@
api.on('select', syncCenteredTheme);
api.on('reInit', syncCenteredTheme);
- return () => {
+ releaseCarouselListeners = () => {
api.off('select', syncCenteredTheme);
api.off('reInit', syncCenteredTheme);
};
- });
+ }
function handleThemeChange(value: string) {
if (disabled) {
@@ -119,13 +124,7 @@
<RadioGroup.Root class="space-y-3" value={selectedTheme} onValueChange={handleThemeChange}>
<div class="overflow-hidden rounded-xl border border-dashed bg-background/30 p-2 sm:p-3">
- <Carousel.Root
- class="w-full"
- opts={{ align: 'center', loop: true }}
- setApi={(api) => {
- carouselApi = api;
- }}
- >
+ <Carousel.Root class="w-full" opts={{ align: 'center', loop: true }} setApi={setCarouselApi}>
<Carousel.Content>
{#each APPLICATION_THEME_OPTIONS as theme (theme.value)}
{@const option = themeCopy[theme.value]}
diff --git a/frontend/src/lib/components/arcane-table/arcane-table.svelte b/frontend/src/lib/components/arcane-table/arcane-table.svelte
index 1f6c02032..6acb9aa69 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table.svelte
@@ -3,7 +3,7 @@
import type { ColumnFiltersState, RowSelectionState, SortingState, ColumnVisibilityState } from '@tanstack/table-core';
import { arcaneTableFeatures, type ArcaneColumnDef, type ArcaneRow, type ArcaneTable } from './table-features';
import DataTableToolbar from './arcane-table-toolbar.svelte';
- import { onMount, untrack } from 'svelte';
+ import { onDestroy, onMount, untrack } from 'svelte';
import { IsMobile } from '#lib/hooks/is-mobile.svelte.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import type { Snippet } from 'svelte';
@@ -26,13 +26,7 @@
type BulkAction
} from './arcane-table.types.svelte';
import type { Component } from 'svelte';
- import {
- extractPersistedPreferences,
- filterMapsEqual,
- fromFilterMap,
- restoreTableRequestOptions,
- toFilterMap
- } from './arcane-table.utils';
+ import { extractPersistedPreferences, fromFilterMap, restoreTableRequestOptions, toFilterMap } from './arcane-table.utils';
import ArcaneTablePagination from './arcane-table-pagination.svelte';
import ArcaneTableHeader from './arcane-table-header.svelte';
import ArcaneTableCell from './arcane-table-cell.svelte';
@@ -122,12 +116,27 @@
// Default page size constant
const DEFAULT_LIMIT = 20;
- // Table state slices owned outside the table; createTableState applies both value and
- // functional updater forms from the on[State]Change callbacks. columnVisibility is the
- // exception — parents two-way bind it, so it stays a $bindable prop.
const [rowSelection, setRowSelection] = createTableState<RowSelectionState>({});
- const [columnFilters, setColumnFilters] = createTableState<ColumnFiltersState>([]);
- const [sorting, setSorting] = createTableState<SortingState>([]);
+ const columnFilters = $derived(fromFilterMap(requestOptions?.filters));
+ const serverSort = $derived(requestOptions?.sort);
+ let clientSortOverride = $state.raw<{
+ serverSort: SearchPaginationSortRequest['sort'];
+ column?: string;
+ direction?: string;
+ sorting: SortingState;
+ } | null>(null);
+ const sorting = $derived.by((): SortingState => {
+ if (
+ clientSortOverride &&
+ clientSortOverride.serverSort === serverSort &&
+ clientSortOverride.column === serverSort?.column &&
+ clientSortOverride.direction === serverSort?.direction
+ ) {
+ return clientSortOverride.sorting;
+ }
+ if (!serverSort) return [];
+ return [{ id: serverSort.column, desc: serverSort.direction === 'desc' }];
+ });
const [globalFilter, setGlobalFilter] = createTableState<string>(requestOptions?.search ?? '');
const enablePersist = $derived(!!persistKey);
@@ -194,7 +203,7 @@
const sortedData = $derived.by(() => {
const data = items.data ?? [];
- const first = sorting()[0];
+ const first = sorting[0];
const accessor = first ? clientSortAccessors.get(String(first.id)) : undefined;
if (!first || !accessor) return data;
const direction = first.desc ? -1 : 1;
@@ -234,12 +243,15 @@
applyHiddenPatch(patchedVisibility, snapshot.hiddenColumns);
columnVisibility = patchedVisibility;
- if (snapshot.restoredFilters.length) setColumnFilters(snapshot.restoredFilters);
const effectiveSearch = (requestOptions?.search ?? '').trim() || snapshot.search;
if (effectiveSearch !== globalFilter()) setGlobalFilter(effectiveSearch);
const persistedSort = snapshot.sort;
- if (persistedSort && patchedVisibility[persistedSort.column] === false && hiddenSortFallback) {
+ if (
+ persistedSort &&
+ (patchedVisibility[persistedSort.column] ?? defaultColumnVisibility[persistedSort.column]) === false &&
+ hiddenSortFallback
+ ) {
snapshot.sort = hiddenSortFallback;
if (snapshot.sort !== persistedSort && prefs) prefs.current = { ...prefs.current, s: encodeSort(snapshot.sort) };
}
@@ -258,6 +270,7 @@
}
preferencesReady = true;
+ persistCustomSettings(customSettings);
});
function updatePagination(patch: Partial<{ page: number; limit: number }>) {
@@ -392,23 +405,14 @@
if (spec.hidden) {
const accessorKey = spec.accessorKey;
const id = spec.id ?? (accessorKey as string) ?? `col_${i}`;
- hidden[String(accessorKey ?? id)] = false;
+ hidden[id] = false;
}
});
return hidden;
}
- // Apply initial hidden columns once on mount
- let initialHiddenApplied = false;
- $effect(() => {
- if (!initialHiddenApplied && columns.length > 0) {
- const hiddenCols = getInitialHiddenColumns(columns);
- if (Object.keys(hiddenCols).length > 0) {
- columnVisibility = { ...columnVisibility, ...hiddenCols };
- }
- initialHiddenApplied = true;
- }
- });
+ const defaultColumnVisibility = $derived(getInitialHiddenColumns(columns));
+ const effectiveColumnVisibility = $derived({ ...defaultColumnVisibility, ...columnVisibility });
// Memoize column definitions until their structure or facet options change.
// Facet catalogs can arrive after the table's first render, so their metadata
@@ -447,16 +451,16 @@
},
state: {
get sorting() {
- return sorting();
+ return sorting;
},
get columnVisibility() {
- return columnVisibility;
+ return effectiveColumnVisibility;
},
get rowSelection() {
return rowSelection();
},
get columnFilters() {
- return columnFilters();
+ return columnFilters;
},
get globalFilter() {
return globalFilter();
@@ -470,13 +474,22 @@
},
onRowSelectionChange: setRowSelection,
onSortingChange: (updater) => {
- const prev = sorting();
- const wasClientSort = prev[0] && clientSortAccessors.has(String(prev[0].id));
- setSorting(updater);
- const first = sorting()[0];
- // Client-sorted columns reorder locally — no server round-trip, no persisted sort.
- if (first && clientSortAccessors.has(String(first.id))) return;
- if (!first && wasClientSort) return;
+ const wasClientSort = sorting[0] && clientSortAccessors.has(String(sorting[0].id));
+ let next: SortingState;
+ if (typeof updater === 'function') next = updater(sorting);
+ else next = updater;
+ const first = next[0];
+ // Keep client-only sorting, including its cleared state, until the server sort changes.
+ if ((first && clientSortAccessors.has(String(first.id))) || (!first && wasClientSort)) {
+ clientSortOverride = {
+ serverSort,
+ column: serverSort?.column,
+ direction: serverSort?.direction,
+ sorting: next
+ };
+ return;
+ }
+ clientSortOverride = null;
const sortState = first
? { column: String(first.id), direction: (first.desc ? 'desc' : 'asc') as 'asc' | 'desc' }
: undefined;
@@ -497,13 +510,15 @@
onRefresh(requestOptions);
},
onColumnFiltersChange: (updater) => {
- setColumnFilters(updater);
+ let next: ColumnFiltersState;
+ if (typeof updater === 'function') next = updater(columnFilters);
+ else next = updater;
if (enablePersist && prefs) {
- prefs.current = { ...prefs.current, f: encodeFilters(columnFilters()) };
+ prefs.current = { ...prefs.current, f: encodeFilters(next) };
}
requestOptions = {
...requestOptions,
- filters: toFilterMap(columnFilters()),
+ filters: toFilterMap(next),
pagination: {
page: 1,
limit: requestOptions?.pagination?.limit ?? items?.pagination?.itemsPerPage ?? 10
@@ -512,7 +527,9 @@
onRefresh(requestOptions);
},
onColumnVisibilityChange: (updater) => {
- const nextVisibility = typeof updater === 'function' ? updater(columnVisibility) : updater;
+ let nextVisibility: ColumnVisibilityState;
+ if (typeof updater === 'function') nextVisibility = updater(effectiveColumnVisibility);
+ else nextVisibility = updater;
columnVisibility = nextVisibility;
// Persist visibility
if (enablePersist && prefs) {
@@ -521,7 +538,7 @@
const activeSort = requestOptions?.sort;
if (activeSort && nextVisibility[activeSort.column] === false && hiddenSortFallback) {
- setSorting([{ id: hiddenSortFallback.column, desc: hiddenSortFallback.direction === 'desc' }]);
+ clientSortOverride = null;
requestOptions = {
...requestOptions,
sort: hiddenSortFallback,
@@ -638,70 +655,22 @@
}
}
- $effect(() => {
- const s = requestOptions?.sort;
- const currentSort = untrack(() => sorting()[0]);
-
- if (!s) {
- if (currentSort) {
- untrack(() => {
- setSorting([]);
- });
- }
- return;
- }
-
- const desc = s.direction === 'desc';
- if (!currentSort || currentSort.id !== s.column || currentSort.desc !== desc) {
- untrack(() => {
- setSorting([{ id: s.column, desc }]);
- });
- }
- });
-
- // Reflect externally-set requestOptions.filters (e.g. a clickable stat card applying
- // a filter) back into the facet UI so the displayed filters match the active query.
- // Only mutates local columnFilters — never triggers onRefresh — so it can't loop with
- // the forward onColumnFiltersChange path.
- $effect(() => {
- const incoming = requestOptions?.filters;
- const currentMap = untrack(() => toFilterMap(columnFilters()));
- if (filterMapsEqual(incoming, currentMap)) return;
- untrack(() => {
- setColumnFilters(fromFilterMap(incoming));
- });
- });
-
- // Track last persisted settings to prevent infinite loops
let lastPersistedSettings: string | null = null;
- let persistTimeout: ReturnType<typeof setTimeout> | null = null;
-
- $effect(() => {
- if (!enablePersist || !prefs) return;
+ let persistTimeout: ReturnType<typeof setTimeout> | undefined;
- // Read current settings without creating dependency on the stringified value
- const currentSettings = customSettings;
- const settingsJson = JSON.stringify(currentSettings);
-
- // Skip if unchanged
+ export function persistCustomSettings(settings: Record<string, unknown>) {
+ if (!preferencesReady || !prefs) return;
+ const settingsJson = JSON.stringify(settings);
+ clearTimeout(persistTimeout);
if (settingsJson === lastPersistedSettings) return;
-
- // Debounce persistence to prevent rapid updates
- if (persistTimeout) clearTimeout(persistTimeout);
-
+ const owner = prefs;
persistTimeout = setTimeout(() => {
- untrack(() => {
- if (prefs && settingsJson !== lastPersistedSettings) {
- lastPersistedSettings = settingsJson;
- prefs.current = { ...prefs.current, c: currentSettings };
- }
- });
+ owner.current = { ...owner.current, c: settings };
+ lastPersistedSettings = settingsJson;
}, 100);
+ }
- return () => {
- if (persistTimeout) clearTimeout(persistTimeout);
- };
- });
+ onDestroy(() => clearTimeout(persistTimeout));
// Styled/unstyled differ only in wrapper chrome; the inner table/mobile/pagination tree is shared.
const shellClass = $derived(
diff --git a/frontend/src/lib/components/backup-file-picker.svelte b/frontend/src/lib/components/backup-file-picker.svelte
index 27ffa0e0b..0b7c68746 100644
--- a/frontend/src/lib/components/backup-file-picker.svelte
+++ b/frontend/src/lib/components/backup-file-picker.svelte
@@ -1,4 +1,5 @@
<script lang="ts">
+ import { onDestroy, onMount, tick, untrack } from 'svelte';
import { tryCatch } from '#lib/utils/try-catch.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
@@ -36,11 +37,10 @@
let pages = $state<Record<string, FolderPageState>>({});
let expandedFolders = $state<Set<string>>(new Set());
let selectedDirectoryPaths = $state<Set<string>>(new Set());
- let debouncedSearch = $state('');
- let selectionSearch = $state('');
- let generation = $state(0);
+ let debouncedSearch = $state(untrack(() => search.trim()));
+ let generation = 0;
+ let searchTimeout: ReturnType<typeof setTimeout> | undefined;
let nextRequestID = 0;
- let initializedProvider: BackupFileProvider | null = null;
let scrollElement = $state<HTMLElement | null>(null);
const selectedSet = $derived(new Set(selectedPaths));
@@ -63,7 +63,10 @@
return row?.kind === 'entry' ? `entry:${row.entry.path}` : `continuation:${row?.folder ?? ''}`;
},
estimateSize: () => 34,
- overscan: 8
+ overscan: 8,
+ onChange: (instance) => {
+ loadVisibleContinuationsInternal(instance.getVirtualItems().map((item) => item.index));
+ }
}));
function pageStateInternal(folder: string): FolderPageState {
@@ -132,20 +135,30 @@
const latest = pages[folder];
if (generation !== requestGeneration || latest?.requestID !== requestID) return;
updatePageInternal(folder, { ...latest, loading: false, error: true });
+ return;
+ }
+ await tick();
+ if (generation === requestGeneration) {
+ loadVisibleContinuationsInternal(rowVirtualizer.virtualItems.map((item) => item.index));
}
}
- function toggleFolderInternal(folder: string) {
+ async function toggleFolderInternal(folder: string) {
if (searchActive) return;
+ const requestGeneration = generation;
const next = new Set(expandedFolders);
if (next.has(folder)) {
next.delete(folder);
expandedFolders = next;
- return;
+ } else {
+ next.add(folder);
+ expandedFolders = next;
+ if (!pages[folder]) void loadPageInternal(folder, 0, true);
+ }
+ await tick();
+ if (generation === requestGeneration) {
+ loadVisibleContinuationsInternal(rowVirtualizer.virtualItems.map((item) => item.index));
}
- next.add(folder);
- expandedFolders = next;
- if (!pages[folder]) void loadPageInternal(folder, 0, true);
}
function coveringAncestorInternal(entryPath: string): string | undefined {
@@ -187,59 +200,48 @@
function selectAllInternal() {
selectedPaths = [];
selectAll = true;
- selectionSearch = search.trim();
}
function clearSelectionInternal() {
selectedPaths = [];
selectAll = false;
- selectionSearch = '';
}
- // A new provider means a new backup tree: the picker owns clearing its
- // selection and search state so every parent dialog doesn't have to.
- $effect(() => {
- const currentProvider = provider;
- if (initializedProvider === currentProvider) return;
- initializedProvider = currentProvider;
- selectedPaths = [];
- selectAll = false;
- selectionSearch = '';
- selectedDirectoryPaths = new Set();
- search = '';
- debouncedSearch = '';
- resetPagesInternal();
+ onMount(() => {
+ void loadPageInternal('', 0, true);
+ });
+ onDestroy(() => {
+ generation += 1;
+ clearTimeout(searchTimeout);
});
- $effect(() => {
- const query = search.trim();
- if (selectAll && query !== selectionSearch) {
- selectAll = false;
- selectionSearch = '';
- }
+ function updateSearchInternal(value: string) {
+ const query = value.trim();
+ if (selectAll && query !== search.trim()) selectAll = false;
+ search = value;
+ clearTimeout(searchTimeout);
if (query === debouncedSearch) return;
- const timeout = window.setTimeout(() => {
+ searchTimeout = setTimeout(() => {
debouncedSearch = query;
resetPagesInternal();
}, 250);
- return () => window.clearTimeout(timeout);
- });
+ }
- $effect(() => {
- for (const virtualItem of rowVirtualizer.virtualItems) {
- const row = rows[virtualItem.index];
+ function loadVisibleContinuationsInternal(indices: number[]) {
+ for (const index of indices) {
+ const row = rows[index];
if (row?.kind !== 'continuation') continue;
const state = pages[row.folder];
if (state?.continuationStart !== undefined && !state.loading && !state.error) {
void loadPageInternal(row.folder, state.continuationStart, false);
}
}
- });
+ }
</script>
<div class="space-y-3">
<div class="flex items-center justify-between gap-2">
- <Input class="h-9" placeholder={m.volume_search_files()} bind:value={search} />
+ <Input class="h-9" placeholder={m.volume_search_files()} bind:value={() => search, updateSearchInternal} />
<div class="flex items-center gap-2">
<ArcaneButton
action="base"
diff --git a/frontend/src/lib/components/backup-policy-dialog.svelte b/frontend/src/lib/components/backup-policy-dialog.svelte
index d5d47c84c..96b8e74df 100644
--- a/frontend/src/lib/components/backup-policy-dialog.svelte
+++ b/frontend/src/lib/components/backup-policy-dialog.svelte
@@ -1,7 +1,7 @@
<script lang="ts" generics="TPolicy extends BackupPolicy, TUpdate extends { id: string } = BackupPolicyUpdate">
import { tryCatch } from '#lib/utils/try-catch.js';
- import { untrack, type Snippet } from 'svelte';
+ import { onMount, untrack, type Snippet } from 'svelte';
import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog/index.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import BackupPolicyFields from '#lib/components/backup-policy-fields.svelte';
@@ -27,7 +27,6 @@
defaultEnabled = true,
showStopContainers = false,
destinations,
- resetKey,
beforeFields,
afterFields,
policyPayload = (policy) => backupPolicyUpdateFromPolicy(policy, showStopContainers) as unknown as TUpdate,
@@ -35,7 +34,6 @@
updatePolicies,
messages,
onSaved,
- onReset,
contentClass = 'sm:max-w-[720px]'
}: {
open: boolean;
@@ -50,7 +48,6 @@
defaultEnabled?: boolean;
showStopContainers?: boolean;
destinations?: S3Destination[];
- resetKey?: string;
beforeFields?: Snippet;
afterFields?: Snippet;
policyPayload?: (policy: TPolicy) => TUpdate;
@@ -58,7 +55,6 @@
updatePolicies: (policies: TUpdate[]) => Promise<TPolicy[]>;
messages: { saved: string; saveFailed: string; removed: string };
onSaved: (policies: TPolicy[]) => void;
- onReset?: (policy?: TPolicy) => void;
contentClass?: string;
} = $props();
@@ -66,7 +62,23 @@
let deleting = $state(false);
let loadedDestinations = $state<S3Destination[]>([]);
let destinationsLoading = $state(false);
- let form = $state<PolicyForm>(newPolicy());
+ const initialPolicy = untrack(() => policies.find((item) => item.id === policyId));
+ let initialForm: PolicyForm;
+ if (initialPolicy) {
+ initialForm = {
+ id: initialPolicy.id,
+ enabled: initialPolicy.enabled,
+ schedule: initialPolicy.schedule,
+ retentionCount: initialPolicy.retentionCount,
+ stopContainers: initialPolicy.stopContainers ?? false,
+ s3DestinationId: initialPolicy.s3DestinationId || '',
+ destination: backupDestinationFromFlags(initialPolicy.localEnabled, initialPolicy.s3Enabled)
+ };
+ } else {
+ initialForm = newPolicy();
+ }
+ let form = $state<PolicyForm>(initialForm);
+
const destinationList = $derived(destinations ?? loadedDestinations);
const scheduleError = $derived(
!form.schedule.trim()
@@ -120,25 +132,8 @@
}
}
- $effect(() => {
- if (!open) return;
- resetKey;
- untrack(() => {
- const policy = policies.find((item) => item.id === policyId);
- form = policy
- ? {
- id: policy.id,
- enabled: policy.enabled,
- schedule: policy.schedule,
- retentionCount: policy.retentionCount,
- stopContainers: policy.stopContainers ?? false,
- s3DestinationId: policy.s3DestinationId || '',
- destination: backupDestinationFromFlags(policy.localEnabled, policy.s3Enabled)
- }
- : newPolicy();
- onReset?.(policy);
- if (!destinations) void loadDestinations();
- });
+ onMount(() => {
+ if (!destinations) void loadDestinations();
});
function updateForm(values: Partial<BackupPolicyForm>) {
diff --git a/frontend/src/lib/components/confirm-dialog/confirm-dialog.svelte b/frontend/src/lib/components/confirm-dialog/confirm-dialog.svelte
index 398b030bd..4a4f5bdc2 100644
--- a/frontend/src/lib/components/confirm-dialog/confirm-dialog.svelte
+++ b/frontend/src/lib/components/confirm-dialog/confirm-dialog.svelte
@@ -9,23 +9,9 @@
import { m } from '#lib/paraglide/messages.js';
import { toast } from 'svelte-sonner';
- let checkboxStates = $state<Record<string, boolean>>({});
-
- $effect(() => {
- if ($confirmDialogStore.open && $confirmDialogStore.checkboxes) {
- const newStates: Record<string, boolean> = {};
-
- for (const checkbox of $confirmDialogStore.checkboxes) {
- newStates[checkbox.id] = Boolean(checkbox.initialState);
- }
-
- checkboxStates = newStates;
- }
- });
-
async function handleConfirm() {
const action = $confirmDialogStore.confirm.action;
- const states = $state.snapshot(checkboxStates);
+ const states = $state.snapshot($confirmDialogStore.checkboxStates);
$confirmDialogStore.open = false;
// Keep synchronous action failures inside the promise boundary.
const result = await tryCatch(Promise.resolve().then(() => action(states)));
@@ -58,10 +44,10 @@
<div class="mt-6 flex flex-col gap-4 border-t border-border pt-4">
{#each $confirmDialogStore.checkboxes as checkbox (checkbox.id)}
<div class="flex items-start space-x-3">
- {#if checkboxStates[checkbox.id] !== undefined}
+ {#if $confirmDialogStore.checkboxStates[checkbox.id] !== undefined}
<Checkbox
id={checkbox.id}
- bind:checked={checkboxStates[checkbox.id]}
+ bind:checked={$confirmDialogStore.checkboxStates[checkbox.id]}
aria-labelledby={`${checkbox.id}-label`}
class="mt-0.5"
/>
@@ -69,7 +55,7 @@
<Checkbox
id={checkbox.id}
checked={false}
- onchange={() => (checkboxStates[checkbox.id] = true)}
+ onchange={() => ($confirmDialogStore.checkboxStates[checkbox.id] = true)}
aria-labelledby={`${checkbox.id}-label`}
class="mt-0.5"
/>
@@ -84,7 +70,7 @@
{checkbox.label}
</Label>
- {#if checkbox.id === 'files' && checkboxStates[checkbox.id]}
+ {#if checkbox.id === 'files' && $confirmDialogStore.checkboxStates[checkbox.id]}
<div class="mt-1 text-xs leading-snug text-destructive">{m.confirm_remove_project_files_warning()}</div>
{/if}
</div>
diff --git a/frontend/src/lib/components/confirm-dialog/store.ts b/frontend/src/lib/components/confirm-dialog/store.ts
index 975aa2809..7e3b2afe5 100644
--- a/frontend/src/lib/components/confirm-dialog/store.ts
+++ b/frontend/src/lib/components/confirm-dialog/store.ts
@@ -2,8 +2,9 @@ import { writable } from 'svelte/store';
import { m } from '#lib/paraglide/messages.js';
import type { ConfirmDialogOptions } from '#lib/types/confirm-dialog.js';
-export const confirmDialogStore = writable<ConfirmDialogOptions & { open: boolean }>({
+export const confirmDialogStore = writable<ConfirmDialogOptions & { open: boolean; checkboxStates: Record<string, boolean> }>({
open: false,
+ checkboxStates: {},
title: '',
message: '',
confirm: {
@@ -16,6 +17,7 @@ export const confirmDialogStore = writable<ConfirmDialogOptions & { open: boolea
export function openConfirmDialog({ title, message, confirm, checkboxes }: ConfirmDialogOptions) {
confirmDialogStore.update(() => ({
open: true,
+ checkboxStates: Object.fromEntries((checkboxes ?? []).map((checkbox) => [checkbox.id, Boolean(checkbox.initialState)])),
title,
message,
confirm: {
diff --git a/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte b/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte
index 0a70bd941..273f763d8 100644
--- a/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte
@@ -76,7 +76,7 @@
try {
const requestResult1 = await tryCatch(
(async () => {
- const result = await queryClient.fetchQuery({
+ const result = await queryClient.query({
queryKey: queryKeys.environments.switcher(options),
queryFn: () => environmentManagementService.getEnvironments(options),
staleTime: 0
diff --git a/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelte b/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelte
index da3293ff0..ebeef4146 100644
--- a/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelte
@@ -1,4 +1,5 @@
<script lang="ts">
+ import { untrack } from 'svelte';
import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog/index.js';
import { Button } from '#lib/components/ui/button/index.js';
import FormInput from '#lib/components/form/form-input.svelte';
@@ -70,7 +71,12 @@
const composeFileFilter = (file: FileTreeNode) =>
file.type === 'file' && (file.name.endsWith('.yml') || file.name.endsWith('.yaml'));
- let selectedTargetType = $state<GitOpsSyncTargetType>('project');
+ let selectedTargetType = $state<GitOpsSyncTargetType>(untrack(() => normalizeTargetType(syncToEdit?.targetType ?? targetType)));
+
+ const defaultComposePath = $derived.by(() => {
+ if (selectedTargetType === 'swarm_stack') return 'compose.yml';
+ return 'docker-compose.yml';
+ });
const targetTypeOptions = [
{ value: 'project', label: m.project() },
@@ -113,47 +119,63 @@
return value * bytesPerMegabyte;
}
- const settingsQuery = createQuery(() => ({
- queryKey: queryKeys.settings.byEnvironment(environmentId),
- queryFn: () => settingsService.getSettingsForEnvironmentMerged(environmentId),
- enabled: open,
- staleTime: 0,
- refetchOnMount: 'always'
- }));
+ const settingsQuery = createQuery(() => {
+ const requestEnvironmentId = environmentId;
+ return {
+ queryKey: queryKeys.settings.byEnvironment(requestEnvironmentId),
+ queryFn: () => settingsService.getSettingsForEnvironmentMerged(requestEnvironmentId),
+ enabled: open,
+ staleTime: 0,
+ refetchOnMount: 'always'
+ };
+ });
const lifecycleEnabled = $derived(settingsQuery.data?.lifecycleEnabled ?? false);
const lifecycleDefaultRunnerImage = $derived(settingsQuery.data?.lifecycleDefaultRunnerImage?.trim() || 'alpine:latest');
- let formData = $derived({
- name: open && syncToEdit ? syncToEdit.name : '',
- repositoryId: open && syncToEdit ? syncToEdit.repositoryId : '',
- branch: open && syncToEdit ? syncToEdit.branch : 'main',
- composePath:
- open && syncToEdit ? syncToEdit.composePath : selectedTargetType === 'swarm_stack' ? 'compose.yml' : 'docker-compose.yml',
- syncDirectory: open && syncToEdit ? (syncToEdit.syncDirectory ?? false) : false,
- pullImageAfterSync: open && syncToEdit ? (syncToEdit.pullImageAfterSync ?? false) : false,
- redeployAfterSync: open && syncToEdit ? (syncToEdit.redeployAfterSync ?? false) : false,
- maxSyncFiles: open && syncToEdit ? (syncToEdit.maxSyncFiles ?? 0) : (settingsQuery.data?.gitSyncMaxFiles ?? 0),
- maxSyncTotalSizeMb:
- open && syncToEdit
- ? bytesToMegabytesInternal(syncToEdit.maxSyncTotalSize, 0)
- : (settingsQuery.data?.gitSyncMaxTotalSizeMb ?? 0),
- maxSyncBinarySizeMb:
- open && syncToEdit
- ? bytesToMegabytesInternal(syncToEdit.maxSyncBinarySize, 0)
- : (settingsQuery.data?.gitSyncMaxBinarySizeMb ?? 0),
- autoSync: open && syncToEdit ? (syncToEdit.autoSync ?? true) : true,
- syncInterval: open && syncToEdit ? (syncToEdit.syncInterval ?? 5) : 5,
- preDeployScriptPath: open && syncToEdit ? (syncToEdit.preDeployScriptPath ?? '') : '',
- preDeployRunnerImage: open && syncToEdit ? (syncToEdit.preDeployRunnerImage ?? '') : lifecycleDefaultRunnerImage,
- preDeployTimeoutSec: open && syncToEdit ? (syncToEdit.preDeployTimeoutSec ?? 60) : 60,
- preDeployNetworkMode: open && syncToEdit ? (syncToEdit.preDeployNetworkMode ?? 'none') : 'none',
- preDeployEnv: open && syncToEdit ? (syncToEdit.preDeployEnv ?? '') : '',
- preDeployExtraMounts: open && syncToEdit ? (syncToEdit.preDeployExtraMounts ?? '') : ''
+ const formData = $derived.by(() => {
+ // New drafts use the first settings response; later refreshes preserve edits.
+ if (!untrack(() => isEditMode)) settingsQuery.isFetchedAfterMount;
+ return untrack(() => {
+ let maxSyncFiles = settingsQuery.data?.gitSyncMaxFiles ?? 0;
+ let maxSyncTotalSizeMb = settingsQuery.data?.gitSyncMaxTotalSizeMb ?? 0;
+ let maxSyncBinarySizeMb = settingsQuery.data?.gitSyncMaxBinarySizeMb ?? 0;
+ let preDeployRunnerImage = lifecycleDefaultRunnerImage;
+ if (syncToEdit) {
+ maxSyncFiles = syncToEdit.maxSyncFiles ?? 0;
+ maxSyncTotalSizeMb = bytesToMegabytesInternal(syncToEdit.maxSyncTotalSize, 0);
+ maxSyncBinarySizeMb = bytesToMegabytesInternal(syncToEdit.maxSyncBinarySize, 0);
+ preDeployRunnerImage = syncToEdit.preDeployRunnerImage ?? '';
+ }
+ return {
+ name: syncToEdit?.name ?? '',
+ repositoryId: syncToEdit?.repositoryId ?? '',
+ branch: syncToEdit?.branch ?? 'main',
+ composePath: syncToEdit?.composePath ?? defaultComposePath,
+ syncDirectory: syncToEdit?.syncDirectory ?? false,
+ pullImageAfterSync: syncToEdit?.pullImageAfterSync ?? false,
+ redeployAfterSync: syncToEdit?.redeployAfterSync ?? false,
+ maxSyncFiles,
+ maxSyncTotalSizeMb,
+ maxSyncBinarySizeMb,
+ autoSync: syncToEdit?.autoSync ?? true,
+ syncInterval: syncToEdit?.syncInterval ?? 5,
+ preDeployScriptPath: syncToEdit?.preDeployScriptPath ?? '',
+ preDeployRunnerImage,
+ preDeployTimeoutSec: syncToEdit?.preDeployTimeoutSec ?? 60,
+ preDeployNetworkMode: syncToEdit?.preDeployNetworkMode ?? 'none',
+ preDeployEnv: syncToEdit?.preDeployEnv ?? '',
+ preDeployExtraMounts: syncToEdit?.preDeployExtraMounts ?? ''
+ };
+ });
});
let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
- let selectedRepository = $state<{ value: string; label: string } | undefined>(undefined);
+ const selectedRepository = $derived.by(() => {
+ const repository = repositories.find((item) => item.id === $inputs.repositoryId.value);
+ if (!repository) return undefined;
+ return { value: repository.id, label: repository.name };
+ });
const repositoriesQuery = createQuery(() => ({
queryKey: queryKeys.gitRepositories.syncDialog(),
queryFn: () => gitRepositoryService.getRepositories({ pagination: { page: 1, limit: 100 } }),
@@ -164,12 +186,15 @@
const loadingSettings = $derived(!isEditMode && (settingsQuery.isPending || settingsQuery.isFetching));
const loadingData = $derived(repositoriesQuery.isPending || repositoriesQuery.isFetching || loadingSettings);
- const branchesQuery = createQuery(() => ({
- queryKey: queryKeys.gitRepositories.branches(selectedRepository?.value || ''),
- queryFn: () => gitRepositoryService.getBranches(selectedRepository?.value || ''),
- enabled: open && !!selectedRepository?.value,
- staleTime: 0
- }));
+ const branchesQuery = createQuery(() => {
+ const repositoryId = selectedRepository?.value || '';
+ return {
+ queryKey: queryKeys.gitRepositories.branches(repositoryId),
+ queryFn: () => gitRepositoryService.getBranches(repositoryId),
+ enabled: open && !!repositoryId,
+ staleTime: 0
+ };
+ });
const branches = $derived<BranchInfo[]>(branchesQuery.data?.branches ?? []);
const loadingBranches = $derived(!!selectedRepository?.value && (branchesQuery.isPending || branchesQuery.isFetching));
@@ -213,35 +238,13 @@
);
}
- $effect(() => {
- if (open) {
- selectedRepository = undefined;
- showFileBrowser = false;
- selectedTargetType = isEditMode ? normalizeTargetType(syncToEdit?.targetType) : normalizeTargetType(targetType);
- if (!isEditMode) {
- form.reset();
- }
- }
- });
-
- $effect(() => {
- if (!open || !syncToEdit || repositories.length === 0 || selectedRepository) return;
- const repo = repositories.find((r) => r.id === syncToEdit.repositoryId);
- if (repo) {
- selectedRepository = { value: repo.id, label: repo.name };
- $inputs.repositoryId.value = repo.id;
- }
- });
-
- $effect(() => {
- if (!open || isEditMode || branches.length === 0) return;
- const defaultBranch = branches.find((b) => b.isDefault);
- if (defaultBranch && !$inputs.branch.value) {
- $inputs.branch.value = defaultBranch.name;
- }
+ const selectedBranch = $derived.by(() => {
+ if ($inputs.branch.value || isEditMode) return $inputs.branch.value;
+ return branches.find((branch) => branch.isDefault)?.name ?? '';
});
function handleSubmit() {
+ $inputs.branch.value = selectedBranch;
const data = form.validate();
if (!data) return;
@@ -284,7 +287,7 @@
fileBrowserTarget = target;
showFileBrowser = true;
}}
- disabled={!selectedRepository?.value || !$inputs.branch.value}
+ disabled={!selectedRepository?.value || !selectedBranch}
title={m.git_sync_browse_files_title()}
>
<FolderOpenIcon class="size-4" />
@@ -318,7 +321,13 @@
label={m.target_type()}
value={selectedTargetType}
options={targetTypeOptions}
- onValueChange={(value) => (selectedTargetType = value as GitOpsSyncTargetType)}
+ onValueChange={(value) => {
+ const previousDefault = defaultComposePath;
+ selectedTargetType = value as GitOpsSyncTargetType;
+ if ($inputs.composePath.value === previousDefault) {
+ $inputs.composePath.value = defaultComposePath;
+ }
+ }}
/>
</div>
@@ -332,7 +341,6 @@
if (v) {
const repo = repositories.find((r) => r.id === v);
if (repo) {
- selectedRepository = { value: repo.id, label: repo.name };
$inputs.repositoryId.value = v;
}
}
@@ -362,7 +370,7 @@
{:else if branches.length > 0}
<Select.Root
type="single"
- value={$inputs.branch.value}
+ value={selectedBranch}
onValueChange={(v) => {
if (v) {
$inputs.branch.value = v;
@@ -370,7 +378,7 @@
}}
>
<Select.Trigger id="branch" class="w-full" aria-invalid={$inputs.branch.error ? 'true' : undefined}>
- <span>{$inputs.branch.value || m.common_select_placeholder()}</span>
+ <span>{selectedBranch || m.common_select_placeholder()}</span>
</Select.Trigger>
<Select.Content style="width: var(--bits-select-anchor-width);">
{#each branches as branch (branch.name)}
@@ -689,7 +697,7 @@
<FileBrowserDialog
bind:open={showFileBrowser}
repositoryId={selectedRepository?.value || ''}
- branch={$inputs.branch.value}
+ branch={selectedBranch}
description={fileBrowserTarget === 'preDeployScript'
? m.git_sync_browse_files_description_script()
: m.git_sync_browse_files_description()}
diff --git a/frontend/src/lib/components/dialogs/update-center-dialog.svelte b/frontend/src/lib/components/dialogs/update-center-dialog.svelte
index d37214f3e..a29216129 100644
--- a/frontend/src/lib/components/dialogs/update-center-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/update-center-dialog.svelte
@@ -323,7 +323,7 @@
async function captureBaseline() {
const requestResult2 = await tryCatch(
(async () => {
- baselineVersionInfo = await queryClient.fetchQuery({
+ baselineVersionInfo = await queryClient.query({
queryKey: queryKeys.system.versionInfo(environmentId ?? '0'),
queryFn: () => systemUpgradeService.getVersionInfo(environmentId ?? '0'),
staleTime: 0
diff --git a/frontend/src/lib/components/form/mobile-floating-form-actions.svelte b/frontend/src/lib/components/form/mobile-floating-form-actions.svelte
index b901e78a7..c1f5b3d16 100644
--- a/frontend/src/lib/components/form/mobile-floating-form-actions.svelte
+++ b/frontend/src/lib/components/form/mobile-floating-form-actions.svelte
@@ -1,6 +1,6 @@
<script lang="ts">
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
- import { getEffectiveNavigationSettings } from '#lib/utils/navigation.js';
+ import { getMobileNavigation } from '#lib/utils/navigation.js';
import { IsMobile } from '#lib/hooks/is-mobile.svelte.js';
import { IsTablet } from '#lib/hooks/is-tablet.svelte.js';
import { cn } from '#lib/utils.js';
@@ -16,84 +16,16 @@
const isMobile = new IsMobile();
const isTablet = new IsTablet();
- const navigationSettings = $derived(getEffectiveNavigationSettings());
+ const navigation = getMobileNavigation();
+ const navigationSettings = $derived(navigation.settings);
const navigationMode = $derived(navigationSettings.mode);
const scrollToHideEnabled = $derived(navigationSettings.scrollToHide);
-
- // Track mobile nav visibility for FAB positioning
- let mobileNavVisible = $state(true);
-
- // Monitor mobile nav visibility when scroll-to-hide is enabled
- $effect(() => {
- if (typeof window === 'undefined') return;
- if (!scrollToHideEnabled || !(isMobile.current || isTablet.current)) {
- mobileNavVisible = true;
- return;
- }
-
- // Check the mobile nav element's transform to determine visibility
- const checkNavVisibility = () => {
- const navElement = document.querySelector('[data-testid="mobile-floating-nav"], [data-testid="mobile-docked-nav"]');
- if (!navElement) {
- mobileNavVisible = true;
- return;
- }
-
- const style = window.getComputedStyle(navElement);
- const transform = style.transform;
- const opacity = parseFloat(style.opacity);
-
- // Check if nav is translated away or has low opacity
- if (transform !== 'none' && transform.includes('matrix')) {
- const matrix = transform.match(/matrix.*\((.+)\)/);
- if (matrix) {
- const rawValues = matrix[1];
- if (rawValues) {
- const values = rawValues.split(', ');
- const translateY = parseFloat(values[5] ?? '0');
- // If translateY is positive (moved down), nav is hidden
- mobileNavVisible = translateY === 0 && opacity > 0.5;
- } else {
- mobileNavVisible = opacity > 0.5;
- }
- }
- } else {
- mobileNavVisible = opacity > 0.5;
- }
- };
-
- // Initial check
- checkNavVisibility();
-
- // Use MutationObserver to watch for style changes on nav
- const observer = new MutationObserver(checkNavVisibility);
- const navElement = document.querySelector('[data-testid="mobile-floating-nav"], [data-testid="mobile-docked-nav"]');
-
- if (navElement) {
- observer.observe(navElement, {
- attributes: true,
- attributeFilter: ['style', 'class']
- });
- }
-
- // Also check on scroll as a fallback
- const handleScroll = () => {
- requestAnimationFrame(checkNavVisibility);
- };
-
- window.addEventListener('scroll', handleScroll, { passive: true });
-
- return () => {
- observer.disconnect();
- window.removeEventListener('scroll', handleScroll);
- };
- });
</script>
{#if isMobile.current || isTablet.current}
<div
class="fixed right-4 z-[var(--arcane-z-app-chrome)] flex flex-col gap-3 transition-[bottom] duration-300 ease-out sm:hidden"
- style="bottom: {scrollToHideEnabled && !mobileNavVisible
+ style="bottom: {scrollToHideEnabled && !navigation.visible
? '1rem'
: 'calc(var(--mobile-' +
navigationMode +
diff --git a/frontend/src/lib/components/form/searchable-select.svelte b/frontend/src/lib/components/form/searchable-select.svelte
index ce6fe622f..ed36d7eb2 100644
--- a/frontend/src/lib/components/form/searchable-select.svelte
+++ b/frontend/src/lib/components/form/searchable-select.svelte
@@ -71,7 +71,12 @@
} = $props();
let open = $state(false);
- let filteredItems = $state<SearchableSelectItem[]>([]);
+ let searchText = $state('');
+ const filteredItems = $derived.by(() => {
+ if (disableSearch || !searchText) return items;
+ const search = searchText.toLowerCase();
+ return items.filter((item) => item.label.toLowerCase().includes(search));
+ });
const resolvedLabel = $derived.by(() => {
if (displayText) return displayText;
@@ -114,27 +119,17 @@
document.getElementById(triggerId)?.focus();
});
}
+</script>
- function filterItems(searchString: string) {
- if (!searchString) {
- filteredItems = items;
- return;
+<Popover.Root
+ bind:open={
+ () => open,
+ (value) => {
+ open = value;
+ if (value) searchText = '';
}
- filteredItems = items.filter((item) => item.label.toLowerCase().includes(searchString.toLowerCase()));
}
-
- $effect(() => {
- filteredItems = items;
- });
-
- $effect(() => {
- if (open) {
- filteredItems = items;
- }
- });
-</script>
-
-<Popover.Root bind:open>
+>
<Popover.Trigger>
{#snippet child({ props })}
<ArcaneButton
@@ -166,14 +161,7 @@
>
<Command.Root shouldFilter={false} class={cn('rounded-none bg-transparent', commandClass)}>
{#if !disableSearch}
- <Command.Input
- placeholder={m.common_search()}
- class={cn(inputClass)}
- oninput={(e) => {
- filterItems(e.currentTarget.value);
- oninput?.(e);
- }}
- />
+ <Command.Input placeholder={m.common_search()} class={cn(inputClass)} bind:value={searchText} {oninput} />
{/if}
<Command.Empty>
{#if isLoading}
diff --git a/frontend/src/lib/components/image-update-item.svelte b/frontend/src/lib/components/image-update-item.svelte
index 80eec3baa..f84cc7469 100644
--- a/frontend/src/lib/components/image-update-item.svelte
+++ b/frontend/src/lib/components/image-update-item.svelte
@@ -4,7 +4,7 @@
import { Spinner } from '#lib/components/ui/spinner/index.js';
import { Badge, type BadgeVariant } from '#lib/components/ui/badge/index.js';
import { toast } from 'svelte-sonner';
- import type { ImageUpdateData } from '#lib/types/docker.js';
+ import type { ImageUpdateData, ImageUpdateInfoDto } from '#lib/types/docker.js';
import { m } from '#lib/paraglide/messages.js';
import { imageService } from '#lib/services/image-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
@@ -66,30 +66,36 @@
return instantEpochMilliseconds(info.checkTime) ?? 0;
}
- const imageUpdateQuery = createQuery<ImageUpdateData>(() => ({
- queryKey: queryKeys.images.updateCheck(
- environmentStore.selected?.id || '0',
- containerId ? `container:${containerId}` : imageId || imageRef || ''
- ),
- queryFn: async () => {
- const result =
- imageId && !(containerId && imageRef)
- ? await imageService.checkImageUpdateByID(imageId)
- : (await imageService.checkMultipleImages([imageRef ?? '']))[imageRef ?? ''];
- if (!result) throw new Error(m.images_update_check_failed());
- if (containerId) {
- if (tagUpdates) {
- const scopedResult = result.containerUpdates?.[containerId];
- if (!scopedResult) throw new Error(result.error || m.images_update_check_failed());
- return { ...scopedResult, activityId: scopedResult.activityId ?? result.activityId };
+ const imageUpdateQuery = createQuery<ImageUpdateData>(() => {
+ const environmentId = environmentStore.selected?.id || '0';
+ const target = { imageId, containerId, imageRef, tagUpdates };
+ let key = target.imageId || target.imageRef || '';
+ if (target.containerId) key = `container:${target.containerId}`;
+ return {
+ queryKey: queryKeys.images.updateCheck(environmentId, key),
+ queryFn: async () => {
+ let result: ImageUpdateInfoDto | undefined;
+ if (target.imageId && !(target.containerId && target.imageRef)) {
+ result = await imageService.checkImageUpdateByID(target.imageId);
+ } else {
+ const ref = target.imageRef ?? '';
+ result = (await imageService.checkMultipleImages([ref]))[ref];
+ }
+ if (!result) throw new Error(m.images_update_check_failed());
+ if (target.containerId) {
+ if (target.tagUpdates) {
+ const scopedResult = result.containerUpdates?.[target.containerId];
+ if (!scopedResult) throw new Error(result.error || m.images_update_check_failed());
+ return { ...scopedResult, activityId: scopedResult.activityId ?? result.activityId };
+ }
+ return result.imageUpdate ?? result;
}
- return result.imageUpdate ?? result;
- }
- return result;
- },
- enabled: false,
- retry: false
- }));
+ return result;
+ },
+ enabled: false,
+ retry: false
+ };
+ });
const errorFromQuery = $derived.by((): ImageUpdateData | undefined => {
if (!imageUpdateQuery.error) return undefined;
diff --git a/frontend/src/lib/components/logs/log-controls.svelte b/frontend/src/lib/components/logs/log-controls.svelte
index 254180bd7..b0f2bce2b 100644
--- a/frontend/src/lib/components/logs/log-controls.svelte
+++ b/frontend/src/lib/components/logs/log-controls.svelte
@@ -7,14 +7,12 @@
import * as Select from '#lib/components/ui/select/index.js';
import { Input } from '#lib/components/ui/input/index.js';
import { m } from '#lib/paraglide/messages.js';
- import { PersistedState } from 'runed';
+ import type { UseLogPreferences } from '#lib/hooks/use-log-preferences.svelte.js';
let {
autoScroll = $bindable(),
- tailLines = $bindable(100),
- autoStartLogs = $bindable(false),
+ preferences,
searchTerm = $bindable(''),
- showParsedJson = $bindable(false),
mobileLayout = 'full',
showDesktop = true,
isStreaming = false,
@@ -24,10 +22,8 @@
onRefresh
}: {
autoScroll: boolean;
- tailLines?: number;
- autoStartLogs?: boolean;
+ preferences: UseLogPreferences;
searchTerm?: string;
- showParsedJson?: boolean;
mobileLayout?: 'full' | 'menu-only' | 'actions-only' | 'none';
showDesktop?: boolean;
isStreaming?: boolean;
@@ -46,39 +42,14 @@
{ value: 'all', label: m.log_tail_all_lines() }
];
- const persistedTailLines = new PersistedState('arcane_log_tail_lines', '100');
- const persistedAutoStart = new PersistedState('arcane_log_auto_start', 'false');
- const persistedJsonParsing = new PersistedState('arcane_log_json_parsing_v3', 'false');
-
- let selectedTail = $state<string>(persistedTailLines.current || (tailLines >= 999999 ? 'all' : String(tailLines)));
-
- $effect(() => {
- persistedTailLines.current = selectedTail;
- if (selectedTail === 'all') {
- tailLines = 999999;
- } else {
- tailLines = parseInt(selectedTail, 10);
- }
- });
-
- $effect(() => {
- autoStartLogs = persistedAutoStart.current === 'true';
- });
-
- $effect(() => {
- persistedAutoStart.current = autoStartLogs ? 'true' : 'false';
- });
-
- $effect(() => {
- showParsedJson = persistedJsonParsing.current === 'true';
+ const parsedModeLabel = $derived.by(() => {
+ if (preferences.showParsedJson) return m.common_parsed();
+ return m.common_raw();
});
- function handleParsedModeChange(checked: boolean): void {
- showParsedJson = checked;
- persistedJsonParsing.current = checked ? 'true' : 'false';
- }
-
- const selectedLabel = $derived(tailOptions.find((o) => o.value === selectedTail)?.label ?? m.log_tail_100_lines());
+ const selectedLabel = $derived(
+ tailOptions.find((o) => o.value === preferences.selectedTail.current)?.label ?? m.log_tail_100_lines()
+ );
</script>
{#snippet mobileActionButtons()}
@@ -132,7 +103,10 @@
<DropdownMenu.Content align="end" class="w-72">
<DropdownMenu.Label>{selectedLabel}</DropdownMenu.Label>
- <DropdownMenu.RadioGroup value={selectedTail} onValueChange={(value) => (selectedTail = value)}>
+ <DropdownMenu.RadioGroup
+ value={preferences.selectedTail.current}
+ onValueChange={(value) => (preferences.selectedTail.current = value)}
+ >
{#each tailOptions as option (option.value)}
<DropdownMenu.RadioItem value={option.value} disabled={isStreaming}>{option.label}</DropdownMenu.RadioItem>
{/each}
@@ -152,9 +126,9 @@
</div>
</DropdownMenu.CheckboxItem>
<DropdownMenu.CheckboxItem
- checked={autoStartLogs}
+ checked={preferences.autoStartLogs}
onCheckedChange={(checked) => {
- autoStartLogs = checked === true;
+ preferences.autoStartLogs = checked === true;
}}
>
<div class="flex flex-col gap-0.5">
@@ -163,13 +137,13 @@
</div>
</DropdownMenu.CheckboxItem>
<DropdownMenu.CheckboxItem
- checked={showParsedJson}
+ checked={preferences.showParsedJson}
onCheckedChange={(checked) => {
- handleParsedModeChange(checked === true);
+ preferences.setParsedMode(checked === true);
}}
>
<div class="flex flex-col gap-0.5">
- <span class="font-medium">{showParsedJson ? m.common_parsed() : m.common_raw()}</span>
+ <span class="font-medium">{parsedModeLabel}</span>
<span class="text-xs text-muted-foreground">{m.log_parsed_mode_tooltip()}</span>
</div>
</DropdownMenu.CheckboxItem>
@@ -225,10 +199,10 @@
<SwitchWithLabel
triggerProps={props}
id="auto-start-logs-toggle"
- checked={autoStartLogs}
+ checked={preferences.autoStartLogs}
label={m.auto_start()}
onCheckedChange={(checked) => {
- autoStartLogs = checked;
+ preferences.autoStartLogs = checked;
}}
/>
{/snippet}
@@ -244,10 +218,10 @@
<SwitchWithLabel
triggerProps={props}
id="parsed-log-mode-toggle"
- checked={showParsedJson}
- label={showParsedJson ? m.common_parsed() : m.common_raw()}
+ checked={preferences.showParsedJson}
+ label={parsedModeLabel}
onCheckedChange={(checked) => {
- handleParsedModeChange(checked);
+ preferences.setParsedMode(checked);
}}
/>
{/snippet}
@@ -260,7 +234,12 @@
<Input type="search" placeholder={m.common_search()} bind:value={searchTerm} class="h-9 w-44 text-xs" />
- <Select.Root type="single" bind:value={selectedTail} disabled={isStreaming} onValueChange={(v: string) => (selectedTail = v)}>
+ <Select.Root
+ type="single"
+ value={preferences.selectedTail.current}
+ disabled={isStreaming}
+ onValueChange={(v: string) => (preferences.selectedTail.current = v)}
+ >
<Select.Trigger class="h-9 w-32 text-xs">
<span>{selectedLabel}</span>
</Select.Trigger>
diff --git a/frontend/src/lib/components/mobile-nav/gestures.svelte.ts b/frontend/src/lib/components/mobile-nav/gestures.svelte.ts
index 21b1dd491..c9236b8ba 100644
--- a/frontend/src/lib/components/mobile-nav/gestures.svelte.ts
+++ b/frontend/src/lib/components/mobile-nav/gestures.svelte.ts
@@ -1,4 +1,5 @@
import { SwipeGestureDetector, type SwipeDirection } from '#lib/hooks/use-swipe-gesture.svelte.js';
+import { on } from 'svelte/events';
export interface GestureHandlers {
onMenuOpen: () => void;
@@ -12,8 +13,8 @@ export interface GestureOptions {
export class MobileNavGestures {
private swipeDetector: SwipeGestureDetector;
- private lastScrollY = $state(0);
- private lastWheelTime = $state(0);
+ private lastScrollY = 0;
+ private lastWheelTime = 0;
private scrollTimeout: ReturnType<typeof setTimeout> | null = null;
private flickDetectTimeout: ReturnType<typeof setTimeout> | null = null;
private touchStartY: number | null = null;
@@ -24,7 +25,6 @@ export class MobileNavGestures {
private readonly minScrollDistance = 80;
private readonly flickVelocityThreshold = 3;
- private navElement: HTMLElement | null = null;
private handlers: GestureHandlers;
private options: GestureOptions;
@@ -46,13 +46,9 @@ export class MobileNavGestures {
);
}
- setElement(element: HTMLElement | null) {
- this.navElement = element;
- this.swipeDetector.setElement(element);
- }
-
- private handleTouchStart = (e: TouchEvent) => {
- if (this.options.menuOpen) return;
+ handleTouchStart = (e: TouchEvent) => {
+ this.handleTouchEnd();
+ if (!this.options.scrollToHideEnabled || this.options.menuOpen) return;
const t = e.touches?.[0];
if (!t) return;
const target = e.target as HTMLElement | null;
@@ -68,8 +64,15 @@ export class MobileNavGestures {
this.touchStartX = t.clientX;
};
- private handleTouchMove = (e: TouchEvent) => {
- if (this.options.menuOpen || this.isInteractiveTouch || this.touchStartY === null || this.touchStartX === null) return;
+ handleTouchMove = (e: TouchEvent) => {
+ if (
+ !this.options.scrollToHideEnabled ||
+ this.options.menuOpen ||
+ this.isInteractiveTouch ||
+ this.touchStartY === null ||
+ this.touchStartX === null
+ )
+ return;
const t = e.touches?.[0];
if (!t) return;
const deltaY = t.clientY - this.touchStartY;
@@ -92,14 +95,18 @@ export class MobileNavGestures {
this.touchStartX = t.clientX;
};
- private handleTouchEnd = () => {
+ handleTouchEnd = () => {
this.touchStartY = null;
this.touchStartX = null;
this.isInteractiveTouch = false;
};
- private handleScroll = (e?: Event) => {
+ handleScroll = (e: Event) => {
const currentScrollY = window.scrollY;
+ if (!this.options.scrollToHideEnabled || this.options.menuOpen) {
+ this.lastScrollY = currentScrollY;
+ return;
+ }
const prevScrollY = this.lastScrollY;
const scrollDiff = currentScrollY - prevScrollY;
@@ -131,7 +138,8 @@ export class MobileNavGestures {
if (!atBottom) {
this.scrollTimeout = setTimeout(() => {
- if (window.scrollY < this.minScrollDistance) {
+ this.scrollTimeout = null;
+ if (this.options.scrollToHideEnabled && !this.options.menuOpen && window.scrollY < this.minScrollDistance) {
this.handlers.onVisibilityChange(true);
}
}, 150);
@@ -155,59 +163,28 @@ export class MobileNavGestures {
if (this.flickDetectTimeout) clearTimeout(this.flickDetectTimeout);
this.flickDetectTimeout = setTimeout(() => {
this.lastWheelTime = 0;
+ this.flickDetectTimeout = null;
}, 200);
};
- enableTouchGestures() {
- if (typeof window === 'undefined') return () => {};
- if (!this.options.scrollToHideEnabled) return () => {};
-
- const options = { passive: true, capture: true };
- window.addEventListener('touchstart', this.handleTouchStart, options);
- window.addEventListener('touchmove', this.handleTouchMove, options);
- window.addEventListener('touchend', this.handleTouchEnd, options);
-
- return () => {
- window.removeEventListener('touchstart', this.handleTouchStart, options);
- window.removeEventListener('touchmove', this.handleTouchMove, options);
- window.removeEventListener('touchend', this.handleTouchEnd, options);
- };
- }
-
- enableScrollGestures() {
- if (typeof window === 'undefined') return () => {};
- if (!this.options.scrollToHideEnabled || this.options.menuOpen) {
- this.handlers.onVisibilityChange(true);
- return () => {};
- }
-
- const scrollHandler = (e: Event) => this.handleScroll(e);
- window.addEventListener('scroll', scrollHandler, { passive: true, capture: true });
-
- return () => {
- window.removeEventListener('scroll', scrollHandler, { capture: true });
- if (this.scrollTimeout) {
- clearTimeout(this.scrollTimeout);
- }
- };
+ reset() {
+ this.handleTouchEnd();
+ this.lastWheelTime = 0;
+ if (this.scrollTimeout) clearTimeout(this.scrollTimeout);
+ if (this.flickDetectTimeout) clearTimeout(this.flickDetectTimeout);
+ this.scrollTimeout = null;
+ this.flickDetectTimeout = null;
}
- enableWheelGestures() {
- if (!this.navElement || typeof window === 'undefined') return () => {};
-
- this.navElement.addEventListener('wheel', this.handleWheel, { passive: false });
+ attach = (element: HTMLElement) => {
+ this.lastScrollY = window.scrollY;
+ this.swipeDetector.setElement(element);
+ const removeWheelListener = on(element, 'wheel', this.handleWheel, { passive: false });
return () => {
- if (this.navElement) {
- this.navElement.removeEventListener('wheel', this.handleWheel);
- }
- if (this.flickDetectTimeout) {
- clearTimeout(this.flickDetectTimeout);
- }
+ removeWheelListener();
+ this.swipeDetector.setElement(null);
+ this.reset();
};
- }
-
- updateOptions(options: GestureOptions) {
- this.options = options;
- }
+ };
}
diff --git a/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte b/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte
index d09119807..0d179a321 100644
--- a/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte
+++ b/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte
@@ -31,15 +31,8 @@
debug?: boolean;
} = $props();
- let storeUser = $state<User | null>(null);
-
- $effect(() => {
- const unsub = userStore.subscribe((u) => (storeUser = u));
- return unsub;
- });
-
const currentPath = $derived(page.url.pathname);
- const memoizedUser = $derived.by(() => user ?? storeUser);
+ const memoizedUser = $derived(user ?? $userStore);
const currentEnvId = $derived(environmentStore.selected?.id || '0');
const managementItemsRaw = $derived(getManagementItems(currentEnvId));
const managementItems = $derived(
diff --git a/frontend/src/lib/components/mobile-nav/mobile-nav.svelte b/frontend/src/lib/components/mobile-nav/mobile-nav.svelte
index fccfb9d45..4d8a68d66 100644
--- a/frontend/src/lib/components/mobile-nav/mobile-nav.svelte
+++ b/frontend/src/lib/components/mobile-nav/mobile-nav.svelte
@@ -1,6 +1,6 @@
<script lang="ts">
import { page } from '$app/state';
- import type { MobileNavigationSettings } from '#lib/config/navigation-config.js';
+ import { onDestroy } from 'svelte';
import { getAvailableMobileNavItems, getSwarmNavigationItems } from '#lib/config/navigation-config.js';
import MobileNavItem from './mobile-nav-item.svelte';
import MobileNavMenuButton from './mobile-nav-menu-button.svelte';
@@ -12,17 +12,15 @@
import type { AppVersionInformation } from '#lib/types/settings.js';
import type { PermissionsManifest, User } from '#lib/types/auth.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
- import { registerNavigationVisibilityController } from '#lib/utils/navigation.js';
+ import { getMobileNavigation } from '#lib/utils/navigation.js';
let {
- navigationSettings,
user = null,
versionInformation,
swarmEnabled = false,
permissionsManifest = null,
class: className = ''
}: {
- navigationSettings: MobileNavigationSettings;
user?: User | null;
versionInformation?: AppVersionInformation;
swarmEnabled?: boolean;
@@ -30,6 +28,8 @@
class?: string;
} = $props();
+ const navigation = getMobileNavigation();
+ const navigationSettings = $derived(navigation.settings);
const swarmItems = $derived(getSwarmNavigationItems(swarmEnabled));
const currentEnvId = $derived(environmentStore.selected?.id || '0');
@@ -49,72 +49,35 @@
const leftItems = $derived(pinnedItems.slice(0, Math.floor(pinnedItems.length / 2)));
const rightItems = $derived(pinnedItems.slice(Math.floor(pinnedItems.length / 2)));
- let visible = $state(true);
let menuOpen = $state(false);
- let navElement: HTMLElement;
+ const visible = $derived(navigation.visible);
- function resetVisibility() {
- visible = true;
+ function setMenuOpen(open: boolean) {
+ menuOpen = open;
+ navigation.visible = true;
+ gestures.reset();
}
const gestures = new MobileNavGestures(
{
- onMenuOpen: () => (menuOpen = true),
- onVisibilityChange: (isVisible) => (visible = isVisible)
+ onMenuOpen: () => setMenuOpen(true),
+ onVisibilityChange: (isVisible) => (navigation.visible = isVisible)
},
{
- scrollToHideEnabled: false,
- menuOpen: false
+ get scrollToHideEnabled() {
+ return scrollToHideEnabled;
+ },
+ get menuOpen() {
+ return menuOpen;
+ }
}
);
- // Update gesture options when reactive values change
- $effect(() => {
- gestures.updateOptions({
- scrollToHideEnabled,
- menuOpen
- });
- });
-
- // Enable touch gestures
- $effect(() => {
- scrollToHideEnabled;
- return gestures.enableTouchGestures();
- });
-
- // Enable scroll gestures
- $effect(() => {
- scrollToHideEnabled;
- menuOpen;
- return gestures.enableScrollGestures();
+ onDestroy(() => {
+ navigation.visible = true;
});
- // Enable wheel gestures on nav element
- $effect(() => {
- scrollToHideEnabled;
- menuOpen;
- if (navElement) {
- gestures.setElement(navElement);
- return gestures.enableWheelGestures();
- }
- });
-
- // Show nav when menu closes
- $effect(() => {
- if (!menuOpen) {
- resetVisibility();
- }
- });
-
- $effect(() => {
- registerNavigationVisibilityController({ resetVisibility });
- return () => registerNavigationVisibilityController(null);
- });
-
- // Keep page padding in sync with nav height via CSS variables
- $effect(() => {
- if (!navElement || typeof document === 'undefined') return;
-
+ function measureOffset(navElement: HTMLElement) {
const root = document.documentElement;
const cssVarName = mode === 'floating' ? '--mobile-floating-nav-offset' : '--mobile-docked-nav-offset';
@@ -139,20 +102,20 @@
}
const handleResize = mode === 'floating' ? () => applyOffset() : null;
- if (handleResize && typeof window !== 'undefined') {
+ if (handleResize) {
window.addEventListener('resize', handleResize);
window.visualViewport?.addEventListener('resize', handleResize);
}
return () => {
observer?.disconnect();
- if (handleResize && typeof window !== 'undefined') {
+ if (handleResize) {
window.removeEventListener('resize', handleResize);
window.visualViewport?.removeEventListener('resize', handleResize);
}
root.style.removeProperty(cssVarName);
};
- });
+ }
// Mode-specific styles
const navClasses = $derived(
@@ -183,26 +146,33 @@
)
);
- const ariaLabel = $derived(mode === 'docked' ? m.mobile_navigation() : 'Mobile navigation');
const testId = $derived(mode === 'floating' ? 'mobile-floating-nav' : 'mobile-docked-nav');
</script>
-<nav bind:this={navElement} class={navClasses} data-testid={testId} aria-label={ariaLabel}>
+<svelte:window
+ ontouchstartcapture={gestures.handleTouchStart}
+ ontouchmovecapture={gestures.handleTouchMove}
+ ontouchendcapture={gestures.handleTouchEnd}
+ ontouchcancelcapture={gestures.handleTouchEnd}
+ onscrollcapture={gestures.handleScroll}
+/>
+
+<nav {@attach gestures.attach} {@attach measureOffset} class={navClasses} data-testid={testId} aria-label={m.mobile_navigation()}>
<!-- Left side items -->
{#each leftItems as item (item.url)}
<MobileNavItem {item} {showLabels} active={currentPath === item.url || currentPath.startsWith(item.url + '/')} />
{/each}
<!-- Center action button -->
- <MobileNavMenuButton {showLabels} onclick={() => (menuOpen = true)} />
+ <MobileNavMenuButton {showLabels} onclick={() => setMenuOpen(true)} />
{#each rightItems as item (item.url)}
<MobileNavItem {item} {showLabels} active={currentPath === item.url || currentPath.startsWith(item.url + '/')} />
{/each}
{#if pinnedItems.length === 0}
- <MobileNavMenuButton {showLabels} onclick={() => (menuOpen = true)} />
+ <MobileNavMenuButton {showLabels} onclick={() => setMenuOpen(true)} />
{/if}
</nav>
-<MobileNavSheet bind:open={menuOpen} {user} {versionInformation} {swarmItems} {permissionsManifest} />
+<MobileNavSheet bind:open={() => menuOpen, setMenuOpen} {user} {versionInformation} {swarmItems} {permissionsManifest} />
diff --git a/frontend/src/lib/components/mobile-nav/mobile-user-card.svelte b/frontend/src/lib/components/mobile-nav/mobile-user-card.svelte
index 2b7aa9838..b27b39e7b 100644
--- a/frontend/src/lib/components/mobile-nav/mobile-user-card.svelte
+++ b/frontend/src/lib/components/mobile-nav/mobile-user-card.svelte
@@ -26,11 +26,7 @@
let { user, class: className = '' }: Props = $props();
- let autoLoginEnabled = $state(false);
- $effect(() => {
- const unsub = settingsStore.autoLoginEnabled.subscribe((v) => (autoLoginEnabled = v));
- return unsub;
- });
+ const autoLoginEnabled = settingsStore.autoLoginEnabled;
let userCardExpanded = $state(false);
let envDialogOpen = $state(false);
@@ -71,7 +67,7 @@
>
<ArrowDownIcon class="size-8" />
</div>
- {#if !autoLoginEnabled}
+ {#if !$autoLoginEnabled}
<form action="/logout" method="POST">
<ArcaneButton
action="base"
diff --git a/frontend/src/lib/components/resizable-split.svelte b/frontend/src/lib/components/resizable-split.svelte
index 083df5820..970600e88 100644
--- a/frontend/src/lib/components/resizable-split.svelte
+++ b/frontend/src/lib/components/resizable-split.svelte
@@ -1,6 +1,6 @@
<script lang="ts">
import type { Snippet } from 'svelte';
- import { onDestroy, onMount } from 'svelte';
+ import { untrack } from 'svelte';
import { PersistedState } from 'runed';
import { DoubleArrowLeftIcon, DoubleArrowRightIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
@@ -51,39 +51,52 @@
onResizeEnd = () => {}
}: Props = $props();
- let containerRef = $state<HTMLDivElement | null>(null);
- let isResizing = $state(false);
- let collapsedSide = $state<'first' | 'second' | null>(null);
- let isStacked = $state(false);
+ let containerRef: HTMLDivElement | null = null;
+ let containerWidth = $state(0);
+ let isResizing = false;
let lastSize = 0;
- let persistedState = $state<PersistedState<number | null> | null>(null);
- let persistedKey = $state<string | null>(null);
- let resizeObserver: ResizeObserver | null = null;
-
+ const initialPreferences = untrack(() => ({ key: persistKey, size, storage: persistStorage }));
+ let persistedState: PersistedState<number | null> | null = null;
+ if (initialPreferences.key) {
+ persistedState = new PersistedState<number | null>(initialPreferences.key, initialPreferences.size, {
+ storage: initialPreferences.storage,
+ syncTabs: false
+ });
+ }
+ const storedSize = persistedState?.current;
+ if (storedSize !== null && storedSize !== undefined) size = storedSize;
+ const isStacked = $derived(stackBelow !== undefined && containerWidth < stackBelow);
let resizeStartX = 0;
let resizeStartWidth = 0;
- const evaluateStacked = () => {
- if (stackBelow === undefined) return;
- if (!containerRef && typeof window === 'undefined') return;
- const width = containerRef ? containerRef.getBoundingClientRect().width : window.innerWidth;
- isStacked = width < stackBelow;
- };
-
const clampSize = (value: number, minValue: number, maxValue: number) => Math.min(Math.max(value, minValue), maxValue);
- const layoutHandleSize = $derived(variant === 'flush' ? 1 : handleSize);
+ const layoutHandleSize = $derived.by(() => {
+ if (variant === 'flush') return 1;
+ return handleSize;
+ });
- const getAvailableWidth = () => {
- if (!containerRef) return 0;
- return Math.max(0, containerRef.getBoundingClientRect().width - layoutHandleSize);
- };
+ const getAvailableWidth = () => Math.max(0, containerWidth - layoutHandleSize);
const getMaxNormalSize = () => {
const base = Math.max(0, getAvailableWidth() - minSecondSize);
- return maxSize !== undefined ? Math.min(base, maxSize) : base;
+ if (maxSize !== undefined) return Math.min(base, maxSize);
+ return base;
};
+ const layout = $derived.by(() => {
+ const available = getAvailableWidth();
+ const requested = size ?? Math.round(available * defaultRatio);
+ if (available <= 0) return { size: 0, collapsedSide: null };
+ if (allowCollapse && requested <= collapseThreshold) return { size: 0, collapsedSide: 'first' };
+ if (allowCollapse && maxSize === undefined && requested >= available - collapseThreshold) {
+ return { size: available, collapsedSide: 'second' };
+ }
+ const maxNormal = getMaxNormalSize();
+ return { size: clampSize(requested, Math.min(minSize, maxNormal), maxNormal), collapsedSide: null };
+ });
+ const collapsedSide = $derived(layout.collapsedSide);
+
const ensureInitialSize = () => {
if (!containerRef || size !== null) return;
const available = getAvailableWidth();
@@ -107,19 +120,16 @@
const safeMin = Math.min(minSize, maxNormal);
if (allowCollapse && nextSize <= collapseThreshold) {
- collapsedSide = 'first';
size = 0;
if (persist) commitSize();
return;
}
if (allowCollapse && maxSize === undefined && nextSize >= available - collapseThreshold) {
- collapsedSide = 'second';
size = available;
if (persist) commitSize();
return;
}
- collapsedSide = null;
const clamped = clampSize(nextSize, safeMin, maxNormal);
size = clamped;
lastSize = clamped;
@@ -134,35 +144,31 @@
const stopResize = () => {
if (!isResizing) return;
isResizing = false;
- window.removeEventListener('pointermove', handleMove);
- window.removeEventListener('pointerup', stopResize);
document.body.style.cursor = '';
document.body.style.userSelect = '';
commitSize();
onResizeEnd();
};
- const handleWindowResize = () => {
- if (isResizing) return;
- evaluateStacked();
- if (isStacked) return;
- if (size === null) {
- ensureInitialSize();
- if (size === null) return;
- }
- applySize(size);
- };
-
- const handleContainerResize = () => {
- if (isResizing) return;
- evaluateStacked();
- if (isStacked) return;
- if (size === null) {
+ function measureContainer(node: HTMLDivElement) {
+ containerRef = node;
+ containerWidth = node.getBoundingClientRect().width;
+ const observer = new ResizeObserver(() => {
+ containerWidth = node.getBoundingClientRect().width;
+ if (isResizing || isStacked) return;
ensureInitialSize();
- if (size === null) return;
- }
- applySize(size);
- };
+ if (size !== null) applySize(size);
+ });
+ observer.observe(node);
+ return () => {
+ observer.disconnect();
+ containerRef = null;
+ if (!isResizing) return;
+ isResizing = false;
+ document.body.style.cursor = '';
+ document.body.style.userSelect = '';
+ };
+ }
function startResize(event: PointerEvent) {
if (!containerRef) return;
@@ -170,8 +176,6 @@
resizeStartX = event.clientX;
resizeStartWidth = size ?? 0;
isResizing = true;
- window.addEventListener('pointermove', handleMove);
- window.addEventListener('pointerup', stopResize);
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
event.preventDefault();
@@ -181,66 +185,22 @@
const maxNormal = getMaxNormalSize();
const safeMin = Math.min(minSize, maxNormal);
const restored = clampSize(lastSize || safeMin, safeMin, maxNormal);
- collapsedSide = null;
size = restored;
lastSize = restored;
commitSize();
onResizeEnd();
}
-
- $effect(() => {
- if (!persistKey) {
- persistedState = null;
- persistedKey = null;
- return;
- }
- if (persistedKey === persistKey && persistedState) return;
- persistedState = new PersistedState<number | null>(persistKey, size ?? null, {
- storage: persistStorage,
- syncTabs: false
- });
- persistedKey = persistKey;
- const stored = persistedState.current;
- if (stored !== null && stored !== undefined) {
- size = stored;
- }
- });
-
- $effect(() => {
- if (!containerRef || size === null || isResizing || isStacked) return;
- applySize(size, false);
- });
-
- onMount(() => {
- evaluateStacked();
- if (!isStacked) {
- ensureInitialSize();
- }
- window.addEventListener('resize', handleWindowResize);
- if (stackBelow !== undefined && typeof ResizeObserver !== 'undefined' && containerRef) {
- resizeObserver = new ResizeObserver(handleContainerResize);
- resizeObserver.observe(containerRef);
- }
- return () => {
- window.removeEventListener('resize', handleWindowResize);
- resizeObserver?.disconnect();
- resizeObserver = null;
- };
- });
-
- onDestroy(() => {
- window.removeEventListener('pointermove', handleMove);
- window.removeEventListener('pointerup', stopResize);
- });
</script>
+<svelte:window onpointermove={handleMove} onpointerup={stopResize} />
+
<div
- bind:this={containerRef}
+ {@attach measureContainer}
class={['flex min-h-0 min-w-0', isStacked && (variant === 'flush' ? 'flex-col' : 'flex-col gap-4'), className]}
>
<div
class={['min-h-0 min-w-0 overflow-hidden', isStacked ? 'flex-1' : 'flex-none', firstClass]}
- style={isStacked ? '' : `width: ${size ?? 0}px;`}
+ style={isStacked ? '' : `width: ${layout.size}px;`}
aria-hidden={!isStacked && collapsedSide === 'first'}
>
{#if isStacked || collapsedSide !== 'first'}
diff --git a/frontend/src/lib/components/settings/trivy-security-settings.svelte b/frontend/src/lib/components/settings/trivy-security-settings.svelte
index fde75b5d7..f47225698 100644
--- a/frontend/src/lib/components/settings/trivy-security-settings.svelte
+++ b/frontend/src/lib/components/settings/trivy-security-settings.svelte
@@ -1,5 +1,10 @@
<script lang="ts">
- import { tryCatch } from '#lib/utils/try-catch.js';
+ import { onMount } from 'svelte';
+ import { createQuery, useQueryClient } from '@tanstack/svelte-query';
+ import { queryKeys } from '#lib/query/query-keys.js';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+ import userStore from '#lib/stores/user-store.js';
+ import { hasPermission } from '#lib/utils/auth.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/index.js';
@@ -69,7 +74,29 @@
{ value: 'none', label: m.security_trivy_network_none() }
];
- let customTrivyNetworkOptions = $state<TrivyNetworkOption[]>([]);
+ const queryClient = useQueryClient();
+ const networkRequest: SearchPaginationSortRequest = {
+ pagination: { page: 1, limit: 1000 },
+ sort: { column: 'name', direction: 'asc' }
+ };
+ const targetEnvironmentId = $derived(environmentId ?? environmentStore.selected?.id);
+ const networksQuery = createQuery(() => {
+ const requestedEnvironmentId = targetEnvironmentId;
+ $userStore;
+ return {
+ queryKey: queryKeys.networks.list(requestedEnvironmentId ?? '', networkRequest),
+ queryFn: async () => {
+ await environmentStore.ready;
+ return networkService.getNetworksForEnvironment(requestedEnvironmentId!, networkRequest);
+ },
+ enabled: !!requestedEnvironmentId && hasPermission('networks:read', requestedEnvironmentId)
+ };
+ });
+ const customTrivyNetworkOptions = $derived(
+ [...new Set((networksQuery.data?.data ?? []).map((network) => network.name).filter(Boolean))]
+ .sort((a, b) => a.localeCompare(b))
+ .map((name) => ({ value: name, label: name }))
+ );
const trivyNetworkOptions = $derived.by(() => {
const options = [...baseTrivyNetworkOptions];
@@ -92,35 +119,6 @@
return options;
});
- async function fetchTrivyNetworkOptions(targetEnvironmentId: string | undefined): Promise<TrivyNetworkOption[]> {
- const request: SearchPaginationSortRequest = {
- pagination: {
- page: 1,
- limit: 1000
- },
- sort: {
- column: 'name',
- direction: 'asc'
- }
- };
- const response = targetEnvironmentId
- ? await networkService.getNetworksForEnvironment(targetEnvironmentId, request)
- : await networkService.getNetworks(request);
-
- const networkNames = [
- ...new Set(
- response.data
- .map((network) => network.name)
- .filter((name) => !!name && !baseTrivyNetworkOptions.some((option) => option.value === name))
- )
- ].sort((a, b) => a.localeCompare(b));
-
- return networkNames.map((name) => ({
- value: name,
- label: name
- }));
- }
-
function handleTrivyResourceLimitsChange(checked: boolean) {
$formInputs.trivyResourceLimitsEnabled.value = checked;
if (!checked) {
@@ -129,25 +127,23 @@
}
}
- $effect(() => {
- const targetEnvironmentId = environmentId;
- let cancelled = false;
-
- void (async () => {
- const result = await tryCatch(
- fetchTrivyNetworkOptions(targetEnvironmentId).then((options) => {
- if (!cancelled) customTrivyNetworkOptions = options;
- })
- );
- if (result.error !== null && !cancelled) {
- console.warn('Failed to load Trivy network options:', result.error);
- toast.info(m.security_trivy_network_fetch_failed());
+ onMount(() => {
+ const cache = queryClient.getQueryCache();
+ let lastError: unknown;
+ function reportNetworkError(error: unknown) {
+ if (!error || error === lastError || !targetEnvironmentId || !hasPermission('networks:read', targetEnvironmentId)) return;
+ lastError = error;
+ toast.info(m.security_trivy_network_fetch_failed());
+ }
+ reportNetworkError(networksQuery.error);
+ return cache.subscribe((event) => {
+ if (event.type !== 'updated' && event.type !== 'observerResultsUpdated') return;
+ if (
+ event.query === cache.find({ queryKey: queryKeys.networks.list(targetEnvironmentId ?? '', networkRequest), exact: true })
+ ) {
+ reportNetworkError(event.query.state.error);
}
- })();
-
- return () => {
- cancelled = true;
- };
+ });
});
</script>
diff --git a/frontend/src/lib/components/sheets/git-repository-sheet.svelte b/frontend/src/lib/components/sheets/git-repository-sheet.svelte
index 2a46a726c..77d0c3ce8 100644
--- a/frontend/src/lib/components/sheets/git-repository-sheet.svelte
+++ b/frontend/src/lib/components/sheets/git-repository-sheet.svelte
@@ -1,4 +1,5 @@
<script lang="ts">
+ import { untrack } from 'svelte';
import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';
import SheetFooterActions from '#lib/components/sheets/sheet-footer-actions.svelte';
import FormInput from '#lib/components/form/form-input.svelte';
@@ -42,21 +43,19 @@
enabled: z.boolean().default(true)
});
- let formData = $derived({
- name: open && repositoryToEdit ? repositoryToEdit.name : '',
- url: open && repositoryToEdit ? repositoryToEdit.url : '',
- authType: (open && repositoryToEdit ? repositoryToEdit.authType : 'http') as 'none' | 'http' | 'ssh',
- username: open && repositoryToEdit ? repositoryToEdit.username || '' : '',
+ const formData = untrack(() => ({
+ name: repositoryToEdit?.name ?? '',
+ url: repositoryToEdit?.url ?? '',
+ authType: (repositoryToEdit?.authType ?? 'http') as 'none' | 'http' | 'ssh',
+ username: repositoryToEdit?.username || '',
token: '',
sshKey: '',
- sshHostKeyVerification: (open && repositoryToEdit
- ? repositoryToEdit.sshHostKeyVerification || 'accept_new'
- : 'accept_new') as 'strict' | 'accept_new' | 'skip',
- description: open && repositoryToEdit ? repositoryToEdit.description || '' : '',
- enabled: open && repositoryToEdit ? (repositoryToEdit.enabled ?? true) : true
- });
+ sshHostKeyVerification: (repositoryToEdit?.sshHostKeyVerification || 'accept_new') as 'strict' | 'accept_new' | 'skip',
+ description: repositoryToEdit?.description || '',
+ enabled: repositoryToEdit?.enabled ?? true
+ }));
- let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
+ const { inputs, ...form } = createForm<typeof formSchema>(formSchema, formData);
let hasToken = $derived(!!repositoryToEdit?.hasToken);
let hasSshKey = $derived(!!repositoryToEdit?.hasSshKey);
@@ -65,13 +64,13 @@
let sshKeyNeedsAttention = $derived(urlChanged && hasSshKey && !clearSshKey && !$inputs.sshKey?.value?.trim());
let selectedAuthType = $state<{ value: string; label: string }>({
- value: 'http',
- label: m.git_repository_auth_http()
+ value: formData.authType,
+ label: getAuthTypeLabel(formData.authType)
});
let selectedSshHostKeyVerification = $state<{ value: string; label: string }>({
- value: 'accept_new',
- label: m.git_repository_ssh_host_key_accept_new()
+ value: formData.sshHostKeyVerification,
+ label: getSshHostKeyVerificationLabel(formData.sshHostKeyVerification)
});
function getAuthTypeLabel(type: string): string {
@@ -96,22 +95,6 @@
}
}
- $effect(() => {
- if (open && repositoryToEdit) {
- selectedAuthType = {
- value: repositoryToEdit.authType,
- label: getAuthTypeLabel(repositoryToEdit.authType)
- };
- selectedSshHostKeyVerification = {
- value: repositoryToEdit.sshHostKeyVerification || 'accept_new',
- label: getSshHostKeyVerificationLabel(repositoryToEdit.sshHostKeyVerification || 'accept_new')
- };
- } else if (open && !repositoryToEdit) {
- selectedAuthType = { value: 'http', label: m.git_repository_auth_http() };
- selectedSshHostKeyVerification = { value: 'accept_new', label: m.git_repository_ssh_host_key_accept_new() };
- }
- });
-
function clearCredentialErrors() {
if ($inputs.token) $inputs.token.error = null;
if ($inputs.sshKey) $inputs.sshKey.error = null;
diff --git a/frontend/src/lib/components/sheets/new-environment-sheet.svelte b/frontend/src/lib/components/sheets/new-environment-sheet.svelte
index e34cd57e8..b53594e91 100644
--- a/frontend/src/lib/components/sheets/new-environment-sheet.svelte
+++ b/frontend/src/lib/components/sheets/new-environment-sheet.svelte
@@ -65,7 +65,7 @@
try {
const operationResult1 = await tryCatch(
(async () => {
- const snippets = await queryClient.fetchQuery({
+ const snippets = await queryClient.query({
queryKey: queryKeys.environments.deploymentSnippets(created.id),
queryFn: () => environmentManagementService.getDeploymentSnippets(created.id),
staleTime: 0
@@ -103,7 +103,6 @@
const isSubmittingNewAgent = $derived(createEnvironmentMutation.isPending);
let newAgentUrlProtocol = $state<'https' | 'http'>('http');
- let newAgentUrlHost = $state('');
let edgeMTLSEnabled = $state(false);
// Direct mode form schema requires URL
@@ -127,29 +126,12 @@
});
// Reset on open/close
- $effect(() => {
- if (open) {
- createdEnvironment = null;
- connectionMode = 'direct';
- newAgentUrlProtocol = 'http';
- newAgentUrlHost = '';
- edgeMTLSEnabled = false;
- $directInputs.name.value = '';
- $directInputs.apiUrl.value = '';
- $edgeInputs.name.value = '';
- }
- });
-
- // Sync UrlInput value with form validation for direct mode
- $effect(() => {
- $directInputs.apiUrl.value = newAgentUrlHost;
- });
function handleDirectSubmit() {
const data = directForm.validate();
if (!data) return;
- const fullUrl = `${newAgentUrlProtocol}://${newAgentUrlHost}`;
+ const fullUrl = `${newAgentUrlProtocol}://${data.apiUrl}`;
const dto: CreateEnvironmentDTO = {
name: data.name,
@@ -336,7 +318,7 @@
label={m.environments_agent_address()}
placeholder={m.environments_agent_address_placeholder()}
description={m.environments_agent_address_description()}
- bind:value={newAgentUrlHost}
+ bind:value={$directInputs.apiUrl.value}
bind:protocol={newAgentUrlProtocol}
disabled={isSubmittingNewAgent}
required
diff --git a/frontend/src/lib/components/sheets/variable-form-sheet.svelte b/frontend/src/lib/components/sheets/variable-form-sheet.svelte
index 977d2e207..3a3d5b10e 100644
--- a/frontend/src/lib/components/sheets/variable-form-sheet.svelte
+++ b/frontend/src/lib/components/sheets/variable-form-sheet.svelte
@@ -1,4 +1,5 @@
<script lang="ts">
+ import { untrack } from 'svelte';
import * as ResponsiveDialog from '#lib/components/ui/responsive-dialog/index.js';
import SheetFooterActions from '#lib/components/sheets/sheet-footer-actions.svelte';
import SwitchWithLabel from '#lib/components/form/labeled-switch.svelte';
@@ -39,8 +40,13 @@
const isEditMode = $derived(!!variableToEdit);
let entryMode = $state<'single' | 'bulk'>('single');
- let scope = $state<'all' | 'specific'>('all');
- let selectedEnvIds = $state<string[]>([]);
+ let scope = $state<'all' | 'specific'>(
+ untrack(() => {
+ if (variableToEdit && !variableToEdit.allEnvironments && variableToEdit.environmentIds.length > 0) return 'specific';
+ return 'all';
+ })
+ );
+ let selectedEnvIds = $state<string[]>(untrack(() => [...(variableToEdit?.environmentIds ?? [])]));
let scopeError = $state<string | null>(null);
let bulkText = $state('');
let bulkSecret = $state(false);
@@ -63,7 +69,7 @@
});
}
- const formSchema = $derived.by(() => {
+ const formSchema = untrack(() => {
const wasSecret = variableToEdit?.isSecret ?? false;
return z
@@ -85,13 +91,13 @@
});
});
- const formData = $derived({
- key: variableToEdit?.key ?? '',
- value: variableToEdit ? (variableToEdit.isSecret ? '' : variableToEdit.value) : '',
- isSecret: variableToEdit?.isSecret ?? false
+ const formData = untrack(() => {
+ let value = '';
+ if (variableToEdit && !variableToEdit.isSecret) value = variableToEdit.value;
+ return { key: variableToEdit?.key ?? '', value, isSecret: variableToEdit?.isSecret ?? false };
});
- let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
+ const { inputs, ...form } = createForm<typeof formSchema>(formSchema, formData);
const parsed = $derived(parseEnvText(bulkText));
@@ -107,19 +113,6 @@
return [...duplicates];
});
- $effect(() => {
- if (open) {
- const editing = variableToEdit;
- entryMode = 'single';
- bulkText = '';
- bulkSecret = false;
- bulkError = null;
- scopeError = null;
- scope = editing && !editing.allEnvironments && editing.environmentIds.length > 0 ? 'specific' : 'all';
- selectedEnvIds = editing ? [...editing.environmentIds] : [];
- }
- });
-
function validateScope(): boolean {
scopeError = scope === 'specific' && selectedEnvIds.length === 0 ? m.select_at_least_one_environment() : null;
return !scopeError;
@@ -167,18 +160,10 @@
onSubmit({ mode: 'create', variable: { key: data.key, value: data.value, isSecret: data.isSecret, ...scopeDto() } });
}
}
-
- function handleOpenChange(newOpenState: boolean) {
- open = newOpenState;
- if (!newOpenState) {
- variableToEdit = null;
- }
- }
</script>
<ResponsiveDialog.Root
- {open}
- onOpenChange={handleOpenChange}
+ bind:open
variant="sheet"
title={isEditMode ? m.edit_variable() : m.create_variable()}
description={isEditMode ? (variableToEdit?.key ?? '') : m.common_add_description()}
diff --git a/frontend/src/lib/components/sidebar/sidebar-user.svelte b/frontend/src/lib/components/sidebar/sidebar-user.svelte
index 89e988bf2..c48a23e93 100644
--- a/frontend/src/lib/components/sidebar/sidebar-user.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar-user.svelte
@@ -16,16 +16,8 @@
}: { user: User; isCollapsed: boolean; autoLoginEnabled?: boolean } = $props();
const sidebar = useSidebar();
- let dropdownOpen = $state(false);
-
const displayLabel = $derived(user.displayName || user.username);
- $effect(() => {
- if (sidebar.state === 'collapsed' && !sidebar.isHovered && dropdownOpen) {
- dropdownOpen = false;
- }
- });
-
async function getGravatarUrl(email: string | undefined, size = 40): Promise<string> {
if (!email) return '';
@@ -41,124 +33,122 @@
<Sidebar.Menu>
<Sidebar.MenuItem>
- <DropdownMenu.Root bind:open={dropdownOpen}>
- <DropdownMenu.Trigger>
- {#snippet child({ props })}
- <Sidebar.MenuButton
- size="lg"
- class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
- {...props}
+ {#key sidebar.state === 'collapsed' && !sidebar.isHovered}
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Sidebar.MenuButton
+ size="lg"
+ class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
+ {...props}
+ >
+ {#key user?.updatedAt}
+ <Avatar.Root class="size-8 rounded-lg">
+ {#if user?.avatarUrl}
+ <Avatar.Image src={`${user.avatarUrl}?t=${user.updatedAt}`} alt={displayLabel} />
+ {:else if $settingsStore.enableGravatar}
+ {#await getGravatarUrl(user?.email)}
+ <!-- Loading gravatar, show fallback -->
+ {:then url}
+ <Avatar.Image src={url} alt={displayLabel} />
+ {:catch}
+ <!-- Gravatar failed, show fallback -->
+ {/await}
+ {/if}
+ <Avatar.Fallback class="rounded-lg bg-primary text-sm font-semibold text-primary-foreground">
+ {displayLabel.charAt(0).toUpperCase()}
+ </Avatar.Fallback>
+ </Avatar.Root>
+ {/key}
+ {#if !isCollapsed}
+ <div class="grid flex-1 pl-0 text-left text-sm leading-tight">
+ <span class="truncate font-medium">{displayLabel}</span>
+ <span class="truncate text-xs">{user.email}</span>
+ </div>
+ <ArrowsUpDownIcon class="ml-auto size-4 shrink-0 text-muted-foreground" />
+ {/if}
+ </Sidebar.MenuButton>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content
+ class="min-w-60 rounded-xl border border-border/30 p-1.5 shadow-lg backdrop-blur-2xl backdrop-saturate-150"
+ side="right"
+ align="end"
+ sideOffset={12}
+ >
+ <div
+ role="group"
+ tabindex="-1"
+ onmouseenter={() => {
+ if (sidebar.state === 'collapsed') {
+ sidebar.setHovered(true);
+ }
+ }}
+ onmouseleave={() => {
+ sidebar.setHovered(false, 150);
+ }}
>
- {#key user?.updatedAt}
- <Avatar.Root class="size-8 rounded-lg">
- {#if user?.avatarUrl}
- <Avatar.Image src={`${user.avatarUrl}?t=${user.updatedAt}`} alt={displayLabel} />
- {:else if $settingsStore.enableGravatar}
- {#await getGravatarUrl(user?.email)}
- <!-- Loading gravatar, show fallback -->
- {:then url}
- <Avatar.Image src={url} alt={displayLabel} />
- {:catch}
- <!-- Gravatar failed, show fallback -->
- {/await}
- {/if}
- <Avatar.Fallback class="rounded-lg bg-primary text-sm font-semibold text-primary-foreground">
- {displayLabel.charAt(0).toUpperCase()}
- </Avatar.Fallback>
- </Avatar.Root>
- {/key}
- {#if !isCollapsed}
- <div class="grid flex-1 pl-0 text-left text-sm leading-tight">
- <span class="truncate font-medium">{displayLabel}</span>
- <span class="truncate text-xs">{user.email}</span>
+ <div class="flex items-center gap-2.5 px-2 py-2">
+ {#key user?.updatedAt}
+ <Avatar.Root class="size-8 shrink-0 rounded-lg">
+ {#if user?.avatarUrl}
+ <Avatar.Image src={`${user.avatarUrl}?t=${user.updatedAt}`} alt={displayLabel} />
+ {:else if $settingsStore.enableGravatar}
+ {#await getGravatarUrl(user?.email)}
+ <!-- Loading gravatar, show fallback -->
+ {:then url}
+ <Avatar.Image src={url} alt={displayLabel} />
+ {:catch}
+ <!-- Gravatar failed, show fallback -->
+ {/await}
+ {/if}
+ <Avatar.Fallback class="rounded-lg bg-primary text-xs font-semibold text-primary-foreground">
+ {displayLabel.charAt(0).toUpperCase()}
+ </Avatar.Fallback>
+ </Avatar.Root>
+ {/key}
+ <div class="grid min-w-0 flex-1 leading-tight">
+ <span class="truncate text-sm font-medium">{displayLabel}</span>
+ <span class="truncate text-xs text-muted-foreground">{user.email}</span>
</div>
- <ArrowsUpDownIcon class="ml-auto size-4 shrink-0 text-muted-foreground" />
- {/if}
- </Sidebar.MenuButton>
- {/snippet}
- </DropdownMenu.Trigger>
- <DropdownMenu.Content
- class="min-w-60 rounded-xl border border-border/30 p-1.5 shadow-lg backdrop-blur-2xl backdrop-saturate-150"
- side="right"
- align="end"
- sideOffset={12}
- >
- <div
- role="group"
- tabindex="-1"
- onmouseenter={() => {
- if (sidebar.state === 'collapsed') {
- sidebar.setHovered(true);
- }
- }}
- onmouseleave={() => {
- sidebar.setHovered(false, 150);
- }}
- >
- <div class="flex items-center gap-2.5 px-2 py-2">
- {#key user?.updatedAt}
- <Avatar.Root class="size-8 shrink-0 rounded-lg">
- {#if user?.avatarUrl}
- <Avatar.Image src={`${user.avatarUrl}?t=${user.updatedAt}`} alt={displayLabel} />
- {:else if $settingsStore.enableGravatar}
- {#await getGravatarUrl(user?.email)}
- <!-- Loading gravatar, show fallback -->
- {:then url}
- <Avatar.Image src={url} alt={displayLabel} />
- {:catch}
- <!-- Gravatar failed, show fallback -->
- {/await}
- {/if}
- <Avatar.Fallback class="rounded-lg bg-primary text-xs font-semibold text-primary-foreground">
- {displayLabel.charAt(0).toUpperCase()}
- </Avatar.Fallback>
- </Avatar.Root>
- {/key}
- <div class="grid min-w-0 flex-1 leading-tight">
- <span class="truncate text-sm font-medium">{displayLabel}</span>
- <span class="truncate text-xs text-muted-foreground">{user.email}</span>
</div>
- </div>
- <DropdownMenu.Separator class="my-1" />
+ <DropdownMenu.Separator class="my-1" />
- <button
- type="button"
- class="flex w-full items-center gap-2.5 rounded-lg px-2 py-2 text-sm text-foreground transition-colors hover:bg-muted/60"
- onclick={() => {
- dropdownOpen = false;
- goto('/account');
- }}
- >
- <UserIcon class="size-4 shrink-0 text-muted-foreground" />
- <span>{m.common_account()}</span>
- </button>
+ <DropdownMenu.Item
+ class="flex w-full items-center gap-2.5 rounded-lg px-2 py-2 text-sm text-foreground transition-colors hover:bg-muted/60"
+ onSelect={() => {
+ goto('/account');
+ }}
+ >
+ <UserIcon class="size-4 shrink-0 text-muted-foreground" />
+ <span>{m.common_account()}</span>
+ </DropdownMenu.Item>
- <button
- type="button"
- class="flex w-full items-center gap-2.5 rounded-lg px-2 py-2 text-sm text-foreground transition-colors hover:bg-muted/60"
- onclick={() => {
- dropdownOpen = false;
- goto('/account?tab=preferences');
- }}
- >
- <SettingsIcon class="size-4 shrink-0 text-muted-foreground" />
- <span>{m.account_preferences()}</span>
- </button>
+ <DropdownMenu.Item
+ class="flex w-full items-center gap-2.5 rounded-lg px-2 py-2 text-sm text-foreground transition-colors hover:bg-muted/60"
+ onSelect={() => {
+ goto('/account?tab=preferences');
+ }}
+ >
+ <SettingsIcon class="size-4 shrink-0 text-muted-foreground" />
+ <span>{m.account_preferences()}</span>
+ </DropdownMenu.Item>
- {#if !autoLoginEnabled}
- <form action="/logout" method="POST" class="w-full">
- <button
- type="submit"
- class="flex w-full items-center gap-2.5 rounded-lg px-2 py-2 text-sm text-destructive transition-colors hover:bg-destructive/10"
- >
- <LogoutIcon class="size-4 shrink-0" />
- <span>{m.common_log_out()}</span>
- </button>
- </form>
- {/if}
- </div>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
+ {#if !autoLoginEnabled}
+ <form action="/logout" method="POST" class="w-full">
+ <button
+ type="submit"
+ class="flex w-full items-center gap-2.5 rounded-lg px-2 py-2 text-sm text-destructive transition-colors hover:bg-destructive/10"
+ >
+ <LogoutIcon class="size-4 shrink-0" />
+ <span>{m.common_log_out()}</span>
+ </button>
+ </form>
+ {/if}
+ </div>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ {/key}
</Sidebar.MenuItem>
</Sidebar.Menu>
diff --git a/frontend/src/lib/components/sidebar/sidebar.svelte b/frontend/src/lib/components/sidebar/sidebar.svelte
index fa6aba938..581fc7b26 100644
--- a/frontend/src/lib/components/sidebar/sidebar.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar.svelte
@@ -44,11 +44,8 @@
permissionsManifest?: PermissionsManifest | null;
} = $props();
- let autoLoginEnabled = $state(false);
- $effect(() => {
- const unsub = settingsStore.autoLoginEnabled.subscribe((v) => (autoLoginEnabled = v));
- return unsub;
- });
+ const autoLogin = fromStore(settingsStore.autoLoginEnabled);
+ const autoLoginEnabled = $derived(autoLogin.current);
const sidebar = useSidebar();
diff --git a/frontend/src/lib/components/terminal/terminal-controls.svelte b/frontend/src/lib/components/terminal/terminal-controls.svelte
index 50d8c7fc0..07a0fb8fb 100644
--- a/frontend/src/lib/components/terminal/terminal-controls.svelte
+++ b/frontend/src/lib/components/terminal/terminal-controls.svelte
@@ -14,9 +14,6 @@
onReconnect?: () => void;
} = $props();
- let customShell = $state('');
- let useCustomShell = $state(false);
-
const commonShells = [
{ value: '/bin/sh', label: 'sh' },
{ value: '/bin/bash', label: 'bash' },
@@ -33,14 +30,20 @@
custom: m.custom()
};
+ let customShell = $derived.by(() => {
+ if (selectedShell && !(selectedShell in shellLabels)) return selectedShell;
+ return '';
+ });
+ const useCustomShell = $derived(selectedShell === 'custom' || (!!selectedShell && !(selectedShell in shellLabels)));
+
function handleShellChange(value: string | undefined) {
if (!value) return;
if (value === 'custom') {
- useCustomShell = true;
+ const draft = customShell;
selectedShell = value;
+ customShell = draft;
} else {
- useCustomShell = false;
selectedShell = value;
onShellChange?.(value);
}
@@ -51,38 +54,15 @@
onShellChange?.(customShell);
}
}
-
- $effect(() => {
- if (!selectedShell) {
- return;
- }
-
- const isKnownShell = selectedShell in shellLabels;
- if (!isKnownShell && selectedShell !== 'custom') {
- useCustomShell = true;
- customShell = selectedShell;
- return;
- }
-
- if (selectedShell === 'custom') {
- useCustomShell = true;
- return;
- }
-
- if (isKnownShell) {
- useCustomShell = false;
- customShell = '';
- }
- });
</script>
<div class="flex items-center gap-2">
- <Select.Root bind:value={selectedShell} type="single" onValueChange={handleShellChange}>
+ <Select.Root value={selectedShell} type="single" onValueChange={handleShellChange}>
<Select.Trigger class="h-8 w-[140px]">
{shellLabels[selectedShell] ?? m.select_shell_placeholder()}
</Select.Trigger>
<Select.Content>
- {#each commonShells as shell}
+ {#each commonShells as shell (shell.value)}
<Select.Item value={shell.value}>
{shell.label}
</Select.Item>
diff --git a/frontend/src/lib/components/ui/carousel/carousel.svelte b/frontend/src/lib/components/ui/carousel/carousel.svelte
index 670b0736d..d7510efb8 100644
--- a/frontend/src/lib/components/ui/carousel/carousel.svelte
+++ b/frontend/src/lib/components/ui/carousel/carousel.svelte
@@ -1,5 +1,6 @@
<script lang="ts">
import { type CarouselAPI, type CarouselProps, type EmblaContext, setEmblaContext } from './context.js';
+ import { onDestroy } from 'svelte';
import { cn, type WithElementRef } from '#lib/utils.js';
let {
@@ -70,11 +71,7 @@
onSelect();
}
- $effect(() => {
- return () => {
- carouselState.api?.off('select', onSelect);
- };
- });
+ onDestroy(() => carouselState.api?.off('select', onSelect));
</script>
<div
diff --git a/frontend/src/lib/components/ui/file-drop-zone/file-drop-zone.svelte b/frontend/src/lib/components/ui/file-drop-zone/file-drop-zone.svelte
index 94b466ec4..0195f878b 100644
--- a/frontend/src/lib/components/ui/file-drop-zone/file-drop-zone.svelte
+++ b/frontend/src/lib/components/ui/file-drop-zone/file-drop-zone.svelte
@@ -21,12 +21,6 @@
...rest
}: FileDropZoneProps = $props();
- $effect(() => {
- if (maxFiles !== undefined && fileCount === undefined) {
- console.warn('Make sure to provide FileDropZone with `fileCount` when using the `maxFiles` prompt');
- }
- });
-
let uploading = $state(false);
const drop = async (
@@ -93,6 +87,9 @@
};
const upload = async (uploadFiles: File[]) => {
+ if (maxFiles !== undefined && fileCount === undefined) {
+ console.warn('Make sure to provide FileDropZone with `fileCount` when using the `maxFiles` prop');
+ }
uploading = true;
const validFiles: File[] = [];
diff --git a/frontend/src/lib/components/ui/sidebar/context.svelte.ts b/frontend/src/lib/components/ui/sidebar/context.svelte.ts
index 323c930bd..d08d123bd 100644
--- a/frontend/src/lib/components/ui/sidebar/context.svelte.ts
+++ b/frontend/src/lib/components/ui/sidebar/context.svelte.ts
@@ -1,5 +1,7 @@
import { IsTablet } from '#lib/hooks/is-tablet.svelte.js';
-import { getContext, setContext } from 'svelte';
+import { getContext, setContext, onDestroy } from 'svelte';
+import { fromStore } from 'svelte/store';
+import userStore from '#lib/stores/user-store.js';
import { PersistedState } from 'runed';
import { SIDEBAR_KEYBOARD_SHORTCUT } from './constants.js';
@@ -11,7 +13,7 @@ export type SidebarStateProps = {
* We use a getter function here to support `bind:open` on the `Sidebar.Provider`
* component.
*/
- open: Getter<boolean>;
+ open: Getter<boolean | undefined>;
/**
* A function that sets the open state of the sidebar. To support `bind:open`, we need
@@ -23,13 +25,14 @@ export type SidebarStateProps = {
class SidebarState {
readonly props: SidebarStateProps;
- open = $derived.by(() => this.props.open());
+ open = $derived.by(() => {
+ if (this.#isTablet.current) return false;
+ return this.props.open() ?? this.#isPinnedState.current;
+ });
setOpen: SidebarStateProps['setOpen'];
#isTablet: IsTablet;
#isPinnedState = new PersistedState('sidebar-pinned', true);
- // Effective value comes from the signed-in user's `sidebarHoverExpansion`
- // preference, synced in by `sidebar-provider.svelte`.
- #hoverExpansionEnabled = $state(true);
+ #user = fromStore(userStore);
#isHovered = $state(false);
#hoverTimeout: ReturnType<typeof setTimeout> | null = null;
state = $derived.by(() => (this.open ? 'expanded' : 'collapsed'));
@@ -38,20 +41,8 @@ class SidebarState {
this.setOpen = props.setOpen;
this.#isTablet = new IsTablet();
this.props = props;
-
- // Sync the open state based on pinning preference and screen size
- $effect(() => {
- // On tablet, always collapse regardless of pinning preference
- if (this.#isTablet.current) {
- if (this.open) {
- this.setOpen(false);
- }
- } else {
- // On desktop, respect the pinning preference
- if (this.open !== this.#isPinnedState.current) {
- this.setOpen(this.#isPinnedState.current);
- }
- }
+ onDestroy(() => {
+ if (this.#hoverTimeout !== null) clearTimeout(this.#hoverTimeout);
});
}
@@ -67,19 +58,14 @@ class SidebarState {
// Getter for pinning preference
get isPinned() {
- return this.#isPinnedState.current;
+ return this.props.open() ?? this.#isPinnedState.current;
}
// Getter for hover expansion preference
get hoverExpansionEnabled() {
- return this.#hoverExpansionEnabled;
+ return this.#user.current?.preferences?.sidebarHoverExpansion ?? true;
}
- // Setter for hover expansion preference
- setHoverExpansion = (enabled: boolean) => {
- this.#hoverExpansionEnabled = enabled;
- };
-
// Derived state that shows if sidebar should be visually expanded (either open or hovered)
get isExpanded() {
// In desktop mode: expanded if open OR (collapsed AND hovered AND hover expansion is enabled)
@@ -88,7 +74,7 @@ class SidebarState {
return this.#isHovered;
}
// Only consider hover state for expansion if hover expansion is enabled
- const shouldExpandOnHover = !this.open && this.#isHovered && this.#hoverExpansionEnabled;
+ const shouldExpandOnHover = !this.open && this.#isHovered && this.hoverExpansionEnabled;
return this.open || shouldExpandOnHover;
}
@@ -129,7 +115,7 @@ class SidebarState {
toggle = () => {
if (!this.#isTablet.current) {
// On desktop, toggle the pinning preference
- this.#isPinnedState.current = !this.#isPinnedState.current;
+ this.#isPinnedState.current = !this.isPinned;
return this.setOpen(this.#isPinnedState.current);
}
};
diff --git a/frontend/src/lib/components/ui/sidebar/sidebar-provider.svelte b/frontend/src/lib/components/ui/sidebar/sidebar-provider.svelte
index 3c6968fcf..7091b77ad 100644
--- a/frontend/src/lib/components/ui/sidebar/sidebar-provider.svelte
+++ b/frontend/src/lib/components/ui/sidebar/sidebar-provider.svelte
@@ -4,16 +4,11 @@
import type { HTMLAttributes } from 'svelte/elements';
import { SIDEBAR_COOKIE_MAX_AGE, SIDEBAR_COOKIE_NAME, SIDEBAR_WIDTH, SIDEBAR_WIDTH_ICON } from './constants.js';
import { setSidebar } from './context.svelte.js';
- import { IsTablet } from '#lib/hooks/is-tablet.svelte.js';
- import { IsMobile } from '#lib/hooks/is-mobile.svelte.js';
- import { PersistedState } from 'runed';
import userStore from '#lib/stores/user-store.js';
- const persistedPinned = new PersistedState('sidebar-pinned', true);
-
let {
ref = $bindable(null),
- open = $bindable(persistedPinned.current),
+ open = $bindable<boolean | undefined>(undefined),
onOpenChange = () => {},
class: className,
style,
@@ -24,46 +19,16 @@
onOpenChange?: (open: boolean) => void;
} = $props();
- // Initialize breakpoint detection utilities
- const isTablet = new IsTablet();
- const isMobile = new IsMobile();
- let initialAdjustmentDone = $state(false);
-
- // Set initial state based on screen size (only runs once)
- $effect(() => {
- if (!initialAdjustmentDone) {
- // On tablet screens (but not mobile), force collapse the sidebar
- if (isTablet.current && !isMobile.current) {
- open = false;
- }
- // On desktop screens (1024px and above), auto-expand the sidebar
- else if (!isTablet.current && !isMobile.current && !open) {
- open = true;
- }
- initialAdjustmentDone = true;
- }
- });
-
const sidebar = setSidebar({
open: () => open,
setOpen: (value: boolean) => {
- // Don't allow expanding sidebar on tablet screens
- if (isTablet.current && !isMobile.current && value === true) {
- return;
- }
-
- open = value;
+ if (open !== undefined) open = value;
onOpenChange(value);
// This sets the cookie to keep the sidebar state.
- document.cookie = `${SIDEBAR_COOKIE_NAME}=${open}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
+ document.cookie = `${SIDEBAR_COOKIE_NAME}=${value}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
}
});
-
- // Sync sidebar hover expansion with the signed-in user's preference
- $effect(() => {
- sidebar.setHoverExpansion($userStore?.preferences?.sidebarHoverExpansion ?? true);
- });
</script>
<svelte:window
@@ -77,7 +42,7 @@
<Tooltip.Provider delayDuration={0}>
<div
data-slot="sidebar-wrapper"
- style="--sidebar-width: {SIDEBAR_WIDTH}; --sidebar-width-icon: {SIDEBAR_WIDTH_ICON}; --sidebar-gap-width: {open
+ style="--sidebar-width: {SIDEBAR_WIDTH}; --sidebar-width-icon: {SIDEBAR_WIDTH_ICON}; --sidebar-gap-width: {sidebar.open
? SIDEBAR_WIDTH
: SIDEBAR_WIDTH_ICON}; {style}"
class={cn('group/sidebar-wrapper flex h-dvh w-full has-data-[variant=inset]:bg-sidebar', className)}
diff --git a/frontend/src/lib/components/ui/virtualizer.svelte.ts b/frontend/src/lib/components/ui/virtualizer.svelte.ts
index 38a810c48..72c34c609 100644
--- a/frontend/src/lib/components/ui/virtualizer.svelte.ts
+++ b/frontend/src/lib/components/ui/virtualizer.svelte.ts
@@ -1,3 +1,4 @@
+import { onMount } from 'svelte';
import {
Virtualizer,
elementScroll,
@@ -62,7 +63,7 @@ export function createVirtualizer<TScroll extends Element, TItem extends Element
});
// Attach scroll/resize observers after the DOM (and the bound scroll element) exists.
- $effect(() => instance._didMount());
+ onMount(() => instance._didMount());
return {
get virtualItems() {
diff --git a/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte b/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
index c1b068550..59db8c57d 100644
--- a/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
+++ b/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
@@ -9,33 +9,27 @@
import type { VulnerabilityScanSummary } from '#lib/types/environment.js';
import { m } from '#lib/paraglide/messages.js';
import { formatTime, nowInstantString } from '#lib/utils/formatting.js';
- import { queryKeys } from '#lib/query/query-keys.js';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { vulnerabilityService } from '#lib/services/vulnerability-service.js';
- import {
- startVulnerabilityScanPolling,
- stabilizeFailedVulnerabilitySummary,
- isVulnerabilityScanInProgress
- } from '#lib/utils/docker.js';
+ import { isVulnerabilityScanInProgress } from '#lib/utils/docker.js';
import { toastVulnerabilityScanStatus } from '#lib/utils/vulnerability.js';
import { ShieldCheckIcon, ShieldAlertIcon, ScanIcon, ShieldXIcon } from '#lib/icons/index.js';
- import { createMutation, useQueryClient } from '@tanstack/svelte-query';
+ import { createMutation } from '@tanstack/svelte-query';
import { mergeProps } from 'bits-ui';
interface Props {
scanSummary?: VulnerabilityScanSummary;
imageId: string;
onScanned?: (data: VulnerabilityScanSummary) => void;
- pollingEnabled?: boolean;
}
- let { scanSummary = $bindable(), imageId, onScanned, pollingEnabled = true }: Props = $props();
+ let { scanSummary = $bindable(), imageId, onScanned }: Props = $props();
let isOpen = $state(false);
- let stopPolling: (() => void) | null = $state(null);
let lastScanRequestedAt = $state<string | null>(null);
- const queryClient = useQueryClient();
+ let destroyed = false;
const scanMutation = createMutation(() => ({
- mutationFn: () => vulnerabilityService.scanImage(imageId)
+ mutationFn: (requestedImageId: string) => vulnerabilityService.scanImage(requestedImageId)
}));
const isScanning = $derived(scanMutation.isPending);
@@ -126,11 +120,14 @@
async function startScan() {
if (isScanning) return;
+ const requestedImageId = imageId;
+ const environmentId = await environmentStore.getCurrentEnvironmentId();
try {
const operationResult1 = await tryCatch(
(async () => {
- const result = await scanMutation.mutateAsync();
+ const result = await scanMutation.mutateAsync(requestedImageId);
+ if (destroyed || requestedImageId !== imageId || environmentId !== environmentStore.selected?.id) return;
if (result) {
lastScanRequestedAt = result.scanTime || nowInstantString();
const summary: VulnerabilityScanSummary = {
@@ -144,12 +141,7 @@
};
scanSummary = summary;
onScanned?.(summary);
- if (isVulnerabilityScanInProgress(result.status) && pollingEnabled) {
- toastVulnerabilityScanStatus(result, { includeStarted: true });
- beginPolling(true);
- } else {
- toastVulnerabilityScanStatus(result);
- }
+ toastVulnerabilityScanStatus(result);
}
})()
);
@@ -164,89 +156,8 @@
}
}
- function stopScanPolling() {
- if (stopPolling) {
- stopPolling();
- stopPolling = null;
- }
- }
-
- function beginPolling(showToast: boolean) {
- if (stopPolling) return;
- const cancel = startVulnerabilityScanPolling(
- imageId,
- (id) =>
- queryClient.fetchQuery({
- queryKey: queryKeys.vulnerabilities.summaryByImage(id),
- queryFn: () => vulnerabilityService.getScanSummary(id),
- staleTime: 0
- }),
- {
- onUpdate: (summary) => {
- scanSummary = summary;
- onScanned?.(summary);
- },
- onComplete: async (summary) => {
- let resolvedSummary = summary;
-
- const operationResult2 = await tryCatch(
- (async () => {
- resolvedSummary = await stabilizeFailedVulnerabilitySummary(
- imageId,
- summary,
- (id) =>
- queryClient.fetchQuery({
- queryKey: queryKeys.vulnerabilities.summaryByImage(id),
- queryFn: () => vulnerabilityService.getScanSummary(id),
- staleTime: 0
- }),
- { scanRequestedAt: lastScanRequestedAt ?? scanSummary?.scanTime }
- );
- })()
- );
- if (operationResult2.error !== null) {
- // Keep original summary when stabilization check fails.
- }
-
- scanSummary = resolvedSummary;
- onScanned?.(resolvedSummary);
-
- if (isVulnerabilityScanInProgress(resolvedSummary.status)) {
- stopScanPolling();
- beginPolling(false);
- return;
- }
-
- stopScanPolling();
- if (showToast) {
- toastVulnerabilityScanStatus(resolvedSummary);
- }
- },
- onError: () => {}
- }
- );
-
- stopPolling = cancel;
- }
-
- $effect(() => {
- if (!pollingEnabled) {
- stopScanPolling();
- return;
- }
- if (!lastScanRequestedAt && scanSummary?.scanTime) {
- lastScanRequestedAt = scanSummary.scanTime;
- }
- const scanning = isVulnerabilityScanInProgress(scanSummary?.status);
- if (scanning) {
- beginPolling(false);
- } else {
- stopScanPolling();
- }
- });
-
onDestroy(() => {
- stopScanPolling();
+ destroyed = true;
});
</script>
diff --git a/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte b/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte
index 981a6ae57..6d95a2d85 100644
--- a/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte
+++ b/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte
@@ -6,6 +6,7 @@
import FixedCell from '#lib/components/vulnerability/fixed-cell.svelte';
import SeverityBadge from '#lib/components/vulnerability/severity-badge.svelte';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { Spinner } from '#lib/components/ui/spinner/index.js';
import { Badge, type BadgeVariant } from '#lib/components/ui/badge/index.js';
@@ -21,7 +22,8 @@
getSeverityIconVariant,
getSeverityLabel
} from '#lib/utils/vulnerability.js';
- import { useQueryClient } from '@tanstack/svelte-query';
+ import { createQuery } from '@tanstack/svelte-query';
+ import { tick } from 'svelte';
interface Props {
scan?: VulnerabilityScanResult | null;
@@ -30,7 +32,6 @@
}
let { scan, isScanning = false, onScan }: Props = $props();
- const queryClient = useQueryClient();
const DEFAULT_PAGE_SIZE = 20;
@@ -49,17 +50,6 @@
sort: { column: 'vulnSeverity', direction: 'desc' }
});
- let vulnerabilityItems = $state<Paginated<VulnerabilityRow>>({
- data: [],
- pagination: {
- totalPages: 1,
- totalItems: 0,
- currentPage: 1,
- itemsPerPage: DEFAULT_PAGE_SIZE,
- grandTotalItems: 0
- }
- });
-
// fallow-ignore-next-line code-duplication -- parallel vulnerability views over different row types; cell logic already shared via components
const columns = $derived([
{ accessorKey: 'vulnerabilityId', title: 'CVE', cell: CveCol },
@@ -166,68 +156,46 @@
return [vuln.vulnerabilityId, vuln.pkgName, vuln.installedVersion ?? '', vuln.fixedVersion ?? '', String(index)].join('-');
}
- async function refreshVulnerabilityTable(options: SearchPaginationSortRequest) {
- if (!scan?.imageId) {
- const empty: Paginated<VulnerabilityRow> = {
- data: [],
- pagination: {
- totalPages: 1,
- totalItems: 0,
- currentPage: 1,
- itemsPerPage: DEFAULT_PAGE_SIZE,
- grandTotalItems: 0
- }
- };
- vulnerabilityItems = empty;
- return empty;
+ const vulnerabilityQuery = createQuery(() => {
+ const imageId = scan?.imageId ?? '';
+ const environmentId = environmentStore.selected?.id ?? '0';
+ const options = vulnerabilityRequestOptions;
+ const filters = { ...(options.filters ?? {}) };
+ if (filters['vulnSeverity']) {
+ filters['severity'] = filters['vulnSeverity'];
+ delete filters['vulnSeverity'];
}
-
- const mergedFilters = { ...(options.filters ?? {}) };
- if (mergedFilters['vulnSeverity']) {
- mergedFilters['severity'] = mergedFilters['vulnSeverity'];
- delete mergedFilters['vulnSeverity'];
- }
-
- const sort = options.sort?.column === 'vulnSeverity' ? { ...options.sort, column: 'severity' } : options.sort;
-
- const request: SearchPaginationSortRequest = {
- ...options,
- sort,
- filters: Object.keys(mergedFilters).length ? mergedFilters : undefined
+ const request: SearchPaginationSortRequest = { ...options, filters: undefined };
+ if (Object.keys(filters).length) request.filters = filters;
+ if (options.sort?.column === 'vulnSeverity') request.sort = { ...options.sort, column: 'severity' };
+ const offset = ((request.pagination?.page ?? 1) - 1) * (request.pagination?.limit ?? DEFAULT_PAGE_SIZE);
+ return {
+ queryKey: [...queryKeys.vulnerabilities.imageRows(imageId, request), environmentId, scan?.scanTime],
+ enabled: !!imageId && scan?.status === 'completed' && (resolvedSummary?.total ?? 0) > 0,
+ queryFn: async ({ signal }) => {
+ await environmentStore.ready;
+ signal.throwIfAborted();
+ return vulnerabilityService.getImageVulnerabilities(imageId, request);
+ },
+ select: (response: Paginated<VulnType>): Paginated<VulnerabilityRow> => ({
+ ...response,
+ data: response.data.map((item, index) => ({ ...item, id: getVulnerabilityKey(item, offset + index) }))
+ })
};
+ });
+ const vulnerabilityItems = $derived<Paginated<VulnerabilityRow>>(
+ vulnerabilityQuery.data ?? {
+ data: [],
+ pagination: { totalPages: 1, totalItems: 0, currentPage: 1, itemsPerPage: DEFAULT_PAGE_SIZE, grandTotalItems: 0 }
+ }
+ );
- const response = await queryClient.fetchQuery({
- queryKey: queryKeys.vulnerabilities.imageRows(scan.imageId, request),
- queryFn: () => vulnerabilityService.getImageVulnerabilities(scan.imageId, request),
- staleTime: 0
- });
- const page = request.pagination?.page ?? 1;
- const limit = request.pagination?.limit ?? DEFAULT_PAGE_SIZE;
- const offset = (page - 1) * limit;
- const mapped: Paginated<VulnerabilityRow> = {
- ...response,
- data: (response.data ?? []).map((item, index) => ({
- ...item,
- id: getVulnerabilityKey(item, offset + index)
- }))
- };
- vulnerabilityItems = mapped;
- return mapped;
+ async function refreshVulnerabilityTable(options: SearchPaginationSortRequest) {
+ vulnerabilityRequestOptions = options;
+ await tick();
+ if (scan?.imageId && scan.status === 'completed') await vulnerabilityQuery.refetch({ throwOnError: true });
+ return vulnerabilityItems;
}
-
- let lastScanKey = '';
- $effect(() => {
- const scanKey = scan ? `${scan.imageId}:${scan.scanTime}` : '';
- const totalVulns = resolvedSummary?.total ?? 0;
- if (!scan?.imageId || scan?.status !== 'completed' || totalVulns === 0) {
- lastScanKey = scanKey;
- return;
- }
- if (scanKey && scanKey !== lastScanKey) {
- lastScanKey = scanKey;
- void refreshVulnerabilityTable(vulnerabilityRequestOptions);
- }
- });
</script>
<!-- fallow-ignore-next-line code-duplication -- parallel vulnerability views over different row types; cell logic already shared via components -->
diff --git a/frontend/src/lib/hooks/use-backup-activity.svelte.ts b/frontend/src/lib/hooks/use-backup-activity.svelte.ts
index b98cd2151..a6fe71c93 100644
--- a/frontend/src/lib/hooks/use-backup-activity.svelte.ts
+++ b/frontend/src/lib/hooks/use-backup-activity.svelte.ts
@@ -1,11 +1,12 @@
import { tryCatch } from '#lib/utils/try-catch.js';
-import { untrack } from 'svelte';
+import { onMount } from 'svelte';
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { queryKeys } from '#lib/query/query-keys.js';
import { activityService } from '#lib/services/activity-service.js';
-import { activityStore } from '#lib/stores/activity.store.svelte.js';
+import { clientStream } from '#lib/stores/client-stream.svelte.js';
+import { STREAM_CHANNEL_ACTIVITIES } from '#lib/services/stream-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
-import type { Activity } from '#lib/types/activity.type.js';
+import type { Activity, ActivityStreamEvent } from '#lib/types/activity.type.js';
export function useBackupActivity(
getEnvironmentId: () => string,
@@ -19,6 +20,7 @@ export function useBackupActivity(
const activeQuery = createQuery(() => {
const environmentId = getEnvironmentId();
const discover = getDiscovery();
+ const pollWithoutActivity = !!discover || !clientStream.streamConnected;
return {
queryKey,
queryFn: async ({ signal }): Promise<string[]> => {
@@ -42,40 +44,58 @@ export function useBackupActivity(
}
return activities.filter(matches).map((activity) => activity.id);
},
- refetchInterval: (query) => (discover || query.state.data?.length ? 5000 : false),
+ refetchInterval: (query) => {
+ if (pollWithoutActivity || query.state.data?.length) return 5000;
+ return false;
+ },
refetchIntervalInBackground: true,
staleTime: 0
};
});
const activeIds = $derived(activeQuery.data ?? []);
- $effect(() => {
- if (!activeQuery.dataUpdatedAt) return;
- untrack(() => {
- void tryCatch(onChange()).then((result) => {
- if (result.error !== null) {
- const error = result.error;
- return console.warn('Failed to refresh backup history', error);
- } else {
- return result.data;
- }
- });
+ function refreshHistory() {
+ void tryCatch(onChange()).then((result) => {
+ if (result.error !== null) console.warn('Failed to refresh backup history', result.error);
});
- });
+ }
- $effect(() => {
- const environmentId = getEnvironmentId();
- const key = queryKey;
- activityStore.connected;
- const events = activityStore.activities.filter(
- (activity) => (activity.sourceEnvironmentId || activity.environmentId) === environmentId && matches(activity)
- );
- // Include progress changes as well as terminal transitions.
- JSON.stringify(events);
- untrack(() => {
- void queryClient.cancelQueries({ queryKey: key, exact: true });
- void queryClient.invalidateQueries({ queryKey: key, exact: true });
+ onMount(() => {
+ const cache = queryClient.getQueryCache();
+ const unsubscribeCache = cache.subscribe((event) => {
+ if (event.type !== 'updated' || event.action.type !== 'success') return;
+ if (event.query === cache.find({ queryKey, exact: true })) refreshHistory();
});
+ if (activeQuery.dataUpdatedAt) refreshHistory();
+
+ const unsubscribeStream = clientStream.subscribe(STREAM_CHANNEL_ACTIVITIES, {
+ onConnected() {
+ void queryClient.invalidateQueries({ queryKey, exact: true });
+ },
+ onEvent(payload) {
+ const event = payload as ActivityStreamEvent;
+ const environmentId = getEnvironmentId();
+ if ((event.environmentId || '0') !== environmentId) return;
+ let activities: Activity[] = [];
+ if (event.type === 'snapshot') activities = event.activities ?? [];
+ else if (event.activity) activities = [event.activity];
+ const relevant = activities.some(
+ (activity) =>
+ (activity.sourceEnvironmentId || activity.environmentId || event.environmentId || '0') === environmentId &&
+ matches(activity)
+ );
+ const activeSnapshot = event.type === 'snapshot' && activeIds.length > 0;
+ const activeMessage = event.type === 'message' && activeIds.includes(event.message?.activityId ?? event.activityId ?? '');
+ if (!relevant && !activeSnapshot && !activeMessage) return;
+ const key = queryKey;
+ void queryClient.cancelQueries({ queryKey: key, exact: true });
+ void queryClient.invalidateQueries({ queryKey: key, exact: true });
+ }
+ });
+ return () => {
+ unsubscribeCache();
+ unsubscribeStream();
+ };
});
return {
@@ -86,7 +106,10 @@ export function useBackupActivity(
// Cancel older discovery before adding the accepted operation to the cache.
void queryClient.cancelQueries({ queryKey, exact: true });
if (activityId) {
- queryClient.setQueryData<string[]>(queryKey, (ids = []) => (ids.includes(activityId) ? ids : [...ids, activityId]));
+ queryClient.setQueryData<string[]>(queryKey, (ids = []) => {
+ if (ids.includes(activityId)) return ids;
+ return [...ids, activityId];
+ });
}
void queryClient.invalidateQueries({ queryKey, exact: true });
}
diff --git a/frontend/src/lib/hooks/use-easy-join-candidates.svelte.ts b/frontend/src/lib/hooks/use-easy-join-candidates.svelte.ts
index 90e921e2f..daec8038f 100644
--- a/frontend/src/lib/hooks/use-easy-join-candidates.svelte.ts
+++ b/frontend/src/lib/hooks/use-easy-join-candidates.svelte.ts
@@ -31,7 +31,10 @@ export function useEasyJoinCandidates() {
gcTime: 0
};
});
- const candidates = $derived(canDiscover && !candidatesQuery.isError ? (candidatesQuery.data ?? []) : []);
+ const candidates = $derived.by(() => {
+ if (!canDiscover || candidatesQuery.isError) return [];
+ return candidatesQuery.data ?? [];
+ });
return {
get managerEnvironmentId() {
diff --git a/frontend/src/lib/hooks/use-environment-refresh.svelte.ts b/frontend/src/lib/hooks/use-environment-refresh.svelte.ts
index 2ddc5bd5d..35c3d326b 100644
--- a/frontend/src/lib/hooks/use-environment-refresh.svelte.ts
+++ b/frontend/src/lib/hooks/use-environment-refresh.svelte.ts
@@ -1,24 +1,23 @@
+import { onMount } from 'svelte';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
-/**
- * Creates an effect that triggers a callback when the environment changes.
- * Returns a cleanup function and tracks the last environment ID internally.
- */
+// Refresh only when the selected environment ID changes after initial selection.
export function useEnvironmentRefresh(onRefresh: () => void | Promise<void>) {
- let lastEnvId: string | null = $state(null);
+ onMount(() => {
+ let lastEnvId = environmentStore.selected?.id ?? null;
- $effect(() => {
- const env = environmentStore.selected;
- if (!env) return;
+ return environmentStore.subscribeSelected((env) => {
+ if (!env) return;
- if (lastEnvId === null) {
- lastEnvId = env.id;
- return;
- }
+ if (lastEnvId === null) {
+ lastEnvId = env.id;
+ return;
+ }
- if (env.id !== lastEnvId) {
- lastEnvId = env.id;
- onRefresh();
- }
+ if (env.id !== lastEnvId) {
+ lastEnvId = env.id;
+ onRefresh();
+ }
+ });
});
}
diff --git a/frontend/src/lib/hooks/use-log-preferences.svelte.ts b/frontend/src/lib/hooks/use-log-preferences.svelte.ts
new file mode 100644
index 000000000..6552f0668
--- /dev/null
+++ b/frontend/src/lib/hooks/use-log-preferences.svelte.ts
@@ -0,0 +1,29 @@
+import { PersistedState } from 'runed';
+
+export class UseLogPreferences {
+ selectedTail = new PersistedState('arcane_log_tail_lines', '100');
+ autoStart = new PersistedState('arcane_log_auto_start', 'false');
+ parsedJson = new PersistedState('arcane_log_json_parsing_v3', 'false');
+
+ get tailLines() {
+ const selectedTail = this.selectedTail.current || '100';
+ if (selectedTail === 'all') return 999999;
+ return parseInt(selectedTail, 10);
+ }
+
+ get autoStartLogs() {
+ return this.autoStart.current === 'true';
+ }
+
+ set autoStartLogs(enabled: boolean) {
+ this.autoStart.current = String(enabled);
+ }
+
+ // The viewer may enable parsed mode for this session without persisting it.
+ showParsedJson = $derived(this.parsedJson.current === 'true');
+
+ setParsedMode(enabled: boolean) {
+ this.parsedJson.current = String(enabled);
+ this.showParsedJson = enabled;
+ }
+}
diff --git a/frontend/src/lib/hooks/use-settings-form.svelte.ts b/frontend/src/lib/hooks/use-settings-form.svelte.ts
index a016ac023..7121bebad 100644
--- a/frontend/src/lib/hooks/use-settings-form.svelte.ts
+++ b/frontend/src/lib/hooks/use-settings-form.svelte.ts
@@ -1,16 +1,10 @@
-import { getContext } from 'svelte';
+import { getContext, onDestroy } from 'svelte';
import settingsStore from '#lib/stores/config-store.js';
import { settingsService } from '#lib/services/settings-service.js';
import type { Settings } from '#lib/types/settings.js';
import { tryCatch } from '#lib/utils/try-catch.js';
-import type { Readable } from 'svelte/store';
-
-type SettingsFormState = {
- hasChanges: boolean;
- isLoading: boolean;
- saveFunction?: () => Promise<void> | void;
- resetFunction?: () => void;
-};
+import { fromStore, type Readable } from 'svelte/store';
+import type { SettingsFormContext } from '#lib/types/settings-form.js';
type SettingsPayload = Partial<Settings> & Record<string, unknown>;
@@ -29,42 +23,31 @@ export class UseSettingsForm<
TSaveData extends SettingsPayload
> {
#isLoading = $state(false);
- #formValues = $state<TFormInputs | null>(null);
+ #formValues: { readonly current: TFormInputs };
#saveFunction: (() => Promise<void> | void) | null = null;
#resetFunction: (() => void) | null = null;
- private formState: SettingsFormState | undefined;
+ private formContext: SettingsFormContext | undefined;
private getCurrentSettings: () => TSaveData;
private customOnSave?: (data: TSaveData) => Promise<void>;
constructor({ formInputs, getCurrentSettings, onSave }: Options<TFormInputs, TSaveData>) {
this.getCurrentSettings = getCurrentSettings;
this.customOnSave = onSave;
+ this.#formValues = fromStore(formInputs);
- try {
- this.formState = getContext('settingsFormState') as SettingsFormState | undefined;
- } catch {
- // Context not available
- }
-
- // Subscribe to form inputs store to track changes
- formInputs.subscribe((value) => {
- this.#formValues = value;
- });
+ this.formContext = getContext<SettingsFormContext | undefined>('settingsFormState');
- $effect(() => {
- // Sync to external context (side effect)
- if (this.formState) {
- this.formState.hasChanges = this.hasChanges;
- this.formState.isLoading = this.isLoading;
- if (this.#saveFunction) this.formState.saveFunction = this.#saveFunction;
- if (this.#resetFunction) this.formState.resetFunction = this.#resetFunction;
- }
- });
+ if (this.formContext) {
+ onDestroy(() => {
+ if (this.formContext?.activeForm === this) {
+ this.formContext.activeForm = undefined;
+ }
+ });
+ }
}
#hasChanges = $derived.by(() => {
- const currentFormValues = this.#formValues;
- if (!currentFormValues) return false;
+ const currentFormValues = this.#formValues.current;
const settingsToCompare = this.getCurrentSettings();
const keys = Object.keys(currentFormValues) as (keyof TFormInputs)[];
@@ -101,6 +84,7 @@ export class UseSettingsForm<
registerFormActions(saveFunction: () => Promise<void> | void, resetFunction: () => void) {
this.#saveFunction = saveFunction;
this.#resetFunction = resetFunction;
+ if (this.formContext) this.formContext.activeForm = this;
}
setLoading(loading: boolean) {
@@ -114,4 +98,12 @@ export class UseSettingsForm<
get isLoading() {
return this.#isLoading;
}
+
+ get saveFunction() {
+ return this.#saveFunction ?? undefined;
+ }
+
+ get resetFunction() {
+ return this.#resetFunction ?? undefined;
+ }
}
diff --git a/frontend/src/lib/hooks/use-url-tab.svelte.ts b/frontend/src/lib/hooks/use-url-tab.svelte.ts
index e2f87952e..b366682c2 100644
--- a/frontend/src/lib/hooks/use-url-tab.svelte.ts
+++ b/frontend/src/lib/hooks/use-url-tab.svelte.ts
@@ -19,8 +19,7 @@ export function useUrlTab<T extends string>({
let pendingUrlUpdate = Promise.resolve();
function currentUrl() {
- const reactiveUrl = page.url;
- return typeof window === 'undefined' ? new URL(reactiveUrl.href) : new URL(window.location.href);
+ return new URL((page.shallow?.url ?? page.url).href);
}
function updateUrl(url: URL) {
@@ -43,18 +42,17 @@ export function useUrlTab<T extends string>({
);
}
- function resolveTab(url = currentUrl()) {
+ function resolveTab(requested: string | null) {
const tabs = validTabs();
const defaultValue = defaultTab();
const fallback = tabs.includes(defaultValue) ? defaultValue : (tabs[0] ?? defaultValue);
- const requested = url.searchParams.get('tab');
if (!requested) return fallback;
const aliased = aliases()[requested] ?? requested;
return tabs.includes(aliased as T) ? (aliased as T) : fallback;
}
- let value = $state<T>(resolveTab());
+ let value = $derived(resolveTab(currentUrl().searchParams.get('tab')));
let mounted = $state(false);
onMount(() => {
@@ -79,12 +77,11 @@ export function useUrlTab<T extends string>({
$effect(() => {
const url = currentUrl();
- const selected = resolveTab(url);
+ const selected = resolveTab(url.searchParams.get('tab'));
if (mounted && ready() && url.searchParams.get('tab') !== selected) {
url.searchParams.set('tab', selected);
- updateUrl(url);
+ untrack(() => updateUrl(url));
}
- if (untrack(() => value) !== selected) value = selected;
});
return {
diff --git a/frontend/src/lib/layouts/resource-detail-layout.svelte b/frontend/src/lib/layouts/resource-detail-layout.svelte
index 7b563b868..7db290277 100644
--- a/frontend/src/lib/layouts/resource-detail-layout.svelte
+++ b/frontend/src/lib/layouts/resource-detail-layout.svelte
@@ -33,16 +33,12 @@
let scrollY = $state(0);
const showFloatingHeader = $derived(scrollY > 120);
- $effect(() => {
- const onScroll = () => (scrollY = window.scrollY);
- window.addEventListener('scroll', onScroll, { passive: true });
- return () => window.removeEventListener('scroll', onScroll);
- });
-
const primaryAction = $derived(actions[0]);
const secondaryActions = $derived(actions.slice(1));
</script>
+<svelte:window bind:scrollY />
+
{#snippet ActionMenu(items: DetailAction[], tone: 'ghost' | 'outline', sizeClass: string, minWidthClass: string)}
{#if items.length > 0}
<DropdownMenu.Root>
diff --git a/frontend/src/lib/layouts/settings-page-layout.svelte b/frontend/src/lib/layouts/settings-page-layout.svelte
index bec0583c0..a2ea3ae91 100644
--- a/frontend/src/lib/layouts/settings-page-layout.svelte
+++ b/frontend/src/lib/layouts/settings-page-layout.svelte
@@ -5,6 +5,7 @@
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
import { getContext } from 'svelte';
+ import type { SettingsFormContext } from '#lib/types/settings-form.js';
import { m } from '#lib/paraglide/messages.js';
import { EllipsisIcon, ResetIcon, type IconType, ArrowDownIcon } from '#lib/icons/index.js';
import { cn } from '#lib/utils.js';
@@ -39,12 +40,8 @@
const mobileVisibleButtons = $derived(actionButtons.filter((btn) => btn.showOnMobile));
const mobileDropdownButtons = $derived(actionButtons.filter((btn) => !btn.showOnMobile));
- const formState = getContext<{
- hasChanges: boolean;
- isLoading: boolean;
- saveFunction: (() => Promise<void>) | null;
- resetFunction: (() => void) | null;
- }>('settingsFormState');
+ const formContext = getContext<SettingsFormContext | undefined>('settingsFormState');
+ const formState = $derived(formContext?.activeForm);
</script>
{#snippet ActionOptions(options: SettingsActionOption[], disabled = false, showIcons = true)}
@@ -155,7 +152,7 @@
action="base"
tone="outline"
size="sm"
- onclick={() => formState.resetFunction?.()}
+ onclick={() => formState?.resetFunction?.()}
disabled={formState.isLoading}
class="gap-2"
icon={ResetIcon}
@@ -165,7 +162,7 @@
<ArcaneButton
action="save"
- onclick={() => formState.saveFunction?.()}
+ onclick={() => formState?.saveFunction?.()}
disabled={!formState.hasChanges}
loading={formState.isLoading}
size="sm"
diff --git a/frontend/src/lib/layouts/tabbed-page-layout.svelte b/frontend/src/lib/layouts/tabbed-page-layout.svelte
index 988aa5024..475e80179 100644
--- a/frontend/src/lib/layouts/tabbed-page-layout.svelte
+++ b/frontend/src/lib/layouts/tabbed-page-layout.svelte
@@ -31,29 +31,18 @@
subHeader,
tabContent,
class: className = '',
- showFloatingHeader = false
+ showFloatingHeader
}: Props = $props();
- let scrollContainer = $state<HTMLDivElement | null>(null);
-
- $effect(() => {
- const getScrollTop = () => (scrollContainer ? scrollContainer.scrollTop : window.scrollY);
- const onScroll = () => {
- showFloatingHeader = getScrollTop() > 100;
- };
-
- const target: Window | HTMLDivElement = scrollContainer ?? window;
- target.addEventListener('scroll', onScroll as EventListener);
- onScroll();
- return () => target.removeEventListener('scroll', onScroll as EventListener);
- });
+ let scrollTop = $state(0);
+ const floatingHeaderVisible = $derived(showFloatingHeader ?? scrollTop > 100);
</script>
<div class={cn('flex h-full min-h-0 flex-col bg-background', className)}>
<Tabs.Root value={selectedTab} class="flex min-h-0 w-full flex-1 flex-col">
<div
class="sticky top-0 border-b transition-opacity duration-300"
- style="opacity: {showFloatingHeader ? 0 : 1}; pointer-events: {showFloatingHeader ? 'none' : 'auto'};"
+ style="opacity: {floatingHeaderVisible ? 0 : 1}; pointer-events: {floatingHeaderVisible ? 'none' : 'auto'};"
>
<div class="max-w-full px-4 py-3">
<div class="flex items-start justify-between gap-3">
@@ -83,7 +72,7 @@
</div>
</div>
- {#if showFloatingHeader}
+ {#if floatingHeaderVisible}
<div class="fixed top-4 left-1/2 z-[var(--arcane-z-page-floating)] -translate-x-1/2">
<div
class="bubble-shadow-lg rounded-lg border border-border/50 bg-popover/90 px-4 py-3 backdrop-blur-md supports-backdrop-filter:bg-popover/80"
@@ -101,7 +90,7 @@
</div>
{/if}
- <div class="min-h-0 flex-1 overflow-y-auto" bind:this={scrollContainer}>
+ <div class="min-h-0 flex-1 overflow-y-auto" onscroll={(event) => (scrollTop = event.currentTarget.scrollTop)}>
<div class="flex h-full min-h-0 flex-col px-1 py-4 pb-2 sm:px-4">
{@render tabContent(selectedTab)}
</div>
diff --git a/frontend/src/lib/query/query-keys.ts b/frontend/src/lib/query/query-keys.ts
index 2895c5c6d..56ca791a9 100644
--- a/frontend/src/lib/query/query-keys.ts
+++ b/frontend/src/lib/query/query-keys.ts
@@ -15,8 +15,12 @@ function stableSerialize(value: unknown): string {
export const queryKeys = {
swarm: {
+ info: (environmentId: string) => ['swarm', environmentId, 'info'] as const,
+ joinTokens: (environmentId: string) => ['swarm', environmentId, 'join-tokens'] as const,
+ unlockKey: (environmentId: string) => ['swarm', environmentId, 'unlock-key'] as const,
joinCandidates: (environmentId: string | null, user: Pick<User, 'id' | 'permissionsByEnv'> | null) =>
- ['swarm', environmentId, 'join-candidates', user?.id ?? null, stableSerialize(user?.permissionsByEnv)] as const
+ ['swarm', environmentId, 'join-candidates', user?.id ?? null, stableSerialize(user?.permissionsByEnv)] as const,
+ serviceTasks: (environmentId: string, serviceId: string) => ['swarm', environmentId, 'service-tasks', serviceId] as const
},
jobs: {
list: (environmentId: string) => ['environment-jobs', environmentId] as const,
@@ -114,7 +118,9 @@ export const queryKeys = {
list: (environmentId: string, options: SearchPaginationSortRequest) =>
['images', environmentId, stableSerialize(options)] as const,
usageCounts: (environmentId: string) => ['images', 'usage-counts', environmentId] as const,
+ history: (environmentId: string, imageId: string) => ['image', environmentId, imageId, 'history'] as const,
detail: (environmentId: string, imageId: string) => ['image', environmentId, imageId] as const,
+ updateInfoByRef: (environmentId: string, imageRef: string) => ['image-update-info', environmentId, imageRef] as const,
updateCheck: (environmentId: string, imageId: string) => ['image-update', environmentId, imageId] as const,
builds: (environmentId: string) => ['images', environmentId, 'builds'] as const,
buildsList: (environmentId: string, options: SearchPaginationSortRequest) =>
@@ -156,6 +162,7 @@ export const queryKeys = {
detail: (environmentId: string, syncId: string) => ['gitops-syncs', environmentId, syncId] as const
},
volumes: {
+ sizes: (environmentId: string) => ['volume-sizes', environmentId] as const,
table: (environmentId: string, options: SearchPaginationSortRequest) =>
['volumes', environmentId, stableSerialize(options)] as const,
detail: (environmentId: string, volumeName: string) => ['volume', environmentId, volumeName] as const,
@@ -163,11 +170,12 @@ export const queryKeys = {
workspaceFile: (environmentId: string, volumeName: string, relativePath: string) =>
['volume', environmentId, volumeName, 'workspace-file', relativePath] as const,
backups: (volumeName: string) => ['volume-backups', volumeName] as const,
- backupHasPath: (backupId: string, path: string) => ['volume-backups', backupId, 'has-path', path] as const
+ backupHasPath: (environmentId: string, volumeName: string, backupId: string, path: string) =>
+ ['volume-backups', environmentId, volumeName, backupId, 'has-path', path] as const
},
vulnerabilities: {
summaryByEnvironment: (environmentId: string) => ['vulnerabilities', 'summary', environmentId] as const,
- summaryByImage: (imageId: string) => ['vulnerabilities', 'image-summary', imageId] as const,
+ scanResult: (environmentId: string, imageId: string) => ['vulnerabilities', 'scan-result', environmentId, imageId] as const,
allByEnvironment: (environmentId: string, request: SearchPaginationSortRequest) =>
['vulnerabilities', 'all', environmentId, stableSerialize(request)] as const,
imageRows: (imageId: string, request: SearchPaginationSortRequest) =>
diff --git a/frontend/src/lib/stores/activity.store.svelte.ts b/frontend/src/lib/stores/activity.store.svelte.ts
index 8696f7ad5..4dcc8040b 100644
--- a/frontend/src/lib/stores/activity.store.svelte.ts
+++ b/frontend/src/lib/stores/activity.store.svelte.ts
@@ -165,6 +165,7 @@ function createActivityStore() {
// Last observed status per activity, for completion-toast transition
// detection. Intentionally non-reactive: only stream handling reads it.
const observedStatusById = new Map<string, ActivityStatus>();
+ const activitySubscribers = new Set<(activities: readonly Activity[]) => void>();
// Toast when an activity this session observed as active reaches
// success/failed while the sheet is closed. Activities that first appear
@@ -352,6 +353,7 @@ function createActivityStore() {
observedStatusById.delete(id);
}
}
+ for (const subscriber of activitySubscribers) subscriber(_activities);
}
function mergeActivityInternal(activity: Activity) {
@@ -544,6 +546,13 @@ function createActivityStore() {
}
return {
+ subscribeActivities(subscriber: (activities: readonly Activity[]) => void): () => void {
+ activitySubscribers.add(subscriber);
+ subscriber(_activities);
+ return () => {
+ activitySubscribers.delete(subscriber);
+ };
+ },
get activities(): Activity[] {
return _activities;
},
diff --git a/frontend/src/lib/types/settings-form.ts b/frontend/src/lib/types/settings-form.ts
new file mode 100644
index 000000000..edc481d2a
--- /dev/null
+++ b/frontend/src/lib/types/settings-form.ts
@@ -0,0 +1,10 @@
+export interface SettingsFormState {
+ readonly hasChanges: boolean;
+ readonly isLoading: boolean;
+ readonly saveFunction?: () => Promise<void> | void;
+ readonly resetFunction?: () => void;
+}
+
+export interface SettingsFormContext {
+ activeForm: SettingsFormState | undefined;
+}
diff --git a/frontend/src/lib/utils/navigation.ts b/frontend/src/lib/utils/navigation.ts
index e6cd42187..f971eb26d 100644
--- a/frontend/src/lib/utils/navigation.ts
+++ b/frontend/src/lib/utils/navigation.ts
@@ -1,6 +1,7 @@
import { browser } from '$app/env';
import { PersistedState } from 'runed';
import { get } from 'svelte/store';
+import { createContext } from 'svelte';
import {
DEFAULT_LANDING_PAGE,
defaultMobileNavigationSettings,
@@ -13,19 +14,10 @@ import userStore from '#lib/stores/user-store.js';
const pinnedItemsStore = new PersistedState('mobile-nav-settings', defaultMobileNavigationSettings);
-type NavigationVisibilityController = {
- resetVisibility: () => void;
-};
-
-let mobileNavController: NavigationVisibilityController | null = null;
-
-export function registerNavigationVisibilityController(controller: NavigationVisibilityController | null) {
- mobileNavController = controller;
-}
-
-export function resetNavigationVisibility() {
- mobileNavController?.resetVisibility();
-}
+export const [getMobileNavigation, setMobileNavigation] = createContext<{
+ readonly settings: MobileNavigationSettings;
+ visible: boolean;
+}>();
export function getEffectiveNavigationSettings(): MobileNavigationSettings {
const preferences = get(userStore)?.preferences;
diff --git a/frontend/src/lib/utils/resource-list-page.svelte.ts b/frontend/src/lib/utils/resource-list-page.svelte.ts
index d71227e91..340266197 100644
--- a/frontend/src/lib/utils/resource-list-page.svelte.ts
+++ b/frontend/src/lib/utils/resource-list-page.svelte.ts
@@ -1,14 +1,12 @@
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
-export class ResourceListPageState<TItems, TReq> {
- items = $state() as TItems;
+export class ResourceListPageState<TReq> {
requestOptions = $state() as TReq;
selectedIds = $state<string[]>([]);
isCreateDialogOpen = $state(false);
envId = $derived(environmentStore.selected?.id || '0');
- constructor(items: TItems, requestOptions: TReq) {
- this.items = items;
+ constructor(requestOptions: TReq) {
this.requestOptions = requestOptions;
}
}
diff --git a/frontend/src/lib/utils/settings-form.ts b/frontend/src/lib/utils/settings-form.ts
index 663781eb2..273843e3b 100644
--- a/frontend/src/lib/utils/settings-form.ts
+++ b/frontend/src/lib/utils/settings-form.ts
@@ -72,22 +72,17 @@ export function createSettingsForm<T extends z.ZodType<any, any>>(config: Settin
};
const resetForm = () => {
- form.reset();
+ form.reset(getCurrentSettings?.() ?? currentSettings);
onReset?.();
};
settingsForm.registerFormActions(onSubmit, resetForm);
- const registerOnMount = () => {
- settingsForm.registerFormActions(onSubmit, resetForm);
- };
-
return {
formInputs,
form,
settingsForm,
onSubmit,
- resetForm,
- registerOnMount
+ resetForm
};
}
diff --git a/frontend/src/lib/utils/settings-load.ts b/frontend/src/lib/utils/settings-load.ts
index a8b75d697..071580c75 100644
--- a/frontend/src/lib/utils/settings-load.ts
+++ b/frontend/src/lib/utils/settings-load.ts
@@ -9,7 +9,7 @@ type ParentWithQueryClient = () => Promise<{
}>;
type QueryClientLike = {
- fetchQuery: <T>(options: { queryKey: unknown; queryFn: () => Promise<T> }) => Promise<T>;
+ query: <T>(options: { queryKey: unknown; queryFn: () => Promise<T> }) => Promise<T>;
};
export async function loadMergedSettingsPage(parent: ParentWithQueryClient, errorContext: string) {
@@ -19,7 +19,7 @@ export async function loadMergedSettingsPage(parent: ParentWithQueryClient, erro
const operationResult = await tryCatch(
(async () => {
- const settings = await client.fetchQuery({
+ const settings = await client.query({
queryKey: queryKeys.settings.byEnvironment(envId),
queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
});
diff --git a/frontend/src/lib/utils/settings.ts b/frontend/src/lib/utils/settings.ts
index 3defdb89a..679bb1da9 100644
--- a/frontend/src/lib/utils/settings.ts
+++ b/frontend/src/lib/utils/settings.ts
@@ -136,11 +136,11 @@ export function createForm<T extends z.ZodType<any, any>>(schema: T, initialValu
return (result.success ? result.data : values) as z.infer<T>;
}
- function reset() {
+ function reset(values: z.infer<T> = initialValues) {
inputsStore.update((inputs) => {
for (const input of Object.keys(inputs)) {
inputs[input as keyof z.infer<T>] = {
- value: initialValues[input as keyof z.infer<T>],
+ value: values[input as keyof z.infer<T>],
error: null
};
}
diff --git a/frontend/src/lib/utils/tables.ts b/frontend/src/lib/utils/tables.ts
index 0e84fb3c1..f0c3b2cc7 100644
--- a/frontend/src/lib/utils/tables.ts
+++ b/frontend/src/lib/utils/tables.ts
@@ -133,7 +133,7 @@ export function resolveInitialListPageRequest(
}
type QueryClientLike = {
- fetchQuery: <T>(options: { queryKey: unknown; queryFn: () => Promise<T> }) => Promise<T>;
+ query: <T>(options: { queryKey: unknown; queryFn: () => Promise<T> }) => Promise<T>;
};
type ParentWithQueryClient = () => Promise<unknown>;
diff --git a/frontend/src/lib/utils/template-load.ts b/frontend/src/lib/utils/template-load.ts
index bc94c9776..2130c20e5 100644
--- a/frontend/src/lib/utils/template-load.ts
+++ b/frontend/src/lib/utils/template-load.ts
@@ -5,7 +5,7 @@ import { variableService } from '#lib/services/variable-service.js';
import type { GlobalVariable } from '#lib/types/variable.js';
type QueryClientLike = {
- fetchQuery: <T>(options: { queryKey: unknown; queryFn: () => Promise<T> }) => Promise<T>;
+ query: <T>(options: { queryKey: unknown; queryFn: () => Promise<T> }) => Promise<T>;
};
type ParentWithQueryClient = () => Promise<{
@@ -23,7 +23,7 @@ export async function loadTemplateAuthoringData(parent: ParentWithQueryClient) {
const [defaultTemplates, templates, globalVariables] = await Promise.all([
tryCatch(
- client.fetchQuery({
+ client.query({
queryKey: queryKeys.templates.defaults(),
queryFn: () => templateService.getDefaultTemplates()
})
@@ -38,7 +38,7 @@ export async function loadTemplateAuthoringData(parent: ParentWithQueryClient) {
}
}),
tryCatch(
- client.fetchQuery({
+ client.query({
queryKey: queryKeys.templates.allTemplates(),
queryFn: () => templateService.getAllTemplates()
})
@@ -53,7 +53,7 @@ export async function loadTemplateAuthoringData(parent: ParentWithQueryClient) {
}
}),
tryCatch(
- client.fetchQuery({
+ client.query({
queryKey: queryKeys.variables.list(),
queryFn: () => variableService.list()
})
@@ -74,7 +74,7 @@ export async function loadTemplateAuthoringData(parent: ParentWithQueryClient) {
export async function loadTemplateContent(client: QueryClientLike, templateId: string) {
return tryCatch(
- client.fetchQuery({
+ client.query({
queryKey: queryKeys.templates.content(templateId),
queryFn: () => templateService.getTemplateContent(templateId)
})
diff --git a/frontend/src/routes/(app)/+layout.svelte b/frontend/src/routes/(app)/+layout.svelte
index 5e0a61442..210b0ee07 100644
--- a/frontend/src/routes/(app)/+layout.svelte
+++ b/frontend/src/routes/(app)/+layout.svelte
@@ -10,7 +10,7 @@
import OperationWatchDialog from '#lib/components/operation-watch-dialog.svelte';
import { IsMobile } from '#lib/hooks/is-mobile.svelte.js';
import { IsTablet } from '#lib/hooks/is-tablet.svelte.js';
- import { getEffectiveLandingPage, getEffectiveNavigationSettings } from '#lib/utils/navigation.js';
+ import { getEffectiveLandingPage, getEffectiveNavigationSettings, setMobileNavigation } from '#lib/utils/navigation.js';
import { browser } from '$app/env';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { environmentStatusStore } from '#lib/stores/environment-status.store.svelte.js';
@@ -38,10 +38,22 @@
const navigationSettings = $derived.by(() => {
// Track the store, not the loader snapshot: saving a preference calls
// userStore.setUser() without re-running load().
- $userStore;
+ void $userStore;
return getEffectiveNavigationSettings();
});
const navigationMode = $derived(navigationSettings.mode);
+ let hiddenNavigationSettings = $state.raw<typeof navigationSettings>();
+ setMobileNavigation({
+ get settings() {
+ return navigationSettings;
+ },
+ get visible() {
+ return !isMobile.current || !navigationSettings.scrollToHide || hiddenNavigationSettings !== navigationSettings;
+ },
+ set visible(value: boolean) {
+ hiddenNavigationSettings = value ? undefined : navigationSettings;
+ }
+ });
const currentEnvId = $derived(environmentStore.selected?.id || '0');
const managementItemsRaw = $derived(getManagementItems(currentEnvId));
const managementItems = $derived(filterByPermissions(managementItemsRaw, user ?? null, currentEnvId, permissionsManifest));
@@ -102,7 +114,6 @@
event.preventDefault();
goto(match.url);
}
- $effect(() => void handleNavigationShortcut);
function flattenNavigationItems(items: NavigationItem[]): NavigationItem[] {
return items.flatMap((item) => [item, ...(item.items ? flattenNavigationItems(item.items) : [])]);
@@ -138,7 +149,7 @@
</main>
{#if isMobile.current}
- <MobileNav {navigationSettings} {user} {versionInformation} {swarmEnabled} {permissionsManifest} />
+ <MobileNav {user} {versionInformation} {swarmEnabled} {permissionsManifest} />
{/if}
</Sidebar.Provider>
diff --git a/frontend/src/routes/(app)/account/+page.svelte b/frontend/src/routes/(app)/account/+page.svelte
index f619352ab..54c60d148 100644
--- a/frontend/src/routes/(app)/account/+page.svelte
+++ b/frontend/src/routes/(app)/account/+page.svelte
@@ -62,38 +62,29 @@
);
const avatarMaxUploadSizeBytes = $derived(avatarUploadLimitBytes(avatarMaxUploadSizeMb));
- let profileDisplayName = $state('');
- let profileEmail = $state('');
+ let profileDraft = $state<{ userId: string; displayName: string; email: string } | null>(null);
+ const activeProfileDraft = $derived.by(() => {
+ if (profileDraft?.userId === currentUser?.id) return profileDraft;
+ return null;
+ });
+ const profileDisplayName = $derived(activeProfileDraft?.displayName ?? currentUser?.displayName ?? '');
+ const profileEmail = $derived(activeProfileDraft?.email ?? currentUser?.email ?? '');
let profileSaving = $state(false);
- let profileLoaded = $state(false);
- let avatarUrl = $state<string>(getDefaultProfilePicture());
+ const avatarUrl = $derived(updateAvatar(currentUser?.email, gravatarEnabled));
let avatarCacheBuster = $state(Temporal.Now.instant().epochMilliseconds);
const avatarSrc = $derived(currentUser?.avatarUrl ? `${currentUser.avatarUrl}?t=${avatarCacheBuster}` : '');
- let cropperAvatarSrc = $derived(avatarSrc || avatarUrl);
+ let cropperAvatarSrc = $state('');
let avatarUploading = $state(false);
- $effect(() => {
- if (!profileLoaded && currentUser) {
- profileDisplayName = currentUser.displayName ?? '';
- profileEmail = currentUser.email ?? '';
- profileLoaded = true;
- }
- });
-
- $effect(() => {
- void updateAvatar(currentUser?.email, gravatarEnabled);
- });
-
const profileDirty = $derived(
profileDisplayName.trim() !== (currentUser?.displayName ?? '') || profileEmail.trim() !== (currentUser?.email ?? '')
);
async function updateAvatar(email: string | undefined, enabled: boolean) {
if (!enabled || !email) {
- avatarUrl = getDefaultProfilePicture();
- return;
+ return getDefaultProfilePicture();
}
const operationResult = await tryCatch(
(async () => {
@@ -103,16 +94,21 @@
const hash = Array.from(new Uint8Array(hashBuffer))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
- avatarUrl = `https://www.gravatar.com/avatar/${hash}?s=128&d=404`;
+ return `https://www.gravatar.com/avatar/${hash}?s=128&d=404`;
})()
);
- if (operationResult.error !== null) {
- avatarUrl = getDefaultProfilePicture();
- }
+ if (operationResult.error !== null) return getDefaultProfilePicture();
+ return operationResult.data;
+ }
+
+ function updateProfileField(field: 'displayName' | 'email', value: string) {
+ if (!currentUser) return;
+ profileDraft = { userId: currentUser.id, displayName: profileDisplayName, email: profileEmail, [field]: value };
}
async function saveProfile() {
if (!currentUser || !profileDirty || profileSaving) return;
+ const submittedDraft = profileDraft;
profileSaving = true;
try {
const operationResult = await tryCatch(
@@ -122,6 +118,7 @@
email: profileEmail.trim()
});
await userStore.setUser(updated);
+ if (profileDraft === submittedDraft) profileDraft = null;
toast.success(m.account_profile_updated());
})()
);
@@ -136,11 +133,6 @@
}
}
- function resetProfile() {
- profileDisplayName = currentUser?.displayName ?? '';
- profileEmail = currentUser?.email ?? '';
- }
-
async function handleCroppedAvatar(url: string) {
avatarUploading = true;
try {
@@ -165,7 +157,7 @@
} finally {
avatarUploading = false;
URL.revokeObjectURL(url);
- if (cropperAvatarSrc === url) cropperAvatarSrc = avatarSrc || avatarUrl;
+ if (cropperAvatarSrc === url) cropperAvatarSrc = '';
}
}
@@ -263,8 +255,12 @@
<Avatar.Root class="size-16 rounded-xl transition-all group-hover/avatar:opacity-80">
{#if avatarSrc}
<Avatar.Image src={avatarSrc} alt={currentUser.displayName ?? currentUser.username} />
- {:else if avatarUrl}
- <Avatar.Image src={avatarUrl} alt={currentUser.displayName ?? currentUser.username} />
+ {:else}
+ {#await avatarUrl}
+ <Avatar.Image src={getDefaultProfilePicture()} alt={currentUser.displayName ?? currentUser.username} />
+ {:then url}
+ <Avatar.Image src={url} alt={currentUser.displayName ?? currentUser.username} />
+ {/await}
{/if}
<Avatar.Fallback class="rounded-xl bg-primary text-xl font-semibold text-primary-foreground">
{(currentUser.displayName ?? currentUser.username).charAt(0).toUpperCase()}
@@ -316,7 +312,7 @@
<div class="grid gap-5 sm:grid-cols-2">
<TextInputWithLabel
id="account-display-name"
- bind:value={profileDisplayName}
+ bind:value={() => profileDisplayName, (value) => updateProfileField('displayName', value)}
label={m.common_display_name()}
placeholder={m.account_display_name_placeholder()}
disabled={isOidcUser}
@@ -324,7 +320,7 @@
<TextInputWithLabel
id="account-email"
type="email"
- bind:value={profileEmail}
+ bind:value={() => profileEmail, (value) => updateProfileField('email', value)}
label={m.common_email()}
placeholder={m.account_email_placeholder()}
disabled={isOidcUser}
@@ -336,7 +332,7 @@
action="cancel"
tone="outline"
customLabel={m.common_reset()}
- onclick={resetProfile}
+ onclick={() => (profileDraft = null)}
disabled={!profileDirty || profileSaving}
/>
<ArcaneButton
diff --git a/frontend/src/routes/(app)/account/account-preferences-panel.svelte b/frontend/src/routes/(app)/account/account-preferences-panel.svelte
index 5d77f4b93..1e76d3927 100644
--- a/frontend/src/routes/(app)/account/account-preferences-panel.svelte
+++ b/frontend/src/routes/(app)/account/account-preferences-panel.svelte
@@ -12,7 +12,7 @@
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.js';
- import { resetNavigationVisibility } from '#lib/utils/navigation.js';
+ import { getMobileNavigation } from '#lib/utils/navigation.js';
import { applyGlassEffects, applyInterfaceAnimations, applyOledMode, DEFAULT_ACCENT_COLOR } from '#lib/utils/theme.js';
import { debounced } from '#lib/utils/ws.js';
import { m } from '#lib/paraglide/messages.js';
@@ -24,6 +24,7 @@
import { cn } from '#lib/utils.js';
import { toast } from 'svelte-sonner';
+ const mobileNavigation = getMobileNavigation();
const currentUser = $derived($userStore);
const preferences = $derived(currentUser?.preferences ?? {});
const applicationThemeValue = $derived<ApplicationTheme>(preferences.applicationTheme ?? 'default');
@@ -86,7 +87,7 @@
function selectMobileNavigationMode(value: 'floating' | 'docked') {
if (value === mobileNavigationMode) return;
- resetNavigationVisibility();
+ mobileNavigation.visible = true;
void savePreferences({ mobileNavigationMode: value });
}
</script>
diff --git a/frontend/src/routes/(app)/containers/+page.ts b/frontend/src/routes/(app)/containers/+page.ts
index 0831a4cab..91e0c322e 100644
--- a/frontend/src/routes/(app)/containers/+page.ts
+++ b/frontend/src/routes/(app)/containers/+page.ts
@@ -19,7 +19,7 @@ export const load: PageLoad = async ({ parent }) => {
let containers;
const operationResult = await tryCatch(
(async () =>
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.containers.list(envId, containerRequestOptions),
queryFn: () => containerService.getContainersForEnvironment(envId, containerRequestOptions)
}))()
diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
index 91b91b28c..94ee458db 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
@@ -52,7 +52,9 @@
import { EditIcon, ImagesIcon, PauseIcon, PlayIcon, ProjectsIcon, UpdateIcon, ZapIcon } from '#lib/icons/index.js';
import { runContainerLifecycleAction, confirmAndUpdateContainer } from '#lib/utils/container-actions.js';
import { imageService } from '#lib/services/image-service.js';
- import type { ImageUpdateInfoDto } from '#lib/types/docker.js';
+ import { createQuery } from '@tanstack/svelte-query';
+ import { queryKeys } from '#lib/query/query-keys.js';
+ import userStore from '#lib/stores/user-store.js';
import { isAutoUpdateIgnored, isAutoUpdateLabelDisabled } from '#lib/utils/container-auto-update.js';
import KillContainerDialog from '../components/kill-container-dialog.svelte';
import { useUrlTab } from '#lib/hooks/use-url-tab.svelte.js';
@@ -158,32 +160,24 @@
let lifecycleStatus = $state<'pausing' | 'unpausing' | ''>('');
const isLifecycleActionPending = $derived(lifecycleStatus !== '');
- let updateInfo = $state<ImageUpdateInfoDto | null>(null);
- let updateLoading = $state(false);
- $effect(() => {
+ const imageUpdateQuery = createQuery(() => {
+ const environmentId = environmentStore.selected?.id;
const image = container?.image;
- if (!image || !canUpdateContainer) {
- updateInfo = null;
- return;
- }
- // A slower lookup for a previous image must not overwrite the current one.
- let current = true;
- tryCatch(
- imageService.getUpdateInfoByRefs([image]).then((infoByRef) => {
- if (current) updateInfo = infoByRef[image] ?? null;
- })
- ).then((result) => {
- if (result.error) {
- if (current) updateInfo = null;
-
- return;
- }
- return result.data;
- });
- return () => {
- current = false;
+ $userStore;
+ return {
+ queryKey: queryKeys.images.updateInfoByRef(environmentId ?? '', image ?? ''),
+ queryFn: async () => {
+ await environmentStore.ready;
+ return imageService.getUpdateInfoByRefs([image!]);
+ },
+ enabled: !!environmentId && !!image && hasPermission('containers:autoupdate', environmentId)
};
});
+ const updateInfo = $derived.by(() => {
+ if (container?.image) return imageUpdateQuery.data?.[container.image] ?? null;
+ return null;
+ });
+ let updateLoading = $state(false);
function handleUpdateContainer() {
if (!container) return;
@@ -535,14 +529,16 @@
<Tabs.Content value="logs" class="h-full">
{#if activeTab === 'logs'}
- <ContainerLogsPanel
- containerId={container?.id}
- {stats}
- {hasInitialStatsLoaded}
- isRunning={!!container.state?.running}
- {cpuLimit}
- bind:autoScroll={autoScrollLogs}
- />
+ {#key container?.id}
+ <ContainerLogsPanel
+ containerId={container?.id}
+ {stats}
+ {hasInitialStatsLoaded}
+ isRunning={!!container.state?.running}
+ {cpuLimit}
+ bind:autoScroll={autoScrollLogs}
+ />
+ {/key}
{/if}
</Tabs.Content>
@@ -586,12 +582,14 @@
{/snippet}
{#if container}
- <ContainerDetailStatsSync
- containerId={container.id}
- enabled={(activeTab === 'stats' || activeTab === 'logs') && !!container.state?.running}
- bind:stats
- bind:hasInitialStatsLoaded
- />
+ {#key `${currentEnvId}:${container.id}`}
+ <ContainerDetailStatsSync
+ containerId={container.id}
+ enabled={(activeTab === 'stats' || activeTab === 'logs') && !!container.state?.running}
+ bind:stats
+ bind:hasInitialStatsLoaded
+ />
+ {/key}
<TabbedPageLayout {backUrl} backLabel={m.common_back()} {tabItems} selectedTab={activeTab} {onTabChange}>
{#snippet headerInfo()}
diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.ts b/frontend/src/routes/(app)/containers/[containerId]/+page.ts
index 5ed86879b..8a4b37a04 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/+page.ts
+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.ts
@@ -15,11 +15,11 @@ export const load: PageLoad = async ({ params, parent }) => {
const operationResult = await tryCatch(
(async () => {
const [container, settings] = await Promise.all([
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.containers.detail(envId, containerId),
queryFn: () => containerService.getContainerForEnvironment(envId, containerId)
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.settings.byEnvironment(envId),
queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
})
@@ -38,13 +38,13 @@ export const load: PageLoad = async ({ params, parent }) => {
search: composeProjectName,
pagination: { page: 1, limit: 100 } // Ensure we don't miss projects beyond default page size
};
- const projectsResult = await queryClient.fetchQuery({
+ const projectsResult = await queryClient.query({
queryKey: queryKeys.projects.list(envId, searchOptions),
queryFn: () => projectService.getProjectsForEnvironment(envId, searchOptions)
});
const matched = projectsResult.data.find((p) => p.name === composeProjectName);
if (matched) {
- return await queryClient.fetchQuery({
+ return await queryClient.query({
queryKey: queryKeys.projects.detail(envId, matched.id),
queryFn: () => projectService.getProjectForEnvironment(envId, matched.id)
});
diff --git a/frontend/src/routes/(app)/containers/[containerId]/edit/+page.ts b/frontend/src/routes/(app)/containers/[containerId]/edit/+page.ts
index 8a24d5df1..93c796caf 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/edit/+page.ts
+++ b/frontend/src/routes/(app)/containers/[containerId]/edit/+page.ts
@@ -14,7 +14,7 @@ export const load: PageLoad = async ({ params, parent }) => {
redirect(302, `/containers/${containerId}`);
}
- const editConfig = await queryClient.fetchQuery({
+ const editConfig = await queryClient.query({
queryKey: queryKeys.containers.editConfig(envId, containerId),
queryFn: () => containerService.getContainerEditConfig(containerId, envId)
});
diff --git a/frontend/src/routes/(app)/containers/components/ContainerLogsPanel.svelte b/frontend/src/routes/(app)/containers/components/ContainerLogsPanel.svelte
index 34fda16fe..28842565f 100644
--- a/frontend/src/routes/(app)/containers/components/ContainerLogsPanel.svelte
+++ b/frontend/src/routes/(app)/containers/components/ContainerLogsPanel.svelte
@@ -4,6 +4,7 @@
import * as Card from '#lib/components/ui/card/index.js';
import LogViewer from '#lib/components/logs/log-viewer.svelte';
import LogControls from '#lib/components/logs/log-controls.svelte';
+ import { UseLogPreferences } from '#lib/hooks/use-log-preferences.svelte.js';
import LogPanelTitle from '#lib/components/logs/log-panel-title.svelte';
import type { ContainerStats, ContainerStatsHistorySample } from '#lib/types/docker.js';
import { m } from '#lib/paraglide/messages.js';
@@ -13,7 +14,6 @@
import { CpuIcon, FileTextIcon, MemoryStickIcon } from '#lib/icons/index.js';
import ContainerLogStatMonitor from './ContainerLogStatMonitor.svelte';
- const HISTORY_LIMIT = 30;
type StatHistoryPoint = { percent: number; tooltip: string };
let {
@@ -38,15 +38,11 @@
let isStreaming = $state(false);
let viewer = $state<ReturnType<typeof LogViewer>>();
- let autoStartLogs = $state(false);
+ const preferences = new UseLogPreferences();
let logSearchTerm = $state('');
let hasAutoStarted = $state(false);
- let showParsedJson = $state(false);
- let cpuHistory = $state<StatHistoryPoint[]>([]);
- let memoryHistory = $state<StatHistoryPoint[]>([]);
- let cpuHistoryAccumulator: StatHistoryPoint[] = [];
- let memoryHistoryAccumulator: StatHistoryPoint[] = [];
- let lastStatsRead: string | null = null;
+ const cpuHistory = $derived((stats?.statsHistory ?? []).map(toCPUHistoryPoint));
+ const memoryHistory = $derived((stats?.statsHistory ?? []).map(toMemoryHistoryPoint));
const cpuUsagePercent = $derived(calculateCPUPercent(stats));
const memoryUsageBytes = $derived(calculateMemoryUsage(stats));
@@ -70,22 +66,6 @@
return bytes.format(memoryLimitBytes, { unitSeparator: ' ' }) ?? '';
});
- function resetHistory() {
- cpuHistoryAccumulator = [];
- memoryHistoryAccumulator = [];
- cpuHistory = [];
- memoryHistory = [];
- lastStatsRead = null;
- }
-
- function appendHistorySample(history: StatHistoryPoint[], value: StatHistoryPoint): StatHistoryPoint[] {
- const next = [...history, value];
- if (next.length > HISTORY_LIMIT) {
- next.shift();
- }
- return next;
- }
-
function percentFromTenths(tenths: number | undefined): number {
if (typeof tenths !== 'number' || Number.isNaN(tenths)) {
return 0;
@@ -121,14 +101,6 @@
};
}
- function applyBackendHistory(samples: ContainerStatsHistorySample[] | undefined) {
- const history = samples ?? [];
- cpuHistoryAccumulator = history.map(toCPUHistoryPoint);
- memoryHistoryAccumulator = history.map(toMemoryHistoryPoint);
- cpuHistory = cpuHistoryAccumulator;
- memoryHistory = memoryHistoryAccumulator;
- }
-
function handleStart() {
startLogViewerStream(viewer);
}
@@ -153,42 +125,11 @@
}
$effect(() => {
- if (containerId) {
- hasAutoStarted = false;
- resetHistory();
- }
- });
-
- $effect(() => {
- if (autoStartLogs && !hasAutoStarted && !isStreaming && containerId) {
+ if (preferences.autoStartLogs && !hasAutoStarted && !isStreaming && containerId && viewer) {
hasAutoStarted = true;
handleStart();
}
});
-
- $effect(() => {
- if (!isRunning) {
- return;
- }
-
- if (stats?.statsHistory?.length) {
- applyBackendHistory(stats.statsHistory);
- lastStatsRead = stats.read;
- return;
- }
-
- if (!stats?.read || stats.read === lastStatsRead) {
- return;
- }
-
- lastStatsRead = stats.read;
- if (stats.currentHistorySample) {
- cpuHistoryAccumulator = appendHistorySample(cpuHistoryAccumulator, toCPUHistoryPoint(stats.currentHistorySample));
- memoryHistoryAccumulator = appendHistorySample(memoryHistoryAccumulator, toMemoryHistoryPoint(stats.currentHistorySample));
- cpuHistory = cpuHistoryAccumulator;
- memoryHistory = memoryHistoryAccumulator;
- }
- });
</script>
<Card.Root class="flex h-full min-h-0 flex-col">
@@ -200,8 +141,7 @@
<LogControls
bind:searchTerm={logSearchTerm}
bind:autoScroll
- bind:autoStartLogs
- bind:showParsedJson
+ {preferences}
mobileLayout="full"
showDesktop={false}
{isStreaming}
@@ -216,8 +156,7 @@
<LogControls
bind:searchTerm={logSearchTerm}
bind:autoScroll
- bind:autoStartLogs
- bind:showParsedJson
+ {preferences}
mobileLayout="none"
{isStreaming}
disabled={!containerId}
@@ -261,7 +200,8 @@
bind:autoScroll
type="container"
{containerId}
- bind:showParsedJson
+ bind:showParsedJson={preferences.showParsedJson}
+ tailLines={preferences.tailLines}
maxLines={500}
showTimestamps={true}
groupAdjacentLines={true}
diff --git a/frontend/src/routes/(app)/containers/components/ContainerShell.svelte b/frontend/src/routes/(app)/containers/components/ContainerShell.svelte
index ef09ad409..b0cfb827c 100644
--- a/frontend/src/routes/(app)/containers/components/ContainerShell.svelte
+++ b/frontend/src/routes/(app)/containers/components/ContainerShell.svelte
@@ -1,4 +1,5 @@
<script lang="ts">
+ import { page } from '$app/state';
import * as Card from '#lib/components/ui/card/index.js';
import Terminal from '#lib/components/terminal/terminal.svelte';
import TerminalControls from '#lib/components/terminal/terminal-controls.svelte';
@@ -14,48 +15,15 @@
} = $props();
let isConnected = $state(false);
- let websocketUrl = $state('');
- let selectedShell = $state($settingsStore.defaultShell || '/bin/sh');
+ let selectedShell = $derived($settingsStore.defaultShell || '/bin/sh');
let reconnectKey = $state(0);
- let lastContainerId = $state<string | undefined>(undefined);
- let lastShellForUrl = $state<string | undefined>(undefined);
- let lastDefaultShell = $state<string | undefined>(undefined);
-
- $effect(() => {
- const defaultShell = $settingsStore.defaultShell;
- if (defaultShell !== lastDefaultShell) {
- lastDefaultShell = defaultShell;
- const fallbackShell = defaultShell || '/bin/sh';
- if (selectedShell !== fallbackShell) {
- selectedShell = fallbackShell;
- }
- } else if (!selectedShell) {
- selectedShell = defaultShell || '/bin/sh';
- }
-
- const currentContainer = containerId;
- if (!containerId || !selectedShell) {
- return;
- }
-
- if (lastContainerId === currentContainer && lastShellForUrl === selectedShell) {
- return;
- }
-
- lastContainerId = currentContainer;
- lastShellForUrl = selectedShell;
- updateWebSocketUrl(selectedShell);
+ const websocketUrl = $derived.by(() => {
+ if (!containerId || !selectedShell) return '';
+ let protocol = 'ws:';
+ if (page.url.protocol === 'https:') protocol = 'wss:';
+ return `${protocol}//${page.url.host}/api/environments/${environmentStore.selected?.id ?? '0'}/ws/containers/${containerId}/terminal?shell=${encodeURIComponent(selectedShell)}`;
});
- function updateWebSocketUrl(shell: string) {
- (async () => {
- const envId = await environmentStore.getCurrentEnvironmentId();
- const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
- const host = window.location.host;
- websocketUrl = `${protocol}//${host}/api/environments/${envId}/ws/containers/${containerId}/terminal?shell=${encodeURIComponent(shell)}`;
- })();
- }
-
function handleShellChange(shell: string) {
selectedShell = shell;
}
@@ -98,16 +66,18 @@
</Card.Header>
<Card.Content class="overflow-hidden p-2">
<div class="h-full overflow-hidden rounded-lg border">
- {#if websocketUrl}
- {#key reconnectKey}
- <Terminal
- {websocketUrl}
- height="calc(100vh - 320px)"
- onConnected={handleConnected}
- onDisconnected={handleDisconnected}
- />
- {/key}
- {/if}
+ {#await environmentStore.ready then}
+ {#if websocketUrl}
+ {#key reconnectKey}
+ <Terminal
+ {websocketUrl}
+ height="calc(100vh - 320px)"
+ onConnected={handleConnected}
+ onDisconnected={handleDisconnected}
+ />
+ {/key}
+ {/if}
+ {/await}
</div>
</Card.Content>
</Card.Root>
diff --git a/frontend/src/routes/(app)/containers/components/container-detail-stats-sync.svelte b/frontend/src/routes/(app)/containers/components/container-detail-stats-sync.svelte
index f907f8455..851941154 100644
--- a/frontend/src/routes/(app)/containers/components/container-detail-stats-sync.svelte
+++ b/frontend/src/routes/(app)/containers/components/container-detail-stats-sync.svelte
@@ -3,7 +3,7 @@
import { createContainerStatsWebSocket, type ReconnectingWebSocket } from '#lib/utils/ws.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
- import type { ContainerStats as ContainerStatsType } from '#lib/types/docker.js';
+ import type { ContainerStats as ContainerStatsType, ContainerStatsHistorySample } from '#lib/types/docker.js';
import { refreshAll } from '$app/navigation';
import { onDestroy } from 'svelte';
@@ -19,11 +19,14 @@
hasInitialStatsLoaded?: boolean;
} = $props();
- void stats;
- void hasInitialStatsLoaded;
+ stats = null;
+ hasInitialStatsLoaded = false;
let statsWebSocket: ReconnectingWebSocket<ContainerStatsType> | null = null;
let isConnecting = false;
+ let generation = 0;
+ let history: ContainerStatsHistorySample[] = [];
+ let lastStatsRead: string | null = null;
async function startStatsStream() {
if (!enabled || isConnecting || statsWebSocket || !containerId) {
@@ -32,20 +35,30 @@
hasInitialStatsLoaded = false;
isConnecting = true;
+ const requestGeneration = generation;
+ const requestedContainerId = containerId;
const operationResult = await tryCatch(
(async () => {
const envId = await environmentStore.getCurrentEnvironmentId();
+ if (requestGeneration !== generation || !enabled || requestedContainerId !== containerId) return;
const ws = createContainerStatsWebSocket({
getEnvId: () => envId,
- containerId,
+ containerId: requestedContainerId,
onMessage: (statsData) => {
+ if (requestGeneration !== generation) return;
if (statsData.removed) {
void refreshAll();
return;
}
- stats = statsData;
+ if (statsData.statsHistory?.length) {
+ history = statsData.statsHistory;
+ } else if (statsData.read && statsData.read !== lastStatsRead && statsData.currentHistorySample) {
+ history = [...history, statsData.currentHistorySample].slice(-30);
+ }
+ lastStatsRead = statsData.read;
+ stats = { ...statsData, statsHistory: history };
hasInitialStatsLoaded = true;
},
onOpen: () => {
@@ -66,6 +79,7 @@
statsWebSocket = ws;
})()
);
+ if (requestGeneration !== generation) return;
if (operationResult.error !== null) {
const error = operationResult.error;
@@ -75,6 +89,7 @@
}
function closeStatsStream() {
+ generation += 1;
if (statsWebSocket) {
statsWebSocket.close();
statsWebSocket = null;
diff --git a/frontend/src/routes/(app)/containers/container-table.helpers.ts b/frontend/src/routes/(app)/containers/container-table.helpers.ts
index 0b788efdc..33c7b8b21 100644
--- a/frontend/src/routes/(app)/containers/container-table.helpers.ts
+++ b/frontend/src/routes/(app)/containers/container-table.helpers.ts
@@ -51,10 +51,6 @@ export function getProjectName(container: ContainerSummaryDto): string {
return projectLabel || 'No Project';
}
-export function groupContainerByProject(container: ContainerSummaryDto): string {
- return getProjectName(container);
-}
-
export function getContainerStatusLabel(state: string): string {
switch (state) {
case 'created':
diff --git a/frontend/src/routes/(app)/containers/container-table.svelte b/frontend/src/routes/(app)/containers/container-table.svelte
index 36a544329..88e6975af 100644
--- a/frontend/src/routes/(app)/containers/container-table.svelte
+++ b/frontend/src/routes/(app)/containers/container-table.svelte
@@ -129,6 +129,7 @@
if (value === currentSetting && value === currentRequest) return;
customSettings = { ...customSettings, [settingsKey]: value };
+ tablePreferences?.persistCustomSettings(customSettings);
const nextOptions: SearchPaginationSortRequest = {
...requestOptions,
[requestKey]: value,
@@ -162,6 +163,7 @@
const isAnyLoading = $derived(hasAnyLoadingState(actionStatus, isBulkLoading));
let mobileFieldVisibility = $state<Record<string, boolean>>({});
+ let tablePreferences = $state<{ persistCustomSettings(settings: Record<string, unknown>): void }>();
let customSettings = $state<Record<string, unknown>>({});
let showInternal = $derived.by(() => {
return (customSettings['showInternalContainers'] as boolean) ?? false;
@@ -255,6 +257,7 @@
function setGroupByProject(value: boolean) {
customSettings = { ...customSettings, groupByProject: value };
+ tablePreferences?.persistCustomSettings(customSettings);
groupByProject = value;
const nextOptions: SearchPaginationSortRequest = {
...requestOptions,
@@ -814,6 +817,7 @@
{/snippet}
<ArcaneTable
+ bind:this={tablePreferences}
persistKey="arcane-container-table"
items={containers}
bind:requestOptions
@@ -856,6 +860,7 @@
checked={hideExposedPorts}
onCheckedChange={(v) => {
customSettings = { ...customSettings, hideExposedPorts: !!v };
+ tablePreferences?.persistCustomSettings(customSettings);
}}
>
{m.containers_hide_unexposed_ports()}
diff --git a/frontend/src/routes/(app)/customize/git-repositories/+page.svelte b/frontend/src/routes/(app)/customize/git-repositories/+page.svelte
index bd0c87552..16a306ede 100644
--- a/frontend/src/routes/(app)/customize/git-repositories/+page.svelte
+++ b/frontend/src/routes/(app)/customize/git-repositories/+page.svelte
@@ -15,6 +15,7 @@
let repositories = $derived(data.repositories);
let selectedIds = $state<string[]>([]);
let isRepositoryDialogOpen = $state(false);
+ let repositorySession = $state(0);
let clearToken = $state(false);
let clearSshKey = $state(false);
let repositoryToEdit = $state<GitRepository | null>(null);
@@ -43,6 +44,7 @@
repositoryToEdit = null;
clearToken = false;
clearSshKey = false;
+ repositorySession += 1;
isRepositoryDialogOpen = true;
}
@@ -50,6 +52,7 @@
repositoryToEdit = repository;
clearToken = false;
clearSshKey = false;
+ repositorySession += 1;
isRepositoryDialogOpen = true;
}
@@ -119,13 +122,17 @@
{/snippet}
{#snippet additionalContent()}
- <GitRepositoryFormSheet
- bind:clearToken
- bind:clearSshKey
- bind:open={isRepositoryDialogOpen}
- bind:repositoryToEdit
- onSubmit={handleRepositoryDialogSubmit}
- isLoading={isLoading.create || isLoading.edit}
- />
+ {#if repositorySession > 0}
+ {#key repositorySession}
+ <GitRepositoryFormSheet
+ bind:clearToken
+ bind:clearSshKey
+ bind:open={isRepositoryDialogOpen}
+ bind:repositoryToEdit
+ onSubmit={handleRepositoryDialogSubmit}
+ isLoading={isLoading.create || isLoading.edit}
+ />
+ {/key}
+ {/if}
{/snippet}
</ResourcePageLayout>
diff --git a/frontend/src/routes/(app)/customize/git-repositories/+page.ts b/frontend/src/routes/(app)/customize/git-repositories/+page.ts
index e240c7a8f..0bbd7a3f9 100644
--- a/frontend/src/routes/(app)/customize/git-repositories/+page.ts
+++ b/frontend/src/routes/(app)/customize/git-repositories/+page.ts
@@ -18,7 +18,7 @@ export const load: PageLoad = async ({ parent }) => {
}
} satisfies SearchPaginationSortRequest);
- const repositories = await queryClient.fetchQuery({
+ const repositories = await queryClient.query({
queryKey: queryKeys.gitRepositories.list(repositoryRequestOptions),
queryFn: () => gitRepositoryService.getRepositories(repositoryRequestOptions)
});
diff --git a/frontend/src/routes/(app)/customize/registries/+page.ts b/frontend/src/routes/(app)/customize/registries/+page.ts
index 28811a253..43ed2e9b0 100644
--- a/frontend/src/routes/(app)/customize/registries/+page.ts
+++ b/frontend/src/routes/(app)/customize/registries/+page.ts
@@ -19,12 +19,12 @@ export const load: PageLoad = async ({ parent }) => {
}
} satisfies SearchPaginationSortRequest);
- const registries = await queryClient.fetchQuery({
+ const registries = await queryClient.query({
queryKey: queryKeys.containerRegistries.list(registryRequestOptions),
queryFn: () => containerRegistryService.getRegistries(registryRequestOptions)
});
const pullUsage = await tryCatch(
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.containerRegistries.pullUsage(),
queryFn: () => containerRegistryService.getPullUsage()
})
diff --git a/frontend/src/routes/(app)/customize/templates/+page.ts b/frontend/src/routes/(app)/customize/templates/+page.ts
index 822028b38..32a4f77c8 100644
--- a/frontend/src/routes/(app)/customize/templates/+page.ts
+++ b/frontend/src/routes/(app)/customize/templates/+page.ts
@@ -22,7 +22,7 @@ export const load: PageLoad = async ({
const [templates, registries] = await Promise.all([
tryCatch(
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.templates.list(templateRequestOptions),
queryFn: () => templateService.getTemplates(templateRequestOptions)
})
@@ -35,7 +35,7 @@ export const load: PageLoad = async ({
: result.data
),
tryCatch(
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.templates.registries(),
queryFn: () => templateService.getRegistries()
})
diff --git a/frontend/src/routes/(app)/customize/templates/[id]/+page.ts b/frontend/src/routes/(app)/customize/templates/[id]/+page.ts
index cf8c163d3..d2448b708 100644
--- a/frontend/src/routes/(app)/customize/templates/[id]/+page.ts
+++ b/frontend/src/routes/(app)/customize/templates/[id]/+page.ts
@@ -20,16 +20,16 @@ export const load: PageLoad = async ({
const operationResult = await tryCatch(
(async () => {
const [templateData, allTemplates, globalVariables] = await Promise.all([
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.templates.content(params.id),
queryFn: () => templateService.getTemplateContent(params.id)
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.templates.allTemplates(),
queryFn: () => templateService.getAllTemplates()
}),
tryCatch(
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.variables.list(),
queryFn: () => variableService.list()
})
diff --git a/frontend/src/routes/(app)/customize/templates/create/+page.ts b/frontend/src/routes/(app)/customize/templates/create/+page.ts
index 46814b99a..230d87311 100644
--- a/frontend/src/routes/(app)/customize/templates/create/+page.ts
+++ b/frontend/src/routes/(app)/customize/templates/create/+page.ts
@@ -8,7 +8,7 @@ export const load: PageLoad = async ({ parent }): Promise<{ globalVariables: Glo
const { queryClient } = await parent();
const globalVariables = await tryCatch(
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.variables.list(),
queryFn: () => variableService.list()
})
diff --git a/frontend/src/routes/(app)/customize/variables/+page.svelte b/frontend/src/routes/(app)/customize/variables/+page.svelte
index b9ea94f7a..29963880b 100644
--- a/frontend/src/routes/(app)/customize/variables/+page.svelte
+++ b/frontend/src/routes/(app)/customize/variables/+page.svelte
@@ -25,6 +25,7 @@
let variables = $derived(data.variables);
let isSheetOpen = $state(false);
+ let variableSession = $state(0);
let variableToEdit = $state<GlobalVariable | null>(null);
let isSubmitting = $state(false);
@@ -43,11 +44,13 @@
function openCreateSheet() {
variableToEdit = null;
+ variableSession += 1;
isSheetOpen = true;
}
function openEditSheet(variable: GlobalVariable) {
variableToEdit = variable;
+ variableSession += 1;
isSheetOpen = true;
}
@@ -77,7 +80,6 @@
reportSyncResults(response?.syncResults);
isSheetOpen = false;
- variableToEdit = null;
})()
);
if (operationResult.error !== null) {
@@ -147,13 +149,17 @@
{/snippet}
{#snippet additionalContent()}
- <VariableFormSheet
- bind:open={isSheetOpen}
- bind:variableToEdit
- environments={data.environments}
- existingVariables={variables}
- isLoading={isSubmitting}
- onSubmit={handleSheetSubmit}
- />
+ {#if variableSession > 0}
+ {#key variableSession}
+ <VariableFormSheet
+ bind:open={isSheetOpen}
+ bind:variableToEdit
+ environments={data.environments}
+ existingVariables={variables}
+ isLoading={isSubmitting}
+ onSubmit={handleSheetSubmit}
+ />
+ {/key}
+ {/if}
{/snippet}
</ResourcePageLayout>
diff --git a/frontend/src/routes/(app)/customize/variables/+page.ts b/frontend/src/routes/(app)/customize/variables/+page.ts
index 338884480..f5ca2479a 100644
--- a/frontend/src/routes/(app)/customize/variables/+page.ts
+++ b/frontend/src/routes/(app)/customize/variables/+page.ts
@@ -13,11 +13,11 @@ export const load: PageLoad = async ({ parent }) => {
const { queryClient } = await parent();
const [variables, environmentsPage] = await Promise.all([
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.variables.list(),
queryFn: () => variableService.list()
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.environments.list(environmentListOptions),
queryFn: () => environmentManagementService.getEnvironments(environmentListOptions)
})
diff --git a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
index 77f24c0b4..7567faea1 100644
--- a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
+++ b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
@@ -11,6 +11,7 @@
import { m } from '#lib/paraglide/messages.js';
import { settingsService } from '#lib/services/settings-service.js';
import { systemService } from '#lib/services/system-service.js';
+ import type { Activity } from '#lib/types/activity.type.js';
import { activityStore } from '#lib/stores/activity.store.svelte.js';
import { dashboardStore } from '#lib/stores/dashboard.store.svelte.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
@@ -334,23 +335,17 @@
});
});
- // A prune runs as a background activity; once the streamed activity reaches a
- // terminal state, refresh so the dashboard reflects the post-prune resource counts.
- // A plain (non-reactive) guard dedupes so the refresh fires once per activity
- // without writing $state inside the effect.
let refreshedPruneActivityId: string | null = null;
- $effect(() => {
+ function refreshCompletedPrune(activities: readonly Activity[] = activityStore.activities) {
const id = pendingPruneActivityId;
- if (!id || id === refreshedPruneActivityId) {
- return;
- }
+ if (!id || id === refreshedPruneActivityId) return;
+ const status = activities.find((activity) => activity.id === id)?.status;
+ if (status !== 'success' && status !== 'failed' && status !== 'cancelled') return;
+ refreshedPruneActivityId = id;
+ void refreshOverview();
+ }
- const status = activityStore.getActivity(id)?.status;
- if (status === 'success' || status === 'failed' || status === 'cancelled') {
- refreshedPruneActivityId = id;
- void refreshOverview();
- }
- });
+ onMount(() => activityStore.subscribeActivities(refreshCompletedPrune));
onMount(() => {
void dashboardStore.start({ debugAllGood });
@@ -600,6 +595,7 @@
// an immediate refresh when no activity id is returned.
if (activityId) {
pendingPruneActivityId = activityId;
+ refreshCompletedPrune();
} else {
await refreshOverview();
}
diff --git a/frontend/src/routes/(app)/environments/+page.svelte b/frontend/src/routes/(app)/environments/+page.svelte
index 9b2825034..8f19889b0 100644
--- a/frontend/src/routes/(app)/environments/+page.svelte
+++ b/frontend/src/routes/(app)/environments/+page.svelte
@@ -2,6 +2,7 @@
import { toast } from 'svelte-sonner';
import { dev } from '$app/env';
import { page } from '$app/state';
+ import { afterNavigate } from '$app/navigation';
import NewEnvironmentSheet from '#lib/components/sheets/new-environment-sheet.svelte';
import EnvironmentTable from './environment-table.svelte';
import { m } from '#lib/paraglide/messages.js';
@@ -20,6 +21,7 @@
let selectedIds = $state<string[]>([]);
let requestOptions = $derived(data.environmentRequestOptions);
let showEnvironmentSheet = $state(false);
+ let environmentSession = $state(0);
let showUpdateAllDialog = $state(false);
let isLoading = $state({ refresh: false, creating: false, deleting: false });
@@ -68,7 +70,7 @@
// fleet, so its progress and result states can be reviewed under `just dev` without
// updating anything. `dev` is compiled out of production builds.
const updateAllDemo = $derived(dev && page.url.searchParams.get('updateAllDemo') === '1');
- $effect(() => {
+ afterNavigate(() => {
if (updateAllDemo) showUpdateAllDialog = true;
});
@@ -98,7 +100,10 @@
id: 'create',
action: 'create' as const,
label: m.common_add_button({ resource: m.resource_environment_cap() }),
- onclick: () => (showEnvironmentSheet = true)
+ onclick: () => {
+ environmentSession += 1;
+ showEnvironmentSheet = true;
+ }
}
]
: []),
@@ -148,7 +153,11 @@
{/snippet}
{#snippet additionalContent()}
- <NewEnvironmentSheet bind:open={showEnvironmentSheet} {onEnvironmentCreated} />
+ {#if environmentSession > 0}
+ {#key environmentSession}
+ <NewEnvironmentSheet bind:open={showEnvironmentSheet} {onEnvironmentCreated} />
+ {/key}
+ {/if}
<UpdateAllDialog bind:open={showUpdateAllDialog} debugDemo={updateAllDemo} onFinished={refresh} />
{/snippet}
</ResourcePageLayout>
diff --git a/frontend/src/routes/(app)/environments/+page.ts b/frontend/src/routes/(app)/environments/+page.ts
index c9b4763b6..f0f2fc83e 100644
--- a/frontend/src/routes/(app)/environments/+page.ts
+++ b/frontend/src/routes/(app)/environments/+page.ts
@@ -23,7 +23,7 @@ export const load: PageLoad = async ({ parent }) => {
let environments;
const operationResult = await tryCatch(
(async () =>
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.environments.list(environmentRequestOptions),
queryFn: () => environmentManagementService.getEnvironments(environmentRequestOptions)
}))()
diff --git a/frontend/src/routes/(app)/environments/[id]/+page.svelte b/frontend/src/routes/(app)/environments/[id]/+page.svelte
index 68321d283..6937ba487 100644
--- a/frontend/src/routes/(app)/environments/[id]/+page.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/+page.svelte
@@ -18,7 +18,8 @@
import { environmentManagementService } from '#lib/services/env-mgmt-service.js';
import { settingsService } from '#lib/services/settings-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
- import type { AppVersionInformation } from '#lib/types/settings.js';
+ import { createQuery } from '@tanstack/svelte-query';
+ import { queryKeys } from '#lib/query/query-keys.js';
import type { Environment, EnvironmentStatus } from '#lib/types/environment.js';
import { hasPermission } from '#lib/utils/auth.js';
import { isEnvironmentOnline, resolveEnvironmentStatus } from '#lib/utils/docker.js';
@@ -69,18 +70,28 @@
let showRegenerateDialog = $state(false);
let regeneratedApiKey = $state<string | null>(null);
let easyJoinDialogOpen = $state(false);
+ let easyJoinSession = $state(0);
let nameInputRef = $state<HTMLInputElement | null>(null);
let isEditingApiUrl = $state(false);
const easyJoinCandidates = useEasyJoinCandidates();
- // Version state
- let remoteVersion = $state<AppVersionInformation | null>(null);
- let isLoadingVersion = $state(false);
-
// Only non-edge custom URL tests should temporarily override the displayed status.
let statusOverride = $state<EnvironmentStatus | null>(null);
let currentStatus = $derived(resolveEnvironmentStatus(runtimeEnvironment, statusOverride));
let isCurrentlyOnline = $derived(isEnvironmentOnline(runtimeEnvironment, statusOverride));
+
+ const versionQuery = createQuery(() => {
+ const environmentId = environment.id;
+ return {
+ queryKey: queryKeys.system.versionInfo(environmentId),
+ queryFn: () => environmentManagementService.getVersion(environmentId),
+ enabled: environmentId !== '0' && isCurrentlyOnline,
+ retry: false
+ };
+ });
+ const remoteVersion = $derived(versionQuery.data ?? null);
+ const isLoadingVersion = $derived(versionQuery.isFetching);
+
let isCurrentlyStandby = $derived(currentStatus === 'standby');
let showSettingsTabs = $derived(runtimeEnvironment.enabled && isCurrentlyOnline && settings !== null);
let hasMTLSAssets = $derived(Boolean(runtimeEnvironment.edgeMTLSCertificate));
@@ -149,7 +160,10 @@
id: 'easy-join',
action: 'create',
label: m.swarm_easy_join_action(),
- onclick: () => (easyJoinDialogOpen = true),
+ onclick: () => {
+ easyJoinSession += 1;
+ easyJoinDialogOpen = true;
+ },
icon: ConnectionIcon
});
}
@@ -421,13 +435,6 @@
}
}
- // Fetch version when environment is online
- $effect(() => {
- if (environment.id !== '0' && isCurrentlyOnline && !remoteVersion && !isLoadingVersion) {
- fetchVersion();
- }
- });
-
onMount(() => {
if (environment.isEdge) {
void refreshRuntimeEnvironment();
@@ -457,24 +464,6 @@
}
}
- async function fetchVersion() {
- try {
- const operationResult = await tryCatch(
- (async () => {
- isLoadingVersion = true;
- remoteVersion = await environmentManagementService.getVersion(environment.id);
- })()
- );
- if (operationResult.error !== null) {
- const err = operationResult.error;
-
- console.error('Failed to fetch environment version:', err);
- }
- } finally {
- isLoadingVersion = false;
- }
- }
-
async function refreshEnvironment() {
if (isRefreshing) return;
try {
@@ -482,7 +471,7 @@
(async () => {
isRefreshing = true;
statusOverride = null;
- remoteVersion = null;
+ if (environment.id !== '0' && isCurrentlyOnline) await versionQuery.refetch();
await refreshAll();
})()
);
@@ -847,12 +836,14 @@
</AlertDialog.Root>
</div>
-<EasyJoinDialog
- bind:open={easyJoinDialogOpen}
- managerEnvironmentId={easyJoinCandidates.managerEnvironmentId ?? undefined}
- targetEnvironmentId={runtimeEnvironment.id}
- onComplete={easyJoinCandidates.refresh}
-/>
+{#key `${easyJoinSession}:${easyJoinCandidates.managerEnvironmentId}`}
+ <EasyJoinDialog
+ bind:open={easyJoinDialogOpen}
+ managerEnvironmentId={easyJoinCandidates.managerEnvironmentId ?? undefined}
+ targetEnvironmentId={runtimeEnvironment.id}
+ onComplete={easyJoinCandidates.refresh}
+ />
+{/key}
<MobileFloatingFormActions
hasChanges={settingsForm.hasChanges}
diff --git a/frontend/src/routes/(app)/environments/[id]/+page.ts b/frontend/src/routes/(app)/environments/[id]/+page.ts
index cf36e1c41..cbdaf83fe 100644
--- a/frontend/src/routes/(app)/environments/[id]/+page.ts
+++ b/frontend/src/routes/(app)/environments/[id]/+page.ts
@@ -9,7 +9,7 @@ export const load: PageLoad = async ({ params, parent }) => {
const operationResult = await tryCatch(
(async () => {
- const environment = await queryClient.fetchQuery({
+ const environment = await queryClient.query({
queryKey: queryKeys.environments.detail(params.id),
queryFn: () => environmentManagementService.get(params.id)
});
@@ -17,7 +17,7 @@ export const load: PageLoad = async ({ params, parent }) => {
let settings = null;
const operationResult = await tryCatch(
(async () =>
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.environments.settings(params.id),
queryFn: () => settingsService.getSettingsForEnvironment(params.id)
}))()
diff --git a/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte b/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte
index 1a19b7abe..b67a89a6b 100644
--- a/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/gitops/+page.svelte
@@ -14,7 +14,7 @@
import { m } from '#lib/paraglide/messages.js';
import { gitOpsSyncService } from '#lib/services/gitops-sync-service.js';
import { page } from '$app/state';
- import { goto } from '$app/navigation';
+ import { afterNavigate, goto } from '$app/navigation';
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';
import SyncTable from './sync-table.svelte';
import { RefreshIcon, ClockIcon, SuccessIcon, GitBranchIcon, UploadIcon } from '#lib/icons/index.js';
@@ -24,6 +24,7 @@
let syncs = $derived(data.syncs);
let selectedIds = $state<string[]>([]);
let isSyncDialogOpen = $state(false);
+ let syncSession = $state(0);
let isImportDialogOpen = $state(false);
let syncToEdit = $state<GitOpsSync | null>(null);
let syncRequestOptions = $derived(data.syncRequestOptions);
@@ -43,25 +44,15 @@
};
const syncCounts = $derived(syncs?.counts ?? syncCountsFallback);
- let targetTypeFromQuery = $derived(
- page.url.searchParams.get('action') === 'create' ? (page.url.searchParams.get('targetType') ?? undefined) : undefined
- );
-
let dialogTargetType = $state<string | undefined>(undefined);
- $effect(() => {
- if (page.url.searchParams.get('action') === 'create') {
- const typeQuery = targetTypeFromQuery;
- // Use a small timeout to ensure the page is fully mounted and ready
- setTimeout(() => {
- openCreateSyncDialog(typeQuery);
- // Remove the query param so it doesn't reopen on refresh
- const newUrl = new URL(page.url.href);
- newUrl.searchParams.delete('action');
- newUrl.searchParams.delete('targetType');
- goto(newUrl.toString(), { replaceState: true, reset: false });
- }, 100);
- }
+ afterNavigate(() => {
+ if (page.url.searchParams.get('action') !== 'create') return;
+ openCreateSyncDialog(page.url.searchParams.get('targetType') ?? undefined);
+ const newUrl = new URL(page.url.href);
+ newUrl.searchParams.delete('action');
+ newUrl.searchParams.delete('targetType');
+ void goto(newUrl.toString(), { replaceState: true, reset: false });
});
async function refreshSyncs() {
@@ -80,12 +71,14 @@
function openCreateSyncDialog(targetType?: string | Event) {
syncToEdit = null;
dialogTargetType = typeof targetType === 'string' ? targetType : undefined;
+ syncSession += 1;
isSyncDialogOpen = true;
}
function openEditSyncDialog(sync: GitOpsSync) {
syncToEdit = sync;
dialogTargetType = undefined;
+ syncSession += 1;
isSyncDialogOpen = true;
}
@@ -232,14 +225,18 @@
{/snippet}
{#snippet additionalContent()}
- <GitOpsSyncFormSheet
- bind:open={isSyncDialogOpen}
- bind:syncToEdit
- {environmentId}
- targetType={dialogTargetType}
- onSubmit={handleSyncDialogSubmit}
- isLoading={isLoading.create || isLoading.edit}
- />
+ {#if syncSession > 0}
+ {#key syncSession}
+ <GitOpsSyncFormSheet
+ bind:open={isSyncDialogOpen}
+ bind:syncToEdit
+ {environmentId}
+ targetType={dialogTargetType}
+ onSubmit={handleSyncDialogSubmit}
+ isLoading={isLoading.create || isLoading.edit}
+ />
+ {/key}
+ {/if}
<GitOpsImportDialog bind:open={isImportDialogOpen} onSubmit={handleImportSubmit} isLoading={isLoading.import} />
{/snippet}
</ResourcePageLayout>
diff --git a/frontend/src/routes/(app)/environments/[id]/gitops/+page.ts b/frontend/src/routes/(app)/environments/[id]/gitops/+page.ts
index 3193a3d93..b54180edd 100644
--- a/frontend/src/routes/(app)/environments/[id]/gitops/+page.ts
+++ b/frontend/src/routes/(app)/environments/[id]/gitops/+page.ts
@@ -22,11 +22,11 @@ export const load: PageLoad = async ({ params, parent }) => {
} satisfies SearchPaginationSortRequest);
const [environment, syncs] = await Promise.all([
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.environments.detail(environmentId),
queryFn: () => environmentManagementService.get(environmentId)
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.gitOpsSyncs.list(environmentId, syncRequestOptions),
queryFn: () => gitOpsSyncService.getSyncs(environmentId, syncRequestOptions)
})
diff --git a/frontend/src/routes/(app)/environments/environment-table.svelte b/frontend/src/routes/(app)/environments/environment-table.svelte
index 95b1db147..69a6e2345 100644
--- a/frontend/src/routes/(app)/environments/environment-table.svelte
+++ b/frontend/src/routes/(app)/environments/environment-table.svelte
@@ -58,6 +58,7 @@
let selectedEnvironmentForUpgrade = $state<Environment | null>(null);
let selectedVersionInfoForUpgrade = $state<AppVersionInformation | null>(null);
let easyJoinDialogOpen = $state(false);
+ let easyJoinSession = $state(0);
let easyJoinTarget = $state<Environment | null>(null);
const easyJoinCandidates = useEasyJoinCandidates();
@@ -89,6 +90,7 @@
}
function openEasyJoin(item: Environment) {
+ easyJoinSession += 1;
easyJoinTarget = item;
easyJoinDialogOpen = true;
}
@@ -170,14 +172,6 @@
}
}
- $effect(() => {
- if (!showUpgradeDialog) {
- upgradingEnvironmentId = null;
- selectedEnvironmentForUpgrade = null;
- selectedVersionInfoForUpgrade = null;
- }
- });
-
async function handleToggleEnabled(environment: Environment) {
const newEnabled = !environment.enabled;
isLoading.toggling = true;
@@ -450,7 +444,13 @@
/>
<UpdateCenterDialog
- bind:open={showUpgradeDialog}
+ bind:open={
+ () => showUpgradeDialog,
+ (open) => {
+ showUpgradeDialog = open;
+ if (!open) upgradingEnvironmentId = null;
+ }
+ }
onConfirm={handleConfirmUpgrade}
versionInformation={selectedVersionInfoForUpgrade ?? undefined}
canInstall={canInstallUpdates}
@@ -459,9 +459,11 @@
bind:upgrading={isLoading.upgrading}
/>
-<EasyJoinDialog
- bind:open={easyJoinDialogOpen}
- managerEnvironmentId={easyJoinCandidates.managerEnvironmentId ?? undefined}
- targetEnvironmentId={easyJoinTarget?.id}
- onComplete={easyJoinCandidates.refresh}
-/>
+{#key `${easyJoinSession}:${easyJoinCandidates.managerEnvironmentId}`}
+ <EasyJoinDialog
+ bind:open={easyJoinDialogOpen}
+ managerEnvironmentId={easyJoinCandidates.managerEnvironmentId ?? undefined}
+ targetEnvironmentId={easyJoinTarget?.id}
+ onComplete={easyJoinCandidates.refresh}
+ />
+{/key}
diff --git a/frontend/src/routes/(app)/events/+page.svelte b/frontend/src/routes/(app)/events/+page.svelte
index a7b158953..b17b7a684 100644
--- a/frontend/src/routes/(app)/events/+page.svelte
+++ b/frontend/src/routes/(app)/events/+page.svelte
@@ -14,7 +14,6 @@
let { data } = $props();
- let events = $derived(data.events);
let selectedIds = $state<string[]>([]);
let requestOptions = $derived(data.eventRequestOptions);
let isDeleting = $state(false);
@@ -32,12 +31,7 @@
initialData: data.eventStats
}));
- $effect(() => {
- if (eventsQuery.data) {
- events = eventsQuery.data;
- }
- });
-
+ const events = $derived(eventsQuery.data ?? data.events);
const counts = $derived(statsQuery.data);
const isRefreshing = $derived(eventsQuery.isFetching && !eventsQuery.isPending);
@@ -203,7 +197,7 @@
<ResourcePageLayout title={m.events_title()} subtitle={m.events_subtitle()} {actionButtons} {statCards}>
{#snippet mainContent()}
<EventTable
- bind:events
+ {events}
bind:selectedIds
bind:requestOptions
onRefreshData={async (options) => {
diff --git a/frontend/src/routes/(app)/events/+page.ts b/frontend/src/routes/(app)/events/+page.ts
index bb301f972..f329dcbf6 100644
--- a/frontend/src/routes/(app)/events/+page.ts
+++ b/frontend/src/routes/(app)/events/+page.ts
@@ -25,11 +25,11 @@ export const load: PageLoad = async ({ parent }) => {
const operationResult = await tryCatch(
(async () =>
Promise.all([
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.events.listGlobal(eventRequestOptions),
queryFn: () => eventService.getEvents(eventRequestOptions)
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.events.statsGlobal(),
queryFn: () => eventService.getEventStats()
})
diff --git a/frontend/src/routes/(app)/images/+page.svelte b/frontend/src/routes/(app)/images/+page.svelte
index 7d2468a30..2cd315b3d 100644
--- a/frontend/src/routes/(app)/images/+page.svelte
+++ b/frontend/src/routes/(app)/images/+page.svelte
@@ -19,17 +19,16 @@
import { queryKeys } from '#lib/query/query-keys.js';
import type { ImageUsageCounts } from '#lib/types/docker.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
- import { untrack } from 'svelte';
+ import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';
import { CloseIcon, VolumesIcon, LocalFolderComputerIcon, SearchIcon } from '#lib/icons/index.js';
- import { createMutation, createQuery, useQueryClient, keepPreviousData } from '@tanstack/svelte-query';
+ import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import PruneModeCard from '#lib/components/prune/prune-mode-card.svelte';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
let { data } = $props();
const queryClient = useQueryClient();
- let images = $derived(data.images);
let requestOptions = $derived(data.imageRequestOptions);
let selectedIds = $state<string[]>([]);
let isPullDialogOpen = $state(false);
@@ -42,8 +41,6 @@
let imagePruneMode = $state<'dangling' | 'all' | 'olderThan'>('dangling');
let imagePruneUntil = $state('');
const envId = $derived(environmentStore.selected?.id || '0');
- let previousEnvId = untrack(() => envId);
- let latestImageRequestId = 0;
const imageUsageFallback: ImageUsageCounts = {
imagesInuse: 0,
imagesUnused: 0,
@@ -57,10 +54,14 @@
const imagesQuery = createQuery(() => {
const queryEnvId = envId;
+ const options = requestOptions;
return {
- queryKey: queryKeys.images.list(queryEnvId, requestOptions),
- queryFn: () => imageService.getImagesForEnvironment(queryEnvId, requestOptions),
- placeholderData: keepPreviousData,
+ queryKey: queryKeys.images.list(queryEnvId, options),
+ queryFn: () => imageService.getImagesForEnvironment(queryEnvId, options),
+ placeholderData: (previous, query) => {
+ if (query?.queryKey[1] === queryEnvId) return previous;
+ return undefined;
+ },
initialData: data.envId === queryEnvId ? data.images : undefined,
select: (value) => ({ envId: queryEnvId, value })
};
@@ -75,6 +76,8 @@
select: (value) => ({ envId: queryEnvId, value })
};
});
+ const images = $derived(imagesQuery.data?.value ?? data.images);
+
const resourcesReady = $derived(imagesQuery.data?.envId === envId);
const pruneImagesMutation = createMutation(() => ({
@@ -141,15 +144,7 @@
}
}));
- $effect(() => {
- if (imagesQuery.data?.envId === envId) {
- images = imagesQuery.data.value;
- }
- });
-
- $effect(() => {
- if (envId === previousEnvId) return;
- previousEnvId = envId;
+ useEnvironmentRefresh(() => {
selectedIds = [];
isPullDialogOpen = false;
isRegistrySearchDialogOpen = false;
@@ -202,26 +197,17 @@
];
async function loadImages(options: SearchPaginationSortRequest = requestOptions, requestedEnvId: string = envId) {
- const requestId = ++latestImageRequestId;
requestOptions = options;
- const [nextImages] = await Promise.all([
- queryClient.fetchQuery({
+ await Promise.all([
+ queryClient.query({
queryKey: queryKeys.images.list(requestedEnvId, options),
queryFn: () => imageService.getImagesForEnvironment(requestedEnvId, options)
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.images.usageCounts(requestedEnvId),
queryFn: () => imageService.getImageUsageCountsForEnvironment(requestedEnvId)
})
]);
-
- if (requestedEnvId !== envId) {
- selectedIds = [];
- return;
- }
- if (requestId !== latestImageRequestId) return;
-
- images = nextImages;
}
async function refresh() {
@@ -320,18 +306,20 @@
<ResourcePageLayout title={m.images()} subtitle={m.images_subtitle()} {actionButtons} {statCards}>
{#snippet mainContent()}
{#if resourcesReady}
- <ImageTable
- bind:images
- bind:selectedIds
- bind:requestOptions
- loading={imagesQuery.isLoading}
- onRefreshData={async (options) => {
- await loadImages(options, envId);
- }}
- onImageUpdated={async () => {
- await imagesQuery.refetch();
- }}
- />
+ {#key envId}
+ <ImageTable
+ bind:images={() => images, (value) => queryClient.setQueryData(queryKeys.images.list(envId, requestOptions), value)}
+ bind:selectedIds
+ bind:requestOptions
+ loading={imagesQuery.isLoading}
+ onRefreshData={async (options) => {
+ await loadImages(options, envId);
+ }}
+ onImageUpdated={async () => {
+ await imagesQuery.refetch();
+ }}
+ />
+ {/key}
{/if}
{/snippet}
diff --git a/frontend/src/routes/(app)/images/+page.ts b/frontend/src/routes/(app)/images/+page.ts
index 61a466854..ec8006c73 100644
--- a/frontend/src/routes/(app)/images/+page.ts
+++ b/frontend/src/routes/(app)/images/+page.ts
@@ -21,15 +21,15 @@ export const load: PageLoad = async ({ parent }) => {
const operationResult = await tryCatch(
(async () =>
Promise.all([
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.images.list(envId, imageRequestOptions),
queryFn: () => imageService.getImagesForEnvironment(envId, imageRequestOptions)
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.settings.byEnvironment(envId),
queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.images.usageCounts(envId),
queryFn: () => imageService.getImageUsageCountsForEnvironment(envId)
})
diff --git a/frontend/src/routes/(app)/images/[imageId]/+page.svelte b/frontend/src/routes/(app)/images/[imageId]/+page.svelte
index bc602d478..ecafb3690 100644
--- a/frontend/src/routes/(app)/images/[imageId]/+page.svelte
+++ b/frontend/src/routes/(app)/images/[imageId]/+page.svelte
@@ -7,7 +7,10 @@
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import { toast } from 'svelte-sonner';
- import { onDestroy } from 'svelte';
+ import { onMount, onDestroy, tick } from 'svelte';
+ import { createQuery, useQueryClient } from '@tanstack/svelte-query';
+ import { queryKeys } from '#lib/query/query-keys.js';
+ import userStore from '#lib/stores/user-store.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { m } from '#lib/paraglide/messages.js';
import { imageService } from '#lib/services/image-service.js';
@@ -75,43 +78,47 @@
});
let tagDialogOpen = $state(false);
- let vulnerabilityScan = $state<VulnerabilityScanResult | null>(null);
- let hasLoadedVulnerabilities = $state(false);
- let stopScanPolling: (() => void) | null = $state(null);
- let lastScanRequestedAt = $state<string | null>(null);
-
- // Load vulnerability scan data when image changes
- $effect(() => {
- if (image?.id && !hasLoadedVulnerabilities) {
- loadVulnerabilityScan();
- }
+ const queryClient = useQueryClient();
+ const scanQueryKey = $derived(queryKeys.vulnerabilities.scanResult(currentEnvId, image?.id ?? ''));
+ const scanQuery = createQuery(() => {
+ const environmentId = currentEnvId;
+ const imageId = image?.id;
+ $userStore;
+ return {
+ queryKey: queryKeys.vulnerabilities.scanResult(environmentId, imageId ?? ''),
+ queryFn: async () => {
+ await environmentStore.ready;
+ return vulnerabilityService.getScanResult(imageId!);
+ },
+ enabled: !!imageId && hasPermission('vulnerabilities:read', environmentId),
+ retry: false
+ };
});
-
- async function loadVulnerabilityScan() {
- if (!image?.id) return;
- const operationResult = await tryCatch(
- (async () => {
- const result = await vulnerabilityService.getScanResult(image.id);
- vulnerabilityScan = result;
- lastScanRequestedAt = result.scanTime || lastScanRequestedAt;
- })()
- );
- if (operationResult.error !== null) {
- // No scan data found, that's okay
- vulnerabilityScan = null;
- }
- hasLoadedVulnerabilities = true;
- }
+ const vulnerabilityScan = $derived(scanQuery.data ?? null);
+ const scanInProgress = $derived(isVulnerabilityScanInProgress(vulnerabilityScan?.status));
+ let stopScanPolling: (() => void) | null = null;
+ let pollingScope = '';
+ let scanRequest = $state<{ scope: string; time: string } | null>(null);
+ const lastScanRequestedAt = $derived.by(() => {
+ if (scanRequest?.scope === `${currentEnvId}:${image?.id}`) return scanRequest.time;
+ return vulnerabilityScan?.scanTime ?? null;
+ });
+ let destroyed = false;
async function handleScanImage() {
if (!image?.id || isLoading.scanning) return;
+ const environmentId = currentEnvId;
+ const requestedImageId = image.id;
+ const requestedKey = scanQueryKey;
isLoading.scanning = true;
try {
const operationResult = await tryCatch(
(async () => {
- const result = await vulnerabilityService.scanImage(image.id);
- vulnerabilityScan = result;
- lastScanRequestedAt = result.scanTime || nowInstantString();
+ await queryClient.cancelQueries({ queryKey: requestedKey });
+ const result = await vulnerabilityService.scanImage(requestedImageId);
+ queryClient.setQueryData(requestedKey, result);
+ if (destroyed || environmentId !== currentEnvId || requestedImageId !== image.id) return;
+ scanRequest = { scope: `${environmentId}:${requestedImageId}`, time: result.scanTime || nowInstantString() };
if (isVulnerabilityScanInProgress(result.status)) {
toastVulnerabilityScanStatus(result, { includeStarted: true });
beginScanPolling(true);
@@ -158,9 +165,14 @@
function beginScanPolling(showToast: boolean) {
if (!image?.id || stopScanPolling) return;
- const cancel = startVulnerabilityScanPolling(image.id, (id) => vulnerabilityService.getScanSummary(id), {
+ const environmentId = currentEnvId;
+ const requestedImageId = image.id;
+ const requestedKey = scanQueryKey;
+ pollingScope = `${environmentId}:${requestedImageId}`;
+ const cancel = startVulnerabilityScanPolling(requestedImageId, (id) => vulnerabilityService.getScanSummary(id), {
onUpdate: (summary) => {
- vulnerabilityScan = {
+ if (destroyed || environmentId !== currentEnvId || requestedImageId !== image.id) return;
+ queryClient.setQueryData(requestedKey, {
...(vulnerabilityScan ?? {}),
imageId: summary.imageId,
scanTime: summary.scanTime,
@@ -168,9 +180,10 @@
scanPhase: summary.scanPhase,
summary: summary.summary,
error: summary.error
- } as VulnerabilityScanResult;
+ } as VulnerabilityScanResult);
},
onComplete: async (summary) => {
+ if (destroyed || environmentId !== currentEnvId || requestedImageId !== image.id) return;
let resolvedSummary = summary;
const operationResult = await tryCatch(
(async () =>
@@ -184,8 +197,9 @@
resolvedSummary = operationResult.data;
}
+ if (destroyed || environmentId !== currentEnvId || requestedImageId !== image.id) return;
if (isVulnerabilityScanInProgress(resolvedSummary.status)) {
- vulnerabilityScan = {
+ queryClient.setQueryData(requestedKey, {
...(vulnerabilityScan ?? {}),
imageId: resolvedSummary.imageId,
scanTime: resolvedSummary.scanTime,
@@ -193,7 +207,7 @@
scanPhase: resolvedSummary.scanPhase,
summary: resolvedSummary.summary,
error: resolvedSummary.error
- } as VulnerabilityScanResult;
+ } as VulnerabilityScanResult);
stopPolling();
beginScanPolling(false);
return;
@@ -201,11 +215,12 @@
stopPolling();
const operationResult2 = await tryCatch((async () => vulnerabilityService.getScanResult(resolvedSummary.imageId))());
+ if (destroyed || environmentId !== currentEnvId || requestedImageId !== image.id) return;
if (operationResult2.error !== null) {
const error = operationResult2.error;
console.error('Failed to load scan result:', error);
- vulnerabilityScan = {
+ queryClient.setQueryData(requestedKey, {
...(vulnerabilityScan ?? {}),
imageId: resolvedSummary.imageId,
scanTime: resolvedSummary.scanTime,
@@ -213,9 +228,9 @@
scanPhase: resolvedSummary.scanPhase,
summary: resolvedSummary.summary,
error: resolvedSummary.error
- } as VulnerabilityScanResult;
+ } as VulnerabilityScanResult);
} else {
- vulnerabilityScan = operationResult2.data;
+ queryClient.setQueryData(requestedKey, operationResult2.data);
}
if (showToast) {
toastVulnerabilityScanStatus(resolvedSummary);
@@ -227,19 +242,25 @@
stopScanPolling = cancel;
}
- $effect(() => {
- if (!lastScanRequestedAt && vulnerabilityScan?.scanTime) {
- lastScanRequestedAt = vulnerabilityScan.scanTime;
- }
- const scanning = isVulnerabilityScanInProgress(vulnerabilityScan?.status);
- if (scanning) {
- beginScanPolling(false);
- } else {
- stopPolling();
+ onMount(() => {
+ const cache = queryClient.getQueryCache();
+ function updateScanPolling() {
+ if (destroyed) return;
+ const scope = `${currentEnvId}:${image?.id}`;
+ if (scope !== pollingScope) stopPolling();
+ if (scanInProgress) beginScanPolling(false);
+ else stopPolling();
}
+ updateScanPolling();
+ return cache.subscribe((event) => {
+ if (event.type !== 'updated' && event.type !== 'observerResultsUpdated') return;
+ if (event.query !== cache.find({ queryKey: scanQueryKey, exact: true })) return;
+ void tick().then(updateScanPolling);
+ });
});
onDestroy(() => {
+ destroyed = true;
stopPolling();
});
diff --git a/frontend/src/routes/(app)/images/[imageId]/+page.ts b/frontend/src/routes/(app)/images/[imageId]/+page.ts
index 2f12fe422..2bf687e29 100644
--- a/frontend/src/routes/(app)/images/[imageId]/+page.ts
+++ b/frontend/src/routes/(app)/images/[imageId]/+page.ts
@@ -20,7 +20,7 @@ export const load: PageLoad = async ({ params, parent }): Promise<ImageDetailDat
const operationResult = await tryCatch(
(async () => {
- const image = await queryClient.fetchQuery({
+ const image = await queryClient.query({
queryKey: queryKeys.images.detail(envId, imageId),
queryFn: () => imageService.getImageForEnvironment(envId, imageId)
});
diff --git a/frontend/src/routes/(app)/images/[imageId]/image-history-panel.svelte b/frontend/src/routes/(app)/images/[imageId]/image-history-panel.svelte
index 919b243cc..f4e81d823 100644
--- a/frontend/src/routes/(app)/images/[imageId]/image-history-panel.svelte
+++ b/frontend/src/routes/(app)/images/[imageId]/image-history-panel.svelte
@@ -1,43 +1,39 @@
<script lang="ts">
- import { tryCatch } from '#lib/utils/try-catch.js';
+ import { createQuery } from '@tanstack/svelte-query';
+ import { queryKeys } from '#lib/query/query-keys.js';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+ import userStore from '#lib/stores/user-store.js';
+ import { hasPermission } from '#lib/utils/auth.js';
import * as Card from '#lib/components/ui/card/index.js';
import { Badge } from '#lib/components/ui/badge/index.js';
import { Spinner } from '#lib/components/ui/spinner/index.js';
import { bytes, formatDateTimeShort } from '#lib/utils/formatting.js';
import { imageService } from '#lib/services/image-service.js';
- import type { ImageHistoryItemDto } from '#lib/types/docker.js';
import { m } from '#lib/paraglide/messages.js';
import { Temporal } from 'temporal-polyfill';
let { imageId }: { imageId: string } = $props();
- let history = $state<ImageHistoryItemDto[]>([]);
- let loading = $state(true);
- let error = $state<string | null>(null);
-
- $effect(() => {
- if (!imageId) return;
- void loadHistory(imageId);
+ const historyQuery = createQuery(() => {
+ const environmentId = environmentStore.selected?.id;
+ const requestedImageId = imageId;
+ $userStore;
+ return {
+ queryKey: queryKeys.images.history(environmentId ?? '', requestedImageId),
+ queryFn: async () => {
+ await environmentStore.ready;
+ return imageService.getImageHistory(requestedImageId);
+ },
+ enabled: !!environmentId && !!requestedImageId && hasPermission('images:read', environmentId)
+ };
+ });
+ const history = $derived(historyQuery.data ?? []);
+ const loading = $derived(historyQuery.isPending);
+ const error = $derived.by(() => {
+ if (historyQuery.error) return m.images_history_load_failed();
+ return null;
});
-
- async function loadHistory(id: string) {
- loading = true;
- error = null;
- try {
- const operationResult = await tryCatch((async () => imageService.getImageHistory(id))());
- if (operationResult.error !== null) {
- const err = operationResult.error;
-
- console.error('Failed to load image history:', err);
- error = m.images_history_load_failed();
- } else {
- history = operationResult.data;
- }
- } finally {
- loading = false;
- }
- }
function formatCreated(created: number) {
if (!created) return m.common_na();
diff --git a/frontend/src/routes/(app)/images/builds/+page.svelte b/frontend/src/routes/(app)/images/builds/+page.svelte
index fd406d8b4..6c11683ac 100644
--- a/frontend/src/routes/(app)/images/builds/+page.svelte
+++ b/frontend/src/routes/(app)/images/builds/+page.svelte
@@ -191,16 +191,6 @@
: ''
);
- // Clear the repository name when registry changes to prevent cross-registry mismatches.
- let lastRegistryId = $state($inputs.registryId.value);
- $effect(() => {
- const current = $inputs.registryId.value;
- if (current !== lastRegistryId) {
- lastRegistryId = current;
- $inputs.repositoryName.value = '';
- }
- });
-
type ImageBuildRequest = { envId: string; provider: 'local' | 'depot' } & Pick<
ImageBuildRecord,
| 'contextDir'
@@ -358,12 +348,6 @@
return () => mq.removeEventListener('change', update);
});
- $effect(() => {
- if (!depotAvailable && $inputs.provider.value === 'depot') {
- $inputs.provider.value = 'local';
- }
- });
-
function resetState() {
isBuilding = false;
buildStatusText = '';
@@ -633,7 +617,7 @@
{#snippet configPanel()}
<BuildConfigPanel
{inputs}
- provider={$inputs.provider.value}
+ provider={resolvedProvider}
bind:showAdvanced
{isPushMode}
{registryOptions}
@@ -678,7 +662,7 @@
</Tabs.List>
<div class="flex items-center gap-3 pr-2">
- <BuildControls {inputs} {providerOptions} {isBuilding} onBuild={handleSubmit} />
+ <BuildControls {inputs} provider={resolvedProvider} {providerOptions} {isBuilding} onBuild={handleSubmit} />
<div class="hidden h-4 w-px bg-border xl:block"></div>
<div class="flex items-center gap-2">
<div class="relative flex items-center">
@@ -787,7 +771,7 @@
{#snippet headerActions()}
{#if mainTab === 'build'}
- <BuildControls {inputs} {providerOptions} {isBuilding} onBuild={handleSubmit} />
+ <BuildControls {inputs} provider={resolvedProvider} {providerOptions} {isBuilding} onBuild={handleSubmit} />
{/if}
{/snippet}
@@ -807,7 +791,7 @@
</div>
{/snippet}
{#snippet headerActions()}
- <BuildControls {inputs} {providerOptions} {isBuilding} onBuild={handleSubmit} />
+ <BuildControls {inputs} provider={resolvedProvider} {providerOptions} {isBuilding} onBuild={handleSubmit} />
{/snippet}
{#snippet tabContent(buildTabValue)}
{#if buildTabValue === 'workspace'}
diff --git a/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte b/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte
index cb479021b..ac62c0d00 100644
--- a/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte
+++ b/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte
@@ -64,7 +64,7 @@
let editorOpen = $state(false);
let editorFile = $state<FileEntry | null>(null);
- let editorContent = $state('');
+ let editorDraft = $state<{ envId: string; path: string; content: string } | null>(null);
let editorSaving = $state(false);
const editorContentQuery = createQuery(() => ({
@@ -75,18 +75,10 @@
enabled: !!editorFile && editorOpen
}));
- let lastSeededPath: string | null = null;
-
- $effect(() => {
- if (!editorFile || !editorOpen) {
- lastSeededPath = null;
- return;
- }
- const data = editorContentQuery.data;
- if (data && editorFile.path !== lastSeededPath) {
- lastSeededPath = editorFile.path;
- editorContent = b64DecodeUnicode(data.content);
- }
+ const editorContent = $derived.by(() => {
+ if (editorDraft?.envId === envId && editorDraft.path === editorFile?.path) return editorDraft.content;
+ if (!editorContentQuery.data) return '';
+ return b64DecodeUnicode(editorContentQuery.data.content);
});
const editorLoading = $derived(editorContentQuery.isPending || editorContentQuery.isFetching);
@@ -167,7 +159,7 @@
if (file.isDirectory) return;
editorFile = file;
editorOpen = true;
- editorContent = '';
+ editorDraft = null;
}
async function handleSaveFile() {
@@ -312,7 +304,16 @@
{:else}
<div class="space-y-2">
<Label>{m.build_file_contents()}</Label>
- <Textarea rows={18} bind:value={editorContent} class="font-mono text-xs" />
+ <Textarea
+ rows={18}
+ bind:value={
+ () => editorContent,
+ (content) => {
+ editorDraft = { envId, path: editorFile?.path ?? '', content };
+ }
+ }
+ class="font-mono text-xs"
+ />
<p class="text-xs text-muted-foreground">{m.build_saving_overwrite()}</p>
</div>
{/if}
diff --git a/frontend/src/routes/(app)/images/builds/components/build-config-panel.svelte b/frontend/src/routes/(app)/images/builds/components/build-config-panel.svelte
index 97b1a44c9..3ea4fec8e 100644
--- a/frontend/src/routes/(app)/images/builds/components/build-config-panel.svelte
+++ b/frontend/src/routes/(app)/images/builds/components/build-config-panel.svelte
@@ -44,7 +44,14 @@
options={registryOptions}
description={!registryLoadFailed && registryOptions.length === 0 ? m.registries_none_enabled() : undefined}
error={registryLoadFailed ? m.registries_no_list_permission() : null}
- bind:value={$inputs.registryId.value}
+ bind:value={
+ () => $inputs.registryId.value,
+ (value) => {
+ if (value === $inputs.registryId.value) return;
+ $inputs.registryId.value = value;
+ $inputs.repositoryName.value = '';
+ }
+ }
/>
<SelectWithLabel
diff --git a/frontend/src/routes/(app)/images/builds/components/build-controls.svelte b/frontend/src/routes/(app)/images/builds/components/build-controls.svelte
index e94a06a1e..31aaef90b 100644
--- a/frontend/src/routes/(app)/images/builds/components/build-controls.svelte
+++ b/frontend/src/routes/(app)/images/builds/components/build-controls.svelte
@@ -9,11 +9,13 @@
let {
inputs,
+ provider,
providerOptions,
isBuilding = false,
onBuild
}: {
inputs: BuildFormInputsStore;
+ provider: 'local' | 'depot';
providerOptions: BuildProviderOption[];
isBuilding?: boolean;
onBuild?: () => void;
@@ -28,7 +30,13 @@
triggerSize="sm"
triggerClass="w-[160px]"
options={providerOptions}
- bind:value={$inputs.provider.value}
+ bind:value={
+ () => provider,
+ (value) => {
+ if (value === 'depot') $inputs.provider.value = 'depot';
+ else $inputs.provider.value = 'local';
+ }
+ }
/>
<div class="hidden h-6 w-px bg-border lg:block"></div>
@@ -43,7 +51,7 @@
id="build-load"
checked={$inputs.load.value}
onCheckedChange={(v) => ($inputs.load.value = v === true)}
- disabled={$inputs.provider.value === 'depot'}
+ disabled={provider === 'depot'}
/>
<Label for="build-load" class="text-sm">{m.load()}</Label>
</div>
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.svelte
index f3e3631f2..239c1695b 100644
--- 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.svelte
@@ -1,5 +1,6 @@
<script lang="ts">
- import { createQuery } from '@tanstack/svelte-query';
+ import { onMount } from 'svelte';
+ import { createQuery, useQueryClient } 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/index.js';
@@ -43,6 +44,7 @@
let { environmentId, onApplyBuild }: Props = $props();
+ const queryClient = useQueryClient();
const EMPTY_BUILD_HISTORY: Paginated<ImageBuildRecord> = {
data: [],
pagination: { totalPages: 1, totalItems: 0, currentPage: 1, itemsPerPage: 20 }
@@ -58,45 +60,61 @@
let selectedId = $state<string | null>(null);
let detailsOpen = $state(false);
- const historyQuery = createQuery(() => ({
- queryKey: queryKeys.images.buildsList(environmentId, requestOptions),
- queryFn: () => imageService.getImageBuilds(requestOptions)
- }));
+ const historyQuery = createQuery(() => {
+ const requestedEnvironmentId = environmentId;
+ const options = requestOptions;
+ return {
+ queryKey: queryKeys.images.buildsList(requestedEnvironmentId, options),
+ queryFn: () => imageService.getImageBuilds(options)
+ };
+ });
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(() => {
+ const requestedEnvironmentId = environmentId;
+ const buildId = selectedId;
+ return {
+ queryKey: queryKeys.images.buildRecord(requestedEnvironmentId, buildId ?? 'none'),
+ queryFn: () => imageService.getImageBuild(buildId!),
+ enabled: !!buildId && detailsOpen
+ };
});
- 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;
+ onMount(() => {
+ const cache = queryClient.getQueryCache();
+ let historyLastError = '';
+ let detailLastError = '';
+ function reportError(error: unknown, detail: boolean) {
+ if (!error || (detail && !detailsOpen)) return;
+ let message: string = m.common_error();
+ if (error instanceof Error) message = error.message;
+ if (detail) {
+ if (message === detailLastError) return;
+ detailLastError = message;
+ } else {
+ if (message === historyLastError) return;
+ historyLastError = message;
+ }
toast.error(message);
}
+ reportError(historyQuery.error, false);
+ reportError(detailQuery.error, true);
+ return cache.subscribe((event) => {
+ if (event.type !== 'updated' && event.type !== 'observerResultsUpdated') return;
+ if (event.query === cache.find({ queryKey: queryKeys.images.buildsList(environmentId, requestOptions), exact: true })) {
+ reportError(event.query.state.error, false);
+ } else if (
+ selectedId &&
+ event.query === cache.find({ queryKey: queryKeys.images.buildRecord(environmentId, selectedId), exact: true })
+ ) {
+ reportError(event.query.state.error, true);
+ }
+ });
});
const detailItems = $derived(selectedBuild ? getBuildDetailItems(selectedBuild) : []);
diff --git a/frontend/src/routes/(app)/images/image-table.svelte b/frontend/src/routes/(app)/images/image-table.svelte
index 2f828c157..c01bcfbc3 100644
--- a/frontend/src/routes/(app)/images/image-table.svelte
+++ b/frontend/src/routes/(app)/images/image-table.svelte
@@ -4,7 +4,9 @@
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
import { Spinner } from '#lib/components/ui/spinner/index.js';
import { goto } from '$app/navigation';
- import { onDestroy } from 'svelte';
+ import { onMount, onDestroy, tick } from 'svelte';
+ import { useQueryClient } from '@tanstack/svelte-query';
+ import { queryKeys } from '#lib/query/query-keys.js';
import { toast } from 'svelte-sonner';
import { bytes, formatDateTimeShort, nowInstantString } from '#lib/utils/formatting.js';
import { inUseBadge } from '#lib/utils/mobile-card-badges.js';
@@ -64,6 +66,7 @@
loading?: boolean;
} = $props();
+ const queryClient = useQueryClient();
let isLoading = $state({
removing: false,
checking: false
@@ -189,7 +192,9 @@
}
async function handleInlineVulnerabilityScan(imageId: string) {
+ const requestedEnvId = currentEnvId;
const result = await tryCatch(vulnerabilityService.scanImage(imageId));
+ if (destroyed || requestedEnvId !== currentEnvId) return;
await handleApiResultWithCallbacks({
result,
message: m.vuln_scan_failed(),
@@ -240,22 +245,26 @@
}
async function handleUpdateInfoChanged(imageId: string, newUpdateInfo: ImageUpdateInfoDto) {
- const imageIndex = images.data.findIndex((img) => img.id === imageId);
- const image = imageIndex !== -1 ? images.data[imageIndex] : undefined;
- if (image) {
- image.updateInfo = newUpdateInfo;
- images = { ...images, data: [...images.data] };
- }
+ if (destroyed) return;
+ images = {
+ ...images,
+ data: images.data.map((image) => {
+ if (image.id === imageId) return { ...image, updateInfo: newUpdateInfo };
+ return image;
+ })
+ };
await onImageUpdated?.();
}
async function handleVulnerabilityScanChanged(imageId: string, newScanSummary: VulnerabilityScanSummary) {
- const imageIndex = images.data.findIndex((img) => img.id === imageId);
- const image = imageIndex !== -1 ? images.data[imageIndex] : undefined;
- if (image) {
- image.vulnerabilityScan = newScanSummary;
- images = { ...images, data: [...images.data] };
- }
+ if (destroyed) return;
+ images = {
+ ...images,
+ data: images.data.map((image) => {
+ if (image.id === imageId) return { ...image, vulnerabilityScan: newScanSummary };
+ return image;
+ })
+ };
if (newScanSummary.status === 'completed' || newScanSummary.status === 'failed') {
if (scanRequestedAtByImage[imageId]) {
delete scanRequestedAtByImage[imageId];
@@ -283,6 +292,7 @@
}
async function pollBatchScanSummaries() {
+ const requestedEnvId = currentEnvId;
const imageIds = getScanningImageIds();
if (imageIds.length === 0) {
stopBatchScanPolling();
@@ -299,7 +309,7 @@
const operationResult = await tryCatch(
(async () => {
const response = await vulnerabilityService.getScanSummaries(imageIds);
- if (destroyed) return;
+ if (destroyed || requestedEnvId !== currentEnvId) return;
const summaries = response?.summaries ?? {};
if (Object.keys(summaries).length > 0 && images.data?.length) {
@@ -357,12 +367,19 @@
void pollBatchScanSummaries();
}
- $effect(() => {
- if (getScanningImageIds().length > 0) {
- startBatchScanPolling();
- } else {
- stopBatchScanPolling();
+ onMount(() => {
+ const cache = queryClient.getQueryCache();
+ function updateScanPolling() {
+ if (destroyed) return;
+ if (getScanningImageIds().length > 0) startBatchScanPolling();
+ else stopBatchScanPolling();
}
+ updateScanPolling();
+ return cache.subscribe((event) => {
+ if (event.type !== 'updated' && event.type !== 'observerResultsUpdated') return;
+ if (event.query !== cache.find({ queryKey: queryKeys.images.list(currentEnvId, requestOptions), exact: true })) return;
+ void tick().then(updateScanPolling);
+ });
});
onDestroy(() => {
@@ -608,7 +625,6 @@
<VulnerabilityScanItem
scanSummary={item.vulnerabilityScan}
imageId={item.id}
- pollingEnabled={false}
onScanned={(newSummary) => handleVulnerabilityScanChanged(item.id, newSummary)}
/>
</div>
diff --git a/frontend/src/routes/(app)/networks/+page.svelte b/frontend/src/routes/(app)/networks/+page.svelte
index 2eab1dcb0..ecef6bb4e 100644
--- a/frontend/src/routes/(app)/networks/+page.svelte
+++ b/frontend/src/routes/(app)/networks/+page.svelte
@@ -11,32 +11,33 @@
import { ResourceListPageState } from '#lib/utils/resource-list-page.svelte.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { untrack } from 'svelte';
+ import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';
- import { createMutation, createQuery, useQueryClient, keepPreviousData } from '@tanstack/svelte-query';
+ import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
let { data } = $props();
const queryClient = useQueryClient();
- const pageState = new ResourceListPageState(
- untrack(() => data.networks),
- untrack(() => data.networkRequestOptions)
- );
- let previousEnvId = untrack(() => pageState.envId);
+ const pageState = new ResourceListPageState(untrack(() => data.networkRequestOptions));
const countsFallback: NetworkUsageCounts = { inuse: 0, unused: 0, total: 0 };
const networksQuery = createQuery(() => {
const queryEnvId = pageState.envId;
+ const options = pageState.requestOptions;
return {
- queryKey: queryKeys.networks.list(queryEnvId, pageState.requestOptions),
- queryFn: () => networkService.getNetworksForEnvironment(queryEnvId, pageState.requestOptions),
- placeholderData: keepPreviousData,
+ queryKey: queryKeys.networks.list(queryEnvId, options),
+ queryFn: () => networkService.getNetworksForEnvironment(queryEnvId, options),
+ placeholderData: (previous, query) => {
+ if (query?.queryKey[1] === queryEnvId) return previous;
+ return undefined;
+ },
initialData: data.envId === queryEnvId ? data.networks : undefined,
select: (value) => ({ envId: queryEnvId, value })
};
});
- let displayedEnvId = $state<string | null>(untrack(() => (data.envId === pageState.envId ? data.envId : null)));
- const resourcesReady = $derived(displayedEnvId === pageState.envId);
+ const resourcesReady = $derived(networksQuery.data?.envId === pageState.envId);
+ const networks = $derived(networksQuery.data?.value ?? data.networks);
const createNetworkMutation = createMutation(() => ({
mutationKey: ['networks', 'create', pageState.envId],
@@ -57,17 +58,7 @@
}
}));
- $effect(() => {
- if (networksQuery.data?.envId === pageState.envId) {
- pageState.items = networksQuery.data.value;
- displayedEnvId = pageState.envId;
- }
- });
-
- $effect(() => {
- if (pageState.envId === previousEnvId) return;
- previousEnvId = pageState.envId;
- displayedEnvId = null;
+ useEnvironmentRefresh(() => {
pageState.selectedIds = [];
pageState.isCreateDialogOpen = false;
});
@@ -78,15 +69,10 @@
async function loadNetworks(options = pageState.requestOptions, requestedEnvId = pageState.envId) {
pageState.requestOptions = options;
- const next = await queryClient.fetchQuery({
+ await queryClient.query({
queryKey: queryKeys.networks.list(requestedEnvId, options),
queryFn: () => networkService.getNetworksForEnvironment(requestedEnvId, options)
});
- if (requestedEnvId !== pageState.envId) {
- return;
- }
- pageState.items = next;
- displayedEnvId = requestedEnvId;
}
async function refresh() {
@@ -94,7 +80,10 @@
}
const isRefreshing = $derived(networksQuery.isFetching && !networksQuery.isPending);
- const networkUsageCounts = $derived(resourcesReady ? (pageState.items.counts ?? countsFallback) : countsFallback);
+ const networkUsageCounts = $derived.by(() => {
+ if (resourcesReady) return networks.counts ?? countsFallback;
+ return countsFallback;
+ });
const actionButtons: ActionButton[] = $derived([
{
@@ -142,12 +131,17 @@
<ResourcePageLayout title={m.resource_networks_cap()} subtitle={m.networks_subtitle()} {actionButtons} {statCards}>
{#snippet mainContent()}
{#if resourcesReady}
- <NetworkTable
- bind:networks={pageState.items}
- bind:selectedIds={pageState.selectedIds}
- bind:requestOptions={pageState.requestOptions}
- onRefreshData={loadNetworks}
- />
+ {#key pageState.envId}
+ <NetworkTable
+ bind:networks={
+ () => networks,
+ (value) => queryClient.setQueryData(queryKeys.networks.list(pageState.envId, pageState.requestOptions), value)
+ }
+ bind:selectedIds={pageState.selectedIds}
+ bind:requestOptions={pageState.requestOptions}
+ onRefreshData={loadNetworks}
+ />
+ {/key}
{/if}
{/snippet}
diff --git a/frontend/src/routes/(app)/networks/+page.ts b/frontend/src/routes/(app)/networks/+page.ts
index 15c1fa417..dd4c45c30 100644
--- a/frontend/src/routes/(app)/networks/+page.ts
+++ b/frontend/src/routes/(app)/networks/+page.ts
@@ -19,7 +19,7 @@ export const load: PageLoad = async ({ parent }) => {
let networks;
const operationResult = await tryCatch(
(async () =>
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.networks.list(envId, networkRequestOptions),
queryFn: () => networkService.getNetworksForEnvironment(envId, networkRequestOptions)
}))()
diff --git a/frontend/src/routes/(app)/networks/[networkId]/+page.ts b/frontend/src/routes/(app)/networks/[networkId]/+page.ts
index d080e1b8f..bb2f1660b 100644
--- a/frontend/src/routes/(app)/networks/[networkId]/+page.ts
+++ b/frontend/src/routes/(app)/networks/[networkId]/+page.ts
@@ -13,7 +13,7 @@ export const load: PageLoad = async ({ params, parent }) => {
const operationResult = await tryCatch(
(async () => {
- const network = await queryClient.fetchQuery({
+ const network = await queryClient.query({
queryKey: queryKeys.networks.detail(envId, networkId),
queryFn: () => networkService.getNetworkForEnvironment(envId, networkId)
});
diff --git a/frontend/src/routes/(app)/networks/ports/+page.svelte b/frontend/src/routes/(app)/networks/ports/+page.svelte
index 8ce522937..7854408bf 100644
--- a/frontend/src/routes/(app)/networks/ports/+page.svelte
+++ b/frontend/src/routes/(app)/networks/ports/+page.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import { untrack } from 'svelte';
+ import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';
import { createQuery } from '@tanstack/svelte-query';
import { ResourcePageLayout, type ActionButton } from '#lib/layouts/index.js';
import { m } from '#lib/paraglide/messages.js';
@@ -14,7 +14,6 @@
let selectedIds = $state<string[]>([]);
const envId = $derived(environmentStore.selected?.id || '0');
- let previousEnvId = untrack(() => envId);
const portsQuery = createQuery(() => {
const queryEnvId = envId;
@@ -27,9 +26,7 @@
});
const ports = $derived(portsQuery.data?.envId === envId ? portsQuery.data.value : null);
- $effect(() => {
- if (envId === previousEnvId) return;
- previousEnvId = envId;
+ useEnvironmentRefresh(() => {
selectedIds = [];
});
diff --git a/frontend/src/routes/(app)/networks/ports/+page.ts b/frontend/src/routes/(app)/networks/ports/+page.ts
index b5a81ca95..cf3f13928 100644
--- a/frontend/src/routes/(app)/networks/ports/+page.ts
+++ b/frontend/src/routes/(app)/networks/ports/+page.ts
@@ -18,7 +18,7 @@ export const load: PageLoad = async ({ parent }) => {
let ports;
const operationResult = await tryCatch(
(async () =>
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.ports.list(envId, portRequestOptions),
queryFn: () => portService.getPortsForEnvironment(envId, portRequestOptions)
}))()
diff --git a/frontend/src/routes/(app)/networks/topology/+page.ts b/frontend/src/routes/(app)/networks/topology/+page.ts
index 1c8f5971a..fe80dfead 100644
--- a/frontend/src/routes/(app)/networks/topology/+page.ts
+++ b/frontend/src/routes/(app)/networks/topology/+page.ts
@@ -12,7 +12,7 @@ export const load: PageLoad = async ({ parent }) => {
let topology;
const operationResult = await tryCatch(
(async () =>
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.networks.topology(envId),
queryFn: () => networkService.getNetworkTopology(envId)
}))()
diff --git a/frontend/src/routes/(app)/projects/+page.svelte b/frontend/src/routes/(app)/projects/+page.svelte
index 394c49558..094bbda16 100644
--- a/frontend/src/routes/(app)/projects/+page.svelte
+++ b/frontend/src/routes/(app)/projects/+page.svelte
@@ -1,4 +1,5 @@
<script lang="ts">
+ import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';
import { BoxIcon, ProjectsIcon, StartIcon, StopIcon } from '#lib/icons/index.js';
import { toast } from 'svelte-sonner';
import ProjectsTable from './projects-table.svelte';
@@ -37,7 +38,6 @@
let selectedIds = $state<string[]>([]);
let isManualRefreshing = $state(false);
const envId = $derived(environmentStore.selected?.id || '0');
- let previousEnvId = untrack(() => envId);
const showArchived = $derived(page.url.searchParams.get('archived') === 'true');
const projectRequestOptions = $derived(withArchivedFilter(baseProjectRequestOptions, showArchived));
const countsFallback: ProjectStatusCounts = {
@@ -83,9 +83,7 @@
const projectTags = $derived(projectTagsQuery.data?.envId === envId ? projectTagsQuery.data.value : []);
const resourcesReady = $derived(projects !== null);
- $effect(() => {
- if (envId === previousEnvId) return;
- previousEnvId = envId;
+ useEnvironmentRefresh(() => {
selectedIds = [];
isManualRefreshing = false;
});
diff --git a/frontend/src/routes/(app)/projects/+page.ts b/frontend/src/routes/(app)/projects/+page.ts
index 8cb4aa05c..e03bfbdaf 100644
--- a/frontend/src/routes/(app)/projects/+page.ts
+++ b/frontend/src/routes/(app)/projects/+page.ts
@@ -36,15 +36,15 @@ export const load: PageLoad = async ({ parent, url }) => {
const operationResult = await tryCatch(
(async () =>
Promise.all([
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.projects.list(envId, projectRequestOptions),
queryFn: () => projectService.getProjectsForEnvironment(envId, projectRequestOptions)
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.projects.statusCounts(envId),
queryFn: () => projectService.getProjectStatusCountsForEnvironment(envId)
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.projects.tags(envId),
queryFn: () => projectService.getProjectTagsForEnvironment(envId)
})
diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
index baa383fcb..9a78a62b7 100644
--- a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
@@ -49,7 +49,8 @@
import ProjectsLogsPanel from '../components/ProjectLogsPanel.svelte';
import ResizableSplit from '#lib/components/resizable-split.svelte';
import { Switch } from '#lib/components/ui/switch/index.js';
- import { untrack } from 'svelte';
+ import { onMount, tick, untrack } from 'svelte';
+ import { afterNavigate } from '$app/navigation';
import { projectService } from '#lib/services/project-service.js';
import { projectWorkspaceService } from '#lib/services/project-workspace-service.js';
import settingsStore from '#lib/stores/config-store.js';
@@ -645,7 +646,7 @@
}
}));
- $effect(() => {
+ function initializeProjectPreferences() {
if (!project?.id) return;
if (lastPrefsProjectId === project.id) return;
@@ -663,7 +664,8 @@
const cur = prefs.current ?? {};
const userSelectedTabForProject = userSelectedTabProjectId === project.id;
const requestedTab = new URL(window.location.href).searchParams.get('tab');
- const urlTabValue = tabItems.some((tab) => tab.value === requestedTab) ? (requestedTab as ProjectTab) : null;
+ let urlTabValue: ProjectTab | null = null;
+ if (tabItems.some((tab) => tab.value === requestedTab)) urlTabValue = requestedTab as ProjectTab;
if (!userSelectedTabForProject) {
selectedTab = urlTabValue ?? cur.tab ?? defaultComposeUIPrefs.tab;
// Logs merged into the services tab (#3367): honor legacy ?tab=logs deep
@@ -679,21 +681,27 @@
envOpen = cur.envOpen ?? defaultComposeUIPrefs.envOpen;
autoScrollStackLogs = cur.autoScroll ?? defaultComposeUIPrefs.autoScroll;
selectedFilePreference = cur.selectedFile ?? defaultComposeUIPrefs.selectedFile ?? 'compose';
- openTabsPreference = cur.openTabs && cur.openTabs.length > 0 ? cur.openTabs : [selectedFilePreference];
+ openTabsPreference = [selectedFilePreference];
+ if (cur.openTabs && cur.openTabs.length > 0) openTabsPreference = cur.openTabs;
// Auto-detect layout mode from includes and workspace entries. PersistedState
// always materializes the defaults, so only trust the stored layoutMode when
// this project actually had persisted prefs.
const hasIncludes = project?.includeFiles && project.includeFiles.length > 0;
const hasWorkspaceEntries = projectWorkspaceEntries.length > 0;
- const defaultMode = hasIncludes || hasWorkspaceEntries ? 'tree' : 'classic';
- layoutMode = hadStoredPrefs ? (cur.layoutMode ?? defaultMode) : defaultMode;
+ let defaultMode: 'tree' | 'classic' = 'classic';
+ if (hasIncludes || hasWorkspaceEntries) defaultMode = 'tree';
+ layoutMode = defaultMode;
+ if (hadStoredPrefs) layoutMode = cur.layoutMode ?? defaultMode;
// PersistedState seeds storage with the defaults on first mount; persist the
// resolved state so the auto-detected layout survives the next visit.
if (!hadStoredPrefs || userSelectedTabForProject) {
persistPrefs();
}
- });
+ loadSelectedProjectWorkspaceFiles();
+ }
+
+ afterNavigate(initializeProjectPreferences);
async function handleSaveChanges() {
if (!project || !hasChanges) return;
@@ -956,14 +964,21 @@
return existingPromise;
}
+ const requestedEnvId = envId;
+ const pendingFiles = projectWorkspaceFilePromises;
const promise = (async () => {
- const file = await projectWorkspaceService.getWorkspaceFile(currentProjectId, relativePath, envId);
- if (kind !== 'workspace') {
+ const file = await projectWorkspaceService.getWorkspaceFile(currentProjectId, relativePath, requestedEnvId);
+ if (
+ kind !== 'workspace' &&
+ currentProjectId === projectId &&
+ requestedEnvId === envId &&
+ pendingFiles === projectWorkspaceFilePromises
+ ) {
updateLoadedProjectWorkspaceSource(kind, relativePath, file.content ?? '');
}
return file;
})().finally(() => {
- delete projectWorkspaceFilePromises[requestKey];
+ delete pendingFiles[requestKey];
});
projectWorkspaceFilePromises[requestKey] = promise;
@@ -989,6 +1004,7 @@
if (layoutMode === 'tree') {
persistPrefs();
}
+ loadSelectedProjectWorkspaceFiles();
}
function closeFileTab(key: string) {
@@ -1005,6 +1021,7 @@
selectedFilePreference = remaining[Math.min(Math.max(index - 1, 0), remaining.length - 1)] ?? 'compose';
}
persistPrefs();
+ loadSelectedProjectWorkspaceFiles();
}
function treeTabLabel(key: string): string {
@@ -1060,6 +1077,9 @@
}
async function loadProjectWorkspaceFileDraft(relativePath: string) {
+ const requestedProjectId = projectId;
+ const requestedEnvId = envId;
+ const pendingFiles = projectWorkspaceFilePromises;
if (!relativePath || projectWorkspaceContents[relativePath] !== undefined || projectWorkspaceLoading[relativePath]) {
return;
}
@@ -1074,11 +1094,14 @@
const operationResult = await tryCatch(
(async () => {
const file = await getProjectWorkspaceFileResource('workspace', relativePath);
+ if (requestedProjectId !== projectId || requestedEnvId !== envId || pendingFiles !== projectWorkspaceFilePromises)
+ return;
projectWorkspaceFileMetadata = { ...projectWorkspaceFileMetadata, [relativePath]: file };
if (file.editable) updateLoadedProjectWorkspaceFile(relativePath, file.content ?? '');
})()
);
if (operationResult.error !== null) {
+ if (requestedProjectId !== projectId || requestedEnvId !== envId || pendingFiles !== projectWorkspaceFilePromises) return;
const error = operationResult.error;
projectWorkspaceLoadErrors = {
@@ -1087,26 +1110,16 @@
};
}
} finally {
- projectWorkspaceLoading = removeWorkspaceFileRecord(projectWorkspaceLoading, relativePath);
+ if (requestedProjectId === projectId && requestedEnvId === envId && pendingFiles === projectWorkspaceFilePromises) {
+ projectWorkspaceLoading = removeWorkspaceFileRecord(projectWorkspaceLoading, relativePath);
+ }
}
}
- $effect(() => {
- const relativePath = selectedProjectWorkspacePath;
- const entry = selectedProjectWorkspaceEntry;
- const hasContent = relativePath ? projectWorkspaceContents[relativePath] !== undefined : true;
- const hasMetadata = relativePath ? projectWorkspaceFileMetadata[relativePath] !== undefined : true;
- const isLoadingFile = relativePath ? projectWorkspaceLoading[relativePath] === true : false;
- const hasLoadError = relativePath ? projectWorkspaceLoadErrors[relativePath] !== undefined : false;
-
- if (!relativePath || !entry || entry.isDirectory || hasContent || hasMetadata || isLoadingFile || hasLoadError) {
- return;
- }
-
- void loadProjectWorkspaceFileDraft(relativePath);
- });
-
async function loadProjectSourceFile(kind: 'include' | 'directory', relativePath: string) {
+ const requestedProjectId = projectId;
+ const requestedEnvId = envId;
+ const pendingFiles = projectWorkspaceFilePromises;
projectWorkspaceLoading = {
...projectWorkspaceLoading,
[relativePath]: true
@@ -1120,6 +1133,7 @@
})()
);
if (operationResult.error !== null) {
+ if (requestedProjectId !== projectId || requestedEnvId !== envId || pendingFiles !== projectWorkspaceFilePromises) return;
const error = operationResult.error;
projectWorkspaceLoadErrors = {
@@ -1128,23 +1142,54 @@
};
}
} finally {
- projectWorkspaceLoading = removeWorkspaceFileRecord(projectWorkspaceLoading, relativePath);
+ if (requestedProjectId === projectId && requestedEnvId === envId && pendingFiles === projectWorkspaceFilePromises) {
+ projectWorkspaceLoading = removeWorkspaceFileRecord(projectWorkspaceLoading, relativePath);
+ }
}
}
- $effect(() => {
- const relativePath = selectedIncludeTab;
- if (!relativePath) return;
- const kind = includeFilePaths.has(relativePath) ? 'include' : 'directory';
- const loaded =
- kind === 'include'
- ? includeFilesState[relativePath] !== undefined
- : loadedDirectoryFileContents[relativePath] !== undefined;
- if (loaded || projectWorkspaceLoading[relativePath] || projectWorkspaceLoadErrors[relativePath] !== undefined) {
- return;
+ function loadSelectedProjectWorkspaceFiles() {
+ const relativePath = selectedProjectWorkspacePath;
+ if (
+ relativePath &&
+ selectedProjectWorkspaceEntry &&
+ !selectedProjectWorkspaceEntry.isDirectory &&
+ projectWorkspaceContents[relativePath] === undefined &&
+ !projectWorkspaceFileMetadata[relativePath] &&
+ !projectWorkspaceLoading[relativePath] &&
+ projectWorkspaceLoadErrors[relativePath] === undefined
+ ) {
+ void loadProjectWorkspaceFileDraft(relativePath);
}
+ const sourcePath = selectedIncludeTab;
+ if (!sourcePath || projectWorkspaceLoading[sourcePath] || projectWorkspaceLoadErrors[sourcePath] !== undefined) return;
+ if (includeFilePaths.has(sourcePath)) {
+ if (includeFilesState[sourcePath] === undefined) void loadProjectSourceFile('include', sourcePath);
+ } else if (loadedDirectoryFileContents[sourcePath] === undefined) {
+ void loadProjectSourceFile('directory', sourcePath);
+ }
+ }
- void loadProjectSourceFile(kind, relativePath);
+ onMount(() => {
+ let active = true;
+ const cache = queryClient.getQueryCache();
+ const loadAfterUpdate = async () => {
+ await tick();
+ if (!active) return;
+ initializeProjectPreferences();
+ loadSelectedProjectWorkspaceFiles();
+ };
+ const unsubscribe = cache.subscribe((event) => {
+ if (event.type !== 'updated' || (event.action.type !== 'success' && event.action.type !== 'error')) return;
+ const workspace = cache.find({ queryKey: queryKeys.projects.workspace(envId, projectId), exact: true });
+ const detail = cache.find({ queryKey: queryKeys.projects.detail(envId, projectId), exact: true });
+ if (event.query === workspace || event.query === detail) void loadAfterUpdate();
+ });
+ void loadAfterUpdate();
+ return () => {
+ active = false;
+ unsubscribe();
+ };
});
function remapProjectWorkspaceState(oldPath: string, newPath: string) {
@@ -1167,6 +1212,7 @@
if (remappedSelection) {
selectedFilePreference = remappedSelection;
}
+ loadSelectedProjectWorkspaceFiles();
}
function removeProjectWorkspaceState(relativePath: string) {
@@ -1188,6 +1234,7 @@
if (isWorkspaceFileSelectionUnder(selectedFile, relativePath)) {
selectedFilePreference = openTabs[0] ?? 'compose';
}
+ loadSelectedProjectWorkspaceFiles();
}
function createProjectWorkspaceFile(parentPath: string, name: string, content = '', stagedFile?: File) {
@@ -1290,7 +1337,9 @@
function toggleIncludeFileTab(relativePath: string) {
ensureIncludeFileUiState(relativePath);
- selectedIncludeTabPreference = selectedIncludeTab === relativePath ? null : relativePath;
+ if (selectedIncludeTab === relativePath) selectedIncludeTabPreference = null;
+ else selectedIncludeTabPreference = relativePath;
+ loadSelectedProjectWorkspaceFiles();
}
const allComposeContents = $derived.by(() => {
@@ -1494,35 +1543,37 @@
{#if selectedIncludeTab}
{@render selectedIncludeEditor(project, selectedIncludeTab)}
{:else}
- <ResizableSplit
- class="min-h-0 flex-1 lg:gap-2"
- firstClass="flex min-h-0 flex-col"
- secondClass="flex min-h-0 flex-col"
- bind:size={composeSplitWidth}
- minSize={minComposePaneWidth}
- minSecondSize={minEnvPaneWidth}
- defaultRatio={0.6}
- stackBelow={1024}
- ariaLabel={m.compose_editor_resize_compose_env()}
- persistKey={`arcane.compose.split:${project.id}:classic`}
- onResizeEnd={persistPrefs}
- >
- {#snippet first()}
- {@render composeOverrideEditor()}
- {/snippet}
-
- {#snippet second()}
- <div class="flex min-h-0 flex-1 flex-col">
- <CodePanel
- {...envPanelProps()}
- bind:open={envOpen}
- bind:value={$inputs.envContent.value}
- bind:hasErrors={envHasErrors}
- bind:validationReady={envValidationReady}
- />
- </div>
- {/snippet}
- </ResizableSplit>
+ {#key `arcane.compose.split:${project.id}:classic`}
+ <ResizableSplit
+ class="min-h-0 flex-1 lg:gap-2"
+ firstClass="flex min-h-0 flex-col"
+ secondClass="flex min-h-0 flex-col"
+ bind:size={composeSplitWidth}
+ minSize={minComposePaneWidth}
+ minSecondSize={minEnvPaneWidth}
+ defaultRatio={0.6}
+ stackBelow={1024}
+ ariaLabel={m.compose_editor_resize_compose_env()}
+ persistKey={`arcane.compose.split:${project.id}:classic`}
+ onResizeEnd={persistPrefs}
+ >
+ {#snippet first()}
+ {@render composeOverrideEditor()}
+ {/snippet}
+
+ {#snippet second()}
+ <div class="flex min-h-0 flex-1 flex-col">
+ <CodePanel
+ {...envPanelProps()}
+ bind:open={envOpen}
+ bind:value={$inputs.envContent.value}
+ bind:hasErrors={envHasErrors}
+ bind:validationReady={envValidationReady}
+ />
+ </div>
+ {/snippet}
+ </ResizableSplit>
+ {/key}
{/if}
</div>
{/if}
@@ -1692,11 +1743,13 @@
{/snippet}
{#snippet second()}
<div class="flex h-full min-h-0 flex-col overflow-hidden">
- <ProjectsLogsPanel
- projectId={project.id}
- bind:autoScroll={autoScrollStackLogs}
- isRunning={project.status?.toLowerCase().includes('running')}
- />
+ {#key project.id}
+ <ProjectsLogsPanel
+ projectId={project.id}
+ bind:autoScroll={autoScrollStackLogs}
+ isRunning={project.status?.toLowerCase().includes('running')}
+ />
+ {/key}
</div>
{/snippet}
</ResizableSplit>
diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.ts b/frontend/src/routes/(app)/projects/[projectId]/+page.ts
index 992a87caf..687b14aa5 100644
--- a/frontend/src/routes/(app)/projects/[projectId]/+page.ts
+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.ts
@@ -10,7 +10,7 @@ import type { PageLoad } from './$types';
async function loadGlobalVariables(queryClient: QueryClient) {
return tryCatch(
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.variables.list(),
queryFn: () => variableService.list()
})
@@ -34,7 +34,7 @@ export const load: PageLoad = async ({ params, parent }) => {
let project: ProjectData;
const operationResult = await tryCatch(
(async () =>
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.projects.detail(envId, params.projectId),
queryFn: () => projectService.getProjectForEnvironment(envId, params.projectId)
}))()
diff --git a/frontend/src/routes/(app)/projects/components/ProjectLogsPanel.svelte b/frontend/src/routes/(app)/projects/components/ProjectLogsPanel.svelte
index 8de2b2097..8f15796a2 100644
--- a/frontend/src/routes/(app)/projects/components/ProjectLogsPanel.svelte
+++ b/frontend/src/routes/(app)/projects/components/ProjectLogsPanel.svelte
@@ -2,6 +2,7 @@
import * as Card from '#lib/components/ui/card/index.js';
import LogViewer from '#lib/components/logs/log-viewer.svelte';
import LogControls from '#lib/components/logs/log-controls.svelte';
+ import { UseLogPreferences } from '#lib/hooks/use-log-preferences.svelte.js';
import LogPanelTitle from '#lib/components/logs/log-panel-title.svelte';
import { m } from '#lib/paraglide/messages.js';
import { TerminalIcon } from '#lib/icons/index.js';
@@ -18,11 +19,9 @@
let isStreaming = $state(false);
let viewer = $state<ReturnType<typeof LogViewer>>();
- let tailLines = $state(100);
- let autoStartLogs = $state(false);
+ const preferences = new UseLogPreferences();
let logSearchTerm = $state('');
let hasAutoStarted = $state(false);
- let showParsedJson = $state(false);
function handleStart() {
isStreaming = true;
@@ -38,12 +37,6 @@
await viewer?.clearLogs({ hard: true, restart: true });
}
- $effect(() => {
- if (projectId) {
- hasAutoStarted = false;
- }
- });
-
// The panel stays visible while the project is stopped; the stream pauses and
// picks back up (via auto-start) once the project is running again.
$effect(() => {
@@ -54,7 +47,7 @@
});
$effect(() => {
- if (autoStartLogs && !hasAutoStarted && !isStreaming && projectId && isRunning) {
+ if (preferences.autoStartLogs && !hasAutoStarted && !isStreaming && projectId && isRunning && viewer) {
hasAutoStarted = true;
handleStart();
}
@@ -70,9 +63,7 @@
<LogControls
bind:searchTerm={logSearchTerm}
bind:autoScroll
- bind:tailLines
- bind:autoStartLogs
- bind:showParsedJson
+ {preferences}
mobileLayout="full"
showDesktop={false}
{isStreaming}
@@ -87,9 +78,7 @@
<LogControls
bind:searchTerm={logSearchTerm}
bind:autoScroll
- bind:tailLines
- bind:autoStartLogs
- bind:showParsedJson
+ {preferences}
mobileLayout="none"
{isStreaming}
disabled={!projectId}
@@ -106,8 +95,8 @@
bind:this={viewer}
bind:autoScroll
{projectId}
- {tailLines}
- bind:showParsedJson
+ tailLines={preferences.tailLines}
+ bind:showParsedJson={preferences.showParsedJson}
type="project"
maxLines={500}
showTimestamps={true}
diff --git a/frontend/src/routes/(app)/projects/projects-table.svelte b/frontend/src/routes/(app)/projects/projects-table.svelte
index ec82ecb13..233fa420e 100644
--- a/frontend/src/routes/(app)/projects/projects-table.svelte
+++ b/frontend/src/routes/(app)/projects/projects-table.svelte
@@ -60,10 +60,7 @@
let actionStatus = $state<Record<string, ActionStatus>>({});
let checkingProjectIds = $state<Record<string, boolean>>({});
- let tagCatalog = $state<ProjectTagOption[]>([]);
- $effect(() => {
- tagCatalog = availableTags;
- });
+ let tagCatalog = $derived(availableTags);
let isBulkLoading = $state({
up: false,
diff --git a/frontend/src/routes/(app)/security/+page.svelte b/frontend/src/routes/(app)/security/+page.svelte
index 6c4bba0c6..c31222b44 100644
--- a/frontend/src/routes/(app)/security/+page.svelte
+++ b/frontend/src/routes/(app)/security/+page.svelte
@@ -9,7 +9,7 @@
import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';
import type { EnvironmentVulnerabilitySummary, VulnerabilityWithImage } from '#lib/types/environment.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
- import { onMount } from 'svelte';
+ import { onMount, onDestroy } from 'svelte';
import SecurityVulnerabilityTable from './security-vulnerability-table.svelte';
import SecurityPatchTable from './security-patch-table.svelte';
import type { ImagePatchTargetDto } from '#lib/types/docker.js';
@@ -75,6 +75,7 @@
const operationResult = await tryCatch(
(async () => {
const response = await imageService.listPatchTargets(patchRequestOptions);
+ if (destroyed) return;
patchTargets = { ...response, data: (response.data ?? []).map((t) => ({ ...t, id: t.imageId })) };
})()
);
@@ -206,22 +207,29 @@
useEnvironmentRefresh(refreshAll);
- let activePatchActivityIds = new Set<string>();
- $effect(() => {
- const active = new Set(
- activityStore.activities
- .filter(
- (a) =>
- (a.type === 'image_patch' || a.type === 'vulnerability_scan') && (a.status === 'queued' || a.status === 'running')
- )
- .map((a) => a.id)
- );
- const finished = [...activePatchActivityIds].some((id) => !active.has(id));
- activePatchActivityIds = active;
- if (finished) void loadPatches();
+ onMount(() => {
+ let activePatchActivityIds = new Set<string>();
+ let observedEnvironmentId: string | undefined;
+ return activityStore.subscribeActivities((activities) => {
+ const environmentId = environmentStore.selected?.id;
+ const active = new Set(
+ activities
+ .filter(
+ (activity) =>
+ (activity.sourceEnvironmentId || activity.environmentId || '0') === environmentId &&
+ (activity.type === 'image_patch' || activity.type === 'vulnerability_scan') &&
+ (activity.status === 'queued' || activity.status === 'running')
+ )
+ .map((activity) => activity.id)
+ );
+ const finished = observedEnvironmentId === environmentId && [...activePatchActivityIds].some((id) => !active.has(id));
+ observedEnvironmentId = environmentId;
+ activePatchActivityIds = active;
+ if (finished && environmentId && hasPermission('images:read', environmentId)) void loadPatches();
+ });
});
- $effect(() => () => {
+ onDestroy(() => {
destroyed = true;
stopScanPolling();
});
@@ -236,7 +244,9 @@
const operationResult = await tryCatch(
(async () => {
// Fetch all images with a high limit to get all of them
- const imagesResponse = await imageService.getImages({ pagination: { page: 1, limit: 1000 } });
+ const imagesResponse = await imageService.getImages({
+ pagination: { page: 1, limit: 1000 }
+ });
const images = imagesResponse.data ?? [];
if (images.length === 0) {
diff --git a/frontend/src/routes/(app)/security/+page.ts b/frontend/src/routes/(app)/security/+page.ts
index 584221ed3..43702877d 100644
--- a/frontend/src/routes/(app)/security/+page.ts
+++ b/frontend/src/routes/(app)/security/+page.ts
@@ -41,11 +41,11 @@ export const load: PageLoad = async ({ parent }) => {
const operationResult = await tryCatch(
(async () =>
Promise.all([
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.vulnerabilities.summaryByEnvironment(envId),
queryFn: () => vulnerabilityService.getEnvironmentSummaryForEnvironment(envId)
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.vulnerabilities.allByEnvironment(envId, requestForApi),
queryFn: () => vulnerabilityService.getAllVulnerabilitiesForEnvironment(envId, requestForApi)
})
diff --git a/frontend/src/routes/(app)/settings/+layout.svelte b/frontend/src/routes/(app)/settings/+layout.svelte
index 20abd12f0..7ad3af855 100644
--- a/frontend/src/routes/(app)/settings/+layout.svelte
+++ b/frontend/src/routes/(app)/settings/+layout.svelte
@@ -1,8 +1,9 @@
<script lang="ts">
import type { LayoutProps } from './$types';
import { page } from '$app/state';
- import { goto, beforeNavigate } from '$app/navigation';
+ import { goto } from '$app/navigation';
import { setContext } from 'svelte';
+ import type { SettingsFormContext, SettingsFormState } from '#lib/types/settings-form.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { SettingsIcon, ArrowRightIcon, ArrowLeftIcon } from '#lib/icons/index.js';
import { m } from '#lib/paraglide/messages.js';
@@ -45,42 +46,29 @@
}
});
- // Create a custom event to communicate with form components
- let formState = $state({
- hasChanges: false,
- isLoading: false,
- saveFunction: null as (() => Promise<void>) | null,
- resetFunction: null as (() => void) | null
- });
-
- // Set context so forms can update the header state
- setContext('settingsFormState', formState);
-
- // Query-only navigation keeps the same form mounted, so preserve its actions.
- beforeNavigate(({ from, to }) => {
- if (from?.url.pathname === to?.url.pathname) {
- return;
+ let formState = $state.raw<SettingsFormState>();
+ const formContext: SettingsFormContext = {
+ get activeForm() {
+ return formState;
+ },
+ set activeForm(form) {
+ formState = form;
}
-
- formState.hasChanges = false;
- formState.isLoading = false;
- formState.saveFunction = null;
- formState.resetFunction = null;
- });
+ };
+ setContext('settingsFormState', formContext);
function goBackToSettings() {
goto('/settings');
}
async function handleSave() {
- if (formState.saveFunction) {
+ if (formState?.saveFunction) {
await formState.saveFunction();
}
}
</script>
<div class="flex h-full min-h-full flex-col">
- <!-- Main Content -->
<main class="min-w-0 flex-1">
{#if isSubPage}
<div
@@ -128,12 +116,11 @@
</main>
</div>
-<!-- Mobile Floating Action Buttons -->
-{#if isSubPage && !isReadOnly && formState.saveFunction}
+{#if isSubPage && !isReadOnly && formState?.saveFunction}
<MobileFloatingFormActions
hasChanges={formState.hasChanges}
isLoading={formState.isLoading}
onSave={handleSave}
- onReset={() => formState.resetFunction && formState.resetFunction()}
+ onReset={() => formState?.resetFunction?.()}
/>
{/if}
diff --git a/frontend/src/routes/(app)/settings/activity/+page.svelte b/frontend/src/routes/(app)/settings/activity/+page.svelte
index 73f266fc3..c1538d50c 100644
--- a/frontend/src/routes/(app)/settings/activity/+page.svelte
+++ b/frontend/src/routes/(app)/settings/activity/+page.svelte
@@ -1,5 +1,4 @@
<script lang="ts">
- import { onMount } from 'svelte';
import { z } from 'zod/v4';
import settingsStore from '#lib/stores/config-store.js';
import { m } from '#lib/paraglide/messages.js';
@@ -28,14 +27,12 @@
};
};
- const { formInputs, registerOnMount } = createSettingsForm({
+ const { formInputs } = createSettingsForm({
schema: formSchema,
currentSettings: getFormDefaults(),
getCurrentSettings: getFormDefaults,
successMessage: m.activity_settings_saved()
});
-
- onMount(() => registerOnMount());
</script>
<SettingsPageLayout
diff --git a/frontend/src/routes/(app)/settings/api-keys/+page.ts b/frontend/src/routes/(app)/settings/api-keys/+page.ts
index 39139ced4..05a278b97 100644
--- a/frontend/src/routes/(app)/settings/api-keys/+page.ts
+++ b/frontend/src/routes/(app)/settings/api-keys/+page.ts
@@ -20,11 +20,11 @@ export const load: PageLoad = async ({ parent }) => {
} satisfies SearchPaginationSortRequest);
const [apiKeys, permissionsManifest] = await Promise.all([
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.apiKeys.list(apiKeyRequestOptions),
queryFn: () => apiKeyService.getApiKeys(apiKeyRequestOptions)
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: ['permissions', 'manifest'],
queryFn: () => roleService.getPermissionsManifest(),
staleTime: Infinity
diff --git a/frontend/src/routes/(app)/settings/authentication/+page.svelte b/frontend/src/routes/(app)/settings/authentication/+page.svelte
index 1c9f97374..a0ca86883 100644
--- a/frontend/src/routes/(app)/settings/authentication/+page.svelte
+++ b/frontend/src/routes/(app)/settings/authentication/+page.svelte
@@ -2,7 +2,7 @@
import type { PageProps } from './$types';
import * as AlertDialog from '#lib/components/ui/alert-dialog/index.js';
import { z } from 'zod/v4';
- import { getContext } from 'svelte';
+ import { untrack } from 'svelte';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { Switch } from '#lib/components/ui/switch/index.js';
import TextInputWithLabel from '#lib/components/form/text-input-with-label.svelte';
@@ -35,14 +35,6 @@
let { data }: PageProps = $props();
type AuthenticationTab = 'settings' | 'federated';
- const formState = getContext('settingsFormState') as
- | {
- hasChanges: boolean;
- isLoading: boolean;
- saveFunction: (() => Promise<void>) | null;
- resetFunction: (() => void) | null;
- }
- | undefined;
const authenticationTabItems = $derived.by(
() =>
@@ -171,7 +163,7 @@
oidcProviderLogoUrl: currentSettings.oidcProviderLogoUrl
});
- let { formInputs, form, settingsForm } = $derived(
+ const { formInputs, form, settingsForm } = untrack(() =>
createSettingsForm({
schema: formSchema,
currentSettings: formDefaults,
@@ -195,23 +187,6 @@
})
);
- const hasAuthenticationChanges = $derived(
- $formInputs.authLocalEnabled.value !== currentSettings.authLocalEnabled ||
- $formInputs.authSessionTimeout.value !== currentSettings.authSessionTimeout ||
- $formInputs.authPasswordPolicy.value !== currentSettings.authPasswordPolicy ||
- $formInputs.oidcEnabled.value !== currentSettings.oidcEnabled ||
- $formInputs.oidcMergeAccounts.value !== currentSettings.oidcMergeAccounts ||
- $formInputs.oidcSkipTlsVerify.value !== currentSettings.oidcSkipTlsVerify ||
- $formInputs.oidcAutoRedirectToProvider.value !== currentSettings.oidcAutoRedirectToProvider ||
- $formInputs.oidcClientId.value !== currentSettings.oidcClientId ||
- $formInputs.oidcIssuerUrl.value !== currentSettings.oidcIssuerUrl ||
- $formInputs.oidcScopes.value !== currentSettings.oidcScopes ||
- $formInputs.oidcGroupsClaim.value !== currentSettings.oidcGroupsClaim ||
- $formInputs.oidcProviderName.value !== currentSettings.oidcProviderName ||
- $formInputs.oidcProviderLogoUrl.value !== currentSettings.oidcProviderLogoUrl ||
- $formInputs.oidcClientSecret.value !== ''
- );
-
const redirectUri = $derived(`${globalThis?.location?.origin ?? ''}/auth/oidc/callback`);
const isOidcEnvForced = $derived(data.oidcStatus.envForced);
const isOidcForcedEnabled = $derived(isOidcEnvForced && currentSettings.oidcEnabled);
@@ -272,7 +247,7 @@
}
function customReset() {
- form.reset();
+ form.reset(formDefaults);
$formInputs.oidcClientSecret.value = '';
}
@@ -311,12 +286,7 @@
showMergeAccountsAlert = false;
}
- $effect(() => {
- settingsForm.registerFormActions(customSubmit, customReset);
- if (formState) {
- formState.hasChanges = hasAuthenticationChanges;
- }
- });
+ settingsForm.registerFormActions(customSubmit, customReset);
</script>
{#snippet passwordPolicyOption(value: 'basic' | 'standard' | 'strong', label: string, tooltip: string)}
diff --git a/frontend/src/routes/(app)/settings/authentication/+page.ts b/frontend/src/routes/(app)/settings/authentication/+page.ts
index c11b6bb11..984be2216 100644
--- a/frontend/src/routes/(app)/settings/authentication/+page.ts
+++ b/frontend/src/routes/(app)/settings/authentication/+page.ts
@@ -26,15 +26,15 @@ export const load: PageLoad = async ({ parent }) => {
// configure groups claim + the mappings that read from it in one place.
const [mappings, federatedCredentials, roles, environmentsPage] = await Promise.all([
oidcMappingService.list(),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.federatedCredentials.list(federatedCredentialRequestOptions),
queryFn: () => federatedCredentialService.list(federatedCredentialRequestOptions)
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: ['roles', 'all'],
queryFn: () => roleService.getAll()
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.environments.list({
pagination: { page: 1, limit: 1000 },
sort: { column: 'name', direction: 'asc' }
diff --git a/frontend/src/routes/(app)/settings/backups/+page.svelte b/frontend/src/routes/(app)/settings/backups/+page.svelte
index 05a2fc3d6..c52f5dfea 100644
--- a/frontend/src/routes/(app)/settings/backups/+page.svelte
+++ b/frontend/src/routes/(app)/settings/backups/+page.svelte
@@ -1,7 +1,9 @@
<script lang="ts">
import { tryCatch } from '#lib/utils/try-catch.js';
- import { goto } from '$app/navigation';
+ import { goto, afterNavigate } from '$app/navigation';
+ import { onMount, onDestroy } from 'svelte';
+ import userStore from '#lib/stores/user-store.js';
import { useBackupActivity } from '#lib/hooks/use-backup-activity.svelte.js';
import { activityStore } from '#lib/stores/activity.store.svelte.js';
import { toast } from 'svelte-sonner';
@@ -47,6 +49,7 @@
let systemVolumeOptions = $state<SystemVolumeBackupOption[]>([]);
let requestOptions = $derived<SearchPaginationSortRequest>(data.requestOptions);
let scheduleOpen = $state(false);
+ let scheduleSession = $state(0);
let scheduleType = $state<'system' | 'volume'>('system');
let editingScheduleId = $state<string | undefined>();
let keyOpen = $state(false);
@@ -140,6 +143,8 @@
const invalid = $derived(Boolean(actionKeyInvalid || keyError || destinationError));
function openSchedule(type: 'system' | 'volume' = 'system', id?: string) {
+ scheduleSession += 1;
+ if (type === 'volume') void loadSystemVolumeOptions();
scheduleType = type;
editingScheduleId = id;
scheduleOpen = true;
@@ -157,6 +162,7 @@
await systemBackupService.setRecoveryKey(generated.recoveryKey);
newRecoveryKey = generated.recoveryKey;
policyCollection = { ...policyCollection, recoveryKeyStored: true };
+ void discoverStoredBackups();
keyOpen = true;
})()
);
@@ -201,6 +207,7 @@
(async () => {
await systemBackupService.setRecoveryKey(importKeyInput.trim());
policyCollection = { ...policyCollection, recoveryKeyStored: true };
+ void discoverStoredBackups();
importKeyOpen = false;
toast.success(m.system_backups_recovery_key_saved());
})()
@@ -234,8 +241,6 @@
actionOpen = true;
}
- // The picker resets its own selection and search whenever the provider
- // changes, so the dialog only manages target, key, and provider.
async function openRestoreFiles(backup: BackupHistoryEntry) {
restoreFilesTarget = backup;
restoreFilesRecoveryKey = '';
@@ -247,10 +252,6 @@
function closeRestoreFiles() {
restoreFilesOpen = false;
- restoreFilesTarget = null;
- restoreFilesRecoveryKey = '';
- restoreFilesProvider = null;
- restoreFilesLoaded = false;
}
function updateRestoreFilesRecoveryKey(value: string) {
@@ -261,6 +262,9 @@
function loadRestoreFiles() {
if (!restoreFilesTarget || restoreFilesKeyInvalid) return;
+ restoreFilesSelectedPaths = [];
+ restoreFilesSelectAll = false;
+ restoreFilesSearch = '';
const backupID = restoreFilesTarget.id;
const recoveryKey = restoreFilesRecoveryKey.trim();
restoreFilesProvider = {
@@ -366,26 +370,32 @@
await goto(`/volumes/${encodeURIComponent(backup.resourceName)}?tab=backups`);
}
- // With a stored key the S3 repositories are scanned automatically, so
- // remote snapshots just appear in the table; the manual Find S3 backups
- // flow only exists for fresh instances that must supply an old key.
let autoDiscovered = false;
- $effect(() => {
- if (autoDiscovered || !policyCollection.recoveryKeyStored || data.destinations.length === 0) return;
+ let mounted = false;
+ async function discoverStoredBackups() {
+ if (!mounted || autoDiscovered || !policyCollection.recoveryKeyStored || !data.destinations.length) return;
+ if (!hasPermission('system-backups:manage')) return;
autoDiscovered = true;
- void (async () => {
- const operationResult = await tryCatch(
- (async () => {
- const counts = await Promise.all(data.destinations.map((item) => systemBackupService.discover(item.id, '')));
- if (counts.some((count) => count > 0)) await refresh();
- })()
- );
- if (operationResult.error !== null) {
- const error = operationResult.error;
-
- console.warn('S3 backup discovery failed', error);
- }
- })();
+ const destinations = data.destinations;
+ const result = await tryCatch(Promise.all(destinations.map((item) => systemBackupService.discover(item.id, ''))));
+ if (!mounted) return;
+ if (result.error !== null) {
+ console.warn('S3 backup discovery failed', result.error);
+ return;
+ }
+ if (result.data.some((count) => count > 0)) await refresh();
+ }
+ onMount(() => {
+ mounted = true;
+ return userStore.subscribe(() => {
+ void discoverStoredBackups();
+ });
+ });
+ onDestroy(() => {
+ mounted = false;
+ });
+ afterNavigate(() => {
+ void discoverStoredBackups();
});
const backupActivity = useBackupActivity(
@@ -783,12 +793,14 @@
</div>
{#if restoreFilesProvider}
- <BackupFilePicker
- provider={restoreFilesProvider}
- bind:selectedPaths={restoreFilesSelectedPaths}
- bind:selectAll={restoreFilesSelectAll}
- bind:search={restoreFilesSearch}
- />
+ {#key restoreFilesProvider}
+ <BackupFilePicker
+ provider={restoreFilesProvider}
+ bind:selectedPaths={restoreFilesSelectedPaths}
+ bind:selectAll={restoreFilesSelectAll}
+ bind:search={restoreFilesSearch}
+ />
+ {/key}
<Alert.Root variant="warning" class="py-2 [&>svg]:top-2">
<AlertIcon class="size-4" />
@@ -879,21 +891,23 @@
</div>
{/snippet}
{#snippet additionalContent()}
- {#if scheduleOpen}
- <SystemBackupScheduleDialog
- bind:open={scheduleOpen}
- initialType={scheduleType}
- policyId={editingScheduleId}
- systemPolicies={policyCollection.policies}
- volumePolicies={systemVolumePolicyCollection.policies}
- recoveryKeyStored={policyCollection.recoveryKeyStored}
- destinations={data.destinations}
- volumeOptions={systemVolumeOptions}
- volumeOptionsLoading={systemVolumeOptionsLoading}
- onLoadVolumeOptions={loadSystemVolumeOptions}
- onSystemSaved={(policies) => (policyCollection = { ...policyCollection, policies })}
- onVolumeSaved={(policies) => (systemVolumePolicyCollection = { policies })}
- />
+ {#if scheduleSession > 0}
+ {#key scheduleSession}
+ <SystemBackupScheduleDialog
+ bind:open={scheduleOpen}
+ initialType={scheduleType}
+ policyId={editingScheduleId}
+ systemPolicies={policyCollection.policies}
+ volumePolicies={systemVolumePolicyCollection.policies}
+ recoveryKeyStored={policyCollection.recoveryKeyStored}
+ destinations={data.destinations}
+ volumeOptions={systemVolumeOptions}
+ volumeOptionsLoading={systemVolumeOptionsLoading}
+ onLoadVolumeOptions={loadSystemVolumeOptions}
+ onSystemSaved={(policies) => (policyCollection = { ...policyCollection, policies })}
+ onVolumeSaved={(policies) => (systemVolumePolicyCollection = { policies })}
+ />
+ {/key}
{/if}
{@render recoveryKeyDialog()}
diff --git a/frontend/src/routes/(app)/settings/backups/s3/+page.svelte b/frontend/src/routes/(app)/settings/backups/s3/+page.svelte
index e97a5d916..26acd041d 100644
--- a/frontend/src/routes/(app)/settings/backups/s3/+page.svelte
+++ b/frontend/src/routes/(app)/settings/backups/s3/+page.svelte
@@ -18,16 +18,19 @@
let requestOptions = $derived<SearchPaginationSortRequest>(data.requestOptions);
let selected = $state<S3Destination | null>(null);
let dialogOpen = $state(false);
+ let destinationSession = $state(0);
let saving = $state(false);
const isReadOnly = $derived.by(() => $settingsStore.uiConfigDisabled);
function openCreate() {
selected = null;
+ destinationSession += 1;
dialogOpen = true;
}
function openEdit(destination: S3Destination) {
selected = destination;
+ destinationSession += 1;
dialogOpen = true;
}
@@ -45,7 +48,6 @@
}
destinations = await s3DestinationService.list(requestOptions);
dialogOpen = false;
- selected = null;
})()
);
if (operationResult.error !== null) {
@@ -112,6 +114,10 @@
/>
{/snippet}
{#snippet additionalContent()}
- <S3DestinationDialog bind:open={dialogOpen} destination={selected} {saving} onSubmit={saveDestination} />
+ {#if destinationSession > 0}
+ {#key destinationSession}
+ <S3DestinationDialog bind:open={dialogOpen} destination={selected} {saving} onSubmit={saveDestination} />
+ {/key}
+ {/if}
{/snippet}
</SettingsPageLayout>
diff --git a/frontend/src/routes/(app)/settings/backups/s3/s3-destination-dialog.svelte b/frontend/src/routes/(app)/settings/backups/s3/s3-destination-dialog.svelte
index d5d7e8f20..960fbd83e 100644
--- a/frontend/src/routes/(app)/settings/backups/s3/s3-destination-dialog.svelte
+++ b/frontend/src/routes/(app)/settings/backups/s3/s3-destination-dialog.svelte
@@ -1,4 +1,5 @@
<script lang="ts">
+ import { untrack } from 'svelte';
import { tryCatch } from '#lib/utils/try-catch.js';
import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog/index.js';
@@ -53,19 +54,19 @@
}
});
- let formData = $derived<CreateS3Destination>({
- name: open && destination ? destination.name : '',
- endpoint: open && destination ? (destination.endpoint ?? '') : '',
- bucket: open && destination ? destination.bucket : '',
- region: open && destination ? destination.region : 'us-east-1',
- accessKeyId: open && destination ? destination.accessKeyId : '',
+ const formData = untrack((): CreateS3Destination => ({
+ name: destination?.name ?? '',
+ endpoint: destination?.endpoint ?? '',
+ bucket: destination?.bucket ?? '',
+ region: destination?.region ?? 'us-east-1',
+ accessKeyId: destination?.accessKeyId ?? '',
secretAccessKey: '',
- prefix: open && destination ? (destination.prefix ?? '') : '',
- useSsl: open && destination ? destination.useSsl : true,
- forcePathStyle: open && destination ? destination.forcePathStyle : true
- });
+ prefix: destination?.prefix ?? '',
+ useSsl: destination?.useSsl ?? true,
+ forcePathStyle: destination?.forcePathStyle ?? true
+ }));
- let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
+ const { inputs, ...form } = createForm<typeof formSchema>(formSchema, formData);
let testing = $state(false);
let testedConfiguration = $state<string | null>(null);
const currentConfiguration = $derived(
@@ -82,12 +83,6 @@
);
const connectionVerified = $derived(testedConfiguration === currentConfiguration);
- $effect(() => {
- open;
- destination?.id;
- testedConfiguration = null;
- });
-
function handleSubmit() {
const data = form.validate();
if (!data) return;
diff --git a/frontend/src/routes/(app)/settings/backups/system-backup-schedule-dialog.svelte b/frontend/src/routes/(app)/settings/backups/system-backup-schedule-dialog.svelte
index cf4476341..841010b81 100644
--- a/frontend/src/routes/(app)/settings/backups/system-backup-schedule-dialog.svelte
+++ b/frontend/src/routes/(app)/settings/backups/system-backup-schedule-dialog.svelte
@@ -49,21 +49,19 @@
const editing = untrack(() => Boolean(policyId));
let backupType = $state<BackupType>(untrack(() => initialType));
- let selectionMode = $state<SystemVolumeBackupSelectionMode>('all');
- let volumeNames = $state<string[]>([]);
- let ignoreAnonymous = $state(true);
+ const initialVolumePolicy = untrack(() => volumePolicies.find((policy) => policy.id === policyId));
+ let selectionMode = $state<SystemVolumeBackupSelectionMode>(initialVolumePolicy?.selectionMode ?? 'all');
+ let volumeNames = $state<string[]>([...(initialVolumePolicy?.volumeNames ?? [])]);
+ let ignoreAnonymous = $state(initialVolumePolicy?.ignoreAnonymous ?? true);
const typeOptions = $derived([
{ label: m.system(), value: 'system', description: m.system_backups_type_system_description() },
{ label: m.resource_volume_cap(), value: 'volume', description: m.system_backups_type_volume_description() }
]);
- $effect(() => {
- if (backupType === 'volume') void onLoadVolumeOptions();
- });
-
function changeType(value: string) {
if (editing) return;
backupType = value as BackupType;
+ if (backupType === 'volume') void onLoadVolumeOptions();
selectionMode = 'all';
volumeNames = [];
ignoreAnonymous = true;
@@ -88,12 +86,6 @@
};
}
- function resetVolumeScope(policy?: SystemVolumeBackupPolicy) {
- selectionMode = policy?.selectionMode ?? 'all';
- volumeNames = policy ? [...policy.volumeNames] : [];
- ignoreAnonymous = policy?.ignoreAnonymous ?? true;
- }
-
async function updateSystemPolicies(policies: UpdateSystemBackupPolicy[]) {
return (await systemBackupService.updatePolicies(policies)).policies;
}
@@ -144,7 +136,6 @@
defaultSchedule="0 0 3 * * *"
defaultEnabled={recoveryKeyStored}
{destinations}
- resetKey={backupType}
beforeFields={TypeField}
updatePolicies={updateSystemPolicies}
messages={{
@@ -167,7 +158,6 @@
defaultSchedule="0 0 2 * * *"
showStopContainers
{destinations}
- resetKey={backupType}
beforeFields={TypeField}
afterFields={VolumeScope}
policyPayload={volumePayload}
@@ -179,7 +169,6 @@
removed: m.system_volume_backups_schedule_removed()
}}
onSaved={onVolumeSaved}
- onReset={resetVolumeScope}
contentClass="sm:max-w-[760px]"
/>
{/if}
diff --git a/frontend/src/routes/(app)/settings/builds/+page.svelte b/frontend/src/routes/(app)/settings/builds/+page.svelte
index ed1c83105..cc7d27c0c 100644
--- a/frontend/src/routes/(app)/settings/builds/+page.svelte
+++ b/frontend/src/routes/(app)/settings/builds/+page.svelte
@@ -1,5 +1,4 @@
<script lang="ts">
- import { onMount } from 'svelte';
import { z } from 'zod/v4';
import settingsStore from '#lib/stores/config-store.js';
import { SettingsPageLayout } from '#lib/layouts/index.js';
@@ -25,8 +24,12 @@
const getFormDefaults = () => {
const settings = $settingsStore || data.settings!;
+ let buildProvider = settings.buildProvider;
+ if (!settings.depotConfigured && !((settings.depotProjectId ?? '').trim() && (settings.depotToken ?? '').trim())) {
+ buildProvider = 'local';
+ }
return {
- buildProvider: settings.buildProvider,
+ buildProvider,
buildsDirectory: settings.buildsDirectory,
buildTimeout: settings.buildTimeout,
depotProjectId: settings.depotProjectId,
@@ -34,12 +37,13 @@
};
};
- const { formInputs, registerOnMount } = createSettingsForm({
+ const { formInputs } = createSettingsForm({
schema: formSchema,
currentSettings: getFormDefaults(),
getCurrentSettings: getFormDefaults,
onSave: async (payload) => {
const updated = { ...payload } as Record<string, unknown>;
+ if (!depotCredentialsPresent) updated['buildProvider'] = 'local';
if (!updated['depotToken']) {
delete updated['depotToken'];
}
@@ -72,13 +76,10 @@
return options;
});
- $effect(() => {
- if (!depotCredentialsPresent && $formInputs.buildProvider.value === 'depot') {
- $formInputs.buildProvider.value = 'local';
- }
+ const resolvedProvider = $derived.by(() => {
+ if (!depotCredentialsPresent) return 'local';
+ return $formInputs.buildProvider.value;
});
-
- onMount(() => registerOnMount());
</script>
<SettingsPageLayout
@@ -111,7 +112,13 @@
<SelectWithLabel
id="build-provider"
name="buildProvider"
- bind:value={$formInputs.buildProvider.value}
+ bind:value={
+ () => resolvedProvider,
+ (value) => {
+ if (value === 'depot' && depotCredentialsPresent) $formInputs.buildProvider.value = 'depot';
+ else $formInputs.buildProvider.value = 'local';
+ }
+ }
error={$formInputs.buildProvider.error}
label={m.build_settings_default_provider_label()}
description={m.build_settings_default_provider_description()}
@@ -137,14 +144,26 @@
<h3 class="text-base font-semibold">{m.depot()}</h3>
<div class="grid gap-5 sm:grid-cols-2">
<TextInputWithLabel
- bind:value={$formInputs.depotProjectId.value}
+ bind:value={
+ () => $formInputs.depotProjectId.value,
+ (value) => {
+ $formInputs.depotProjectId.value = value;
+ if (!depotCredentialsPresent) $formInputs.buildProvider.value = 'local';
+ }
+ }
error={$formInputs.depotProjectId.error}
label={m.build_settings_depot_project_id_label()}
description={m.build_settings_depot_project_id_description()}
placeholder={m.build_settings_depot_project_id_placeholder()}
/>
<TextInputWithLabel
- bind:value={$formInputs.depotToken.value}
+ bind:value={
+ () => $formInputs.depotToken.value,
+ (value) => {
+ $formInputs.depotToken.value = value;
+ if (!depotCredentialsPresent) $formInputs.buildProvider.value = 'local';
+ }
+ }
error={$formInputs.depotToken.error}
label={m.build_settings_depot_token_label()}
description={m.build_settings_depot_token_description()}
diff --git a/frontend/src/routes/(app)/settings/notifications/+page.svelte b/frontend/src/routes/(app)/settings/notifications/+page.svelte
index ec6f76215..598fcfdf1 100644
--- a/frontend/src/routes/(app)/settings/notifications/+page.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/+page.svelte
@@ -6,7 +6,8 @@
import SettingsRow from '#lib/components/settings/settings-row.svelte';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { toast } from 'svelte-sonner';
- import { getContext, onMount } from 'svelte';
+ import { getContext, onDestroy, onMount } from 'svelte';
+ import type { SettingsFormContext, SettingsFormState } from '#lib/types/settings-form.js';
import { SettingsPageLayout } from '#lib/layouts/index.js';
import settingsStore from '#lib/stores/config-store.js';
import { m } from '#lib/paraglide/messages.js';
@@ -67,15 +68,9 @@
let mobileDevices = $state<ApnsDevice[]>([]);
let testingDeviceId = $state<string | null>(null);
- type SettingsFormState = {
- hasChanges: boolean;
- isLoading: boolean;
- saveFunction: (() => Promise<void>) | null;
- resetFunction: (() => void) | null;
- };
type ProviderFormRef = { isValid: () => boolean };
- const formState = getContext<SettingsFormState | undefined>('settingsFormState');
+ const formContext = getContext<SettingsFormContext | undefined>('settingsFormState');
let providerFormRefs = $state<Partial<Record<NotificationProviderKey, ProviderFormRef>>>({});
let savedSettings = $state<NotificationSettingsByProvider>(createNotificationSettingsByProvider());
let providerValues = $state<NotificationProviderFormState>(createNotificationProviderFormState());
@@ -91,14 +86,19 @@
return settings?.config ? Object.prototype.hasOwnProperty.call(settings.config, field) : false;
}
- // Sync with settings form context
- $effect(() => {
- if (formState) {
- formState.hasChanges = hasChanges;
- formState.isLoading = isLoading;
- formState.saveFunction = onSubmit;
- formState.resetFunction = resetForm;
- }
+ const activeForm: SettingsFormState = {
+ get hasChanges() {
+ return hasChanges;
+ },
+ get isLoading() {
+ return isLoading;
+ },
+ saveFunction: onSubmit,
+ resetFunction: resetForm
+ };
+ if (formContext) formContext.activeForm = activeForm;
+ onDestroy(() => {
+ if (formContext?.activeForm === activeForm) formContext.activeForm = undefined;
});
onMount(() => {
diff --git a/frontend/src/routes/(app)/settings/notifications/+page.ts b/frontend/src/routes/(app)/settings/notifications/+page.ts
index 651ff7b61..9d125c861 100644
--- a/frontend/src/routes/(app)/settings/notifications/+page.ts
+++ b/frontend/src/routes/(app)/settings/notifications/+page.ts
@@ -8,7 +8,7 @@ export const load: PageLoad = async ({ parent }) => {
const operationResult = await tryCatch(
(async () => {
- const notificationSettings = await queryClient.fetchQuery({
+ const notificationSettings = await queryClient.query({
queryKey: queryKeys.notifications.settings(),
queryFn: () => notificationService.getSettings()
});
diff --git a/frontend/src/routes/(app)/settings/roles/+page.ts b/frontend/src/routes/(app)/settings/roles/+page.ts
index 22d4c7a43..aac6e4f71 100644
--- a/frontend/src/routes/(app)/settings/roles/+page.ts
+++ b/frontend/src/routes/(app)/settings/roles/+page.ts
@@ -17,7 +17,7 @@ export const load: PageLoad = async ({ parent }) => {
}
} satisfies SearchPaginationSortRequest);
- const roles = await queryClient.fetchQuery({
+ const roles = await queryClient.query({
queryKey: ['roles', 'list', rolesRequestOptions],
queryFn: () => roleService.getRoles(rolesRequestOptions)
});
diff --git a/frontend/src/routes/(app)/settings/roles/[id]/+page.ts b/frontend/src/routes/(app)/settings/roles/[id]/+page.ts
index b488600ae..a56be5f8f 100644
--- a/frontend/src/routes/(app)/settings/roles/[id]/+page.ts
+++ b/frontend/src/routes/(app)/settings/roles/[id]/+page.ts
@@ -16,12 +16,12 @@ export const load: PageLoad = async ({ parent, params }) => {
const [role, permissionsManifest] = await Promise.all([
tryCatch(
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: ['roles', 'detail', params.id],
queryFn: () => roleService.get(params.id)
})
).then((result) => (result.error ? null : result.data)),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: ['roles', 'permissions-manifest'],
queryFn: () => roleService.getPermissionsManifest()
})
diff --git a/frontend/src/routes/(app)/settings/roles/new/+page.ts b/frontend/src/routes/(app)/settings/roles/new/+page.ts
index 701730de6..ece7543ee 100644
--- a/frontend/src/routes/(app)/settings/roles/new/+page.ts
+++ b/frontend/src/routes/(app)/settings/roles/new/+page.ts
@@ -13,7 +13,7 @@ export const load: PageLoad = async ({ parent }) => {
throw redirect(302, '/settings/roles');
}
- const permissionsManifest = await queryClient.fetchQuery({
+ const permissionsManifest = await queryClient.query({
queryKey: ['roles', 'permissions-manifest'],
queryFn: () => roleService.getPermissionsManifest()
});
diff --git a/frontend/src/routes/(app)/settings/timeouts/+page.svelte b/frontend/src/routes/(app)/settings/timeouts/+page.svelte
index 2e3d0f52e..5469062c1 100644
--- a/frontend/src/routes/(app)/settings/timeouts/+page.svelte
+++ b/frontend/src/routes/(app)/settings/timeouts/+page.svelte
@@ -1,5 +1,4 @@
<script lang="ts">
- import { onMount } from 'svelte';
import { z } from 'zod/v4';
import settingsStore from '#lib/stores/config-store.js';
import { m } from '#lib/paraglide/messages.js';
@@ -37,14 +36,12 @@
};
};
- const { formInputs, registerOnMount } = createSettingsForm({
+ const { formInputs } = createSettingsForm({
schema: formSchema,
currentSettings: getFormDefaults(),
getCurrentSettings: getFormDefaults,
successMessage: m.timeouts_save()
});
-
- onMount(() => registerOnMount());
</script>
<SettingsPageLayout
diff --git a/frontend/src/routes/(app)/settings/users/+page.svelte b/frontend/src/routes/(app)/settings/users/+page.svelte
index 46bb09879..a74d32313 100644
--- a/frontend/src/routes/(app)/settings/users/+page.svelte
+++ b/frontend/src/routes/(app)/settings/users/+page.svelte
@@ -168,13 +168,9 @@
const avatarMaxUploadSizeMb = $derived(
Number($settingsStore?.avatarMaxUploadSizeMb) > 0 ? Number($settingsStore?.avatarMaxUploadSizeMb) : 2
);
- let avatarSizeInput = $state('');
+ let avatarSizeInput = $derived(String(avatarMaxUploadSizeMb));
let avatarSizeError = $state<string | null>(null);
- $effect(() => {
- avatarSizeInput = String(avatarMaxUploadSizeMb);
- });
-
async function saveAvatarSettings(patch: Partial<Settings>) {
const operationResult = await tryCatch(
(async () => {
diff --git a/frontend/src/routes/(app)/settings/users/+page.ts b/frontend/src/routes/(app)/settings/users/+page.ts
index 21f8df896..33ce86ce4 100644
--- a/frontend/src/routes/(app)/settings/users/+page.ts
+++ b/frontend/src/routes/(app)/settings/users/+page.ts
@@ -21,16 +21,16 @@ export const load: PageLoad = async ({ parent }) => {
} satisfies SearchPaginationSortRequest);
const [users, roles, environmentsPage] = await Promise.all([
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.users.list(userRequestOptions),
queryFn: () => userService.getUsers(userRequestOptions)
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: ['roles', 'all'],
queryFn: () => roleService.getAll(),
staleTime: 30_000
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: ['environments', 'all-for-role-assignments'],
queryFn: () => environmentManagementService.getEnvironments({ pagination: { page: 1, limit: 1000 } }),
staleTime: 30_000
diff --git a/frontend/src/routes/(app)/swarm/cluster/+page.svelte b/frontend/src/routes/(app)/swarm/cluster/+page.svelte
index 74e9f5419..6c3cb96db 100644
--- a/frontend/src/routes/(app)/swarm/cluster/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/cluster/+page.svelte
@@ -11,16 +11,13 @@
import { EyeOffIcon, EyeOnIcon, LockIcon, SettingsIcon, UsersIcon } from '#lib/icons/index.js';
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';
import { m } from '#lib/paraglide/messages.js';
+ import { createQuery } from '@tanstack/svelte-query';
+ import { queryKeys } from '#lib/query/query-keys.js';
+ import userStore from '#lib/stores/user-store.js';
import { swarmService } from '#lib/services/swarm-service.js';
import { hasPermission } from '#lib/utils/auth.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
- import type {
- SwarmInfo,
- SwarmInitRequest,
- SwarmJoinRequest,
- SwarmJoinTokensResponse,
- SwarmUpdateRequest
- } from '#lib/types/swarm.js';
+ import type { SwarmInitRequest, SwarmJoinRequest, SwarmUpdateRequest } from '#lib/types/swarm.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import { toast } from 'svelte-sonner';
@@ -30,13 +27,53 @@
const canManageSwarm = $derived(hasPermission('swarm:nodes', currentEnvId));
const canEasyJoin = $derived(hasPermission('swarm:nodes', currentEnvId) && hasPermission('swarm:unlock', currentEnvId));
- let swarmInfo = $state<SwarmInfo | null>(null);
- let joinTokens = $state<SwarmJoinTokensResponse | null>(null);
- let unlockKey = $state('');
+ const swarmInfoQuery = createQuery(() => {
+ const environmentId = currentEnvId;
+ $userStore;
+ return {
+ queryKey: queryKeys.swarm.info(environmentId ?? ''),
+ queryFn: async () => {
+ await environmentStore.ready;
+ return swarmService.getSwarmInfo();
+ },
+ enabled: !!environmentId && hasPermission('swarm:read', environmentId),
+ retry: false
+ };
+ });
+ const joinTokensQuery = createQuery(() => {
+ const environmentId = currentEnvId;
+ $userStore;
+ return {
+ queryKey: queryKeys.swarm.joinTokens(environmentId ?? ''),
+ queryFn: async () => {
+ await environmentStore.ready;
+ return swarmService.getSwarmJoinTokens();
+ },
+ enabled: !!environmentId && hasPermission('swarm:unlock', environmentId),
+ retry: false
+ };
+ });
+ const unlockKeyQuery = createQuery(() => {
+ const environmentId = currentEnvId;
+ $userStore;
+ return {
+ queryKey: queryKeys.swarm.unlockKey(environmentId ?? ''),
+ queryFn: async () => {
+ await environmentStore.ready;
+ return swarmService.getSwarmUnlockKey();
+ },
+ enabled: !!environmentId && hasPermission('swarm:unlock', environmentId),
+ retry: false
+ };
+ });
+ const swarmInfo = $derived(swarmInfoQuery.data ?? null);
+ const joinTokens = $derived(joinTokensQuery.data ?? null);
+ const unlockKey = $derived(unlockKeyQuery.data?.unlockKey ?? '');
let showManagerToken = $state(false);
let showWorkerToken = $state(false);
let securityDialogOpen = $state(false);
let easyJoinDialogOpen = $state(false);
+ let easyJoinSession = $state(0);
const isSwarmInitialized = $derived(!!swarmInfo?.id);
let initForm = $state({
@@ -56,9 +93,10 @@
let leaveForce = $state(false);
let unlockInput = $state('');
+ let specDraft = $state<string | null>(null);
+ const updateSpec = $derived(specDraft ?? JSON.stringify(swarmInfo?.spec ?? {}, null, 2));
let updateForm = $state({
version: '',
- spec: '{}',
rotateWorkerToken: false,
rotateManagerToken: false,
rotateManagerUnlockKey: false
@@ -97,36 +135,38 @@
function loadCurrentSpec() {
const currentSpec = swarmInfo?.spec ?? {};
- updateForm.spec = JSON.stringify(currentSpec, null, 2);
+ specDraft = JSON.stringify(currentSpec, null, 2);
}
async function refresh() {
+ const environmentId = currentEnvId;
+ if (!environmentId) return;
isLoading.refresh = true;
+ showManagerToken = false;
+ showWorkerToken = false;
try {
- const [infoRes, tokensRes, unlockRes] = await Promise.allSettled([
- swarmService.getSwarmInfo(),
- swarmService.getSwarmJoinTokens(),
- swarmService.getSwarmUnlockKey()
- ]);
-
- swarmInfo = infoRes.status === 'fulfilled' ? infoRes.value : null;
- joinTokens = tokensRes.status === 'fulfilled' ? tokensRes.value : null;
- unlockKey = unlockRes.status === 'fulfilled' ? unlockRes.value.unlockKey : '';
- showManagerToken = false;
- showWorkerToken = false;
-
- if (swarmInfo && updateForm.spec === '{}') {
- loadCurrentSpec();
- }
+ const requests: Promise<unknown>[] = [];
+ if (hasPermission('swarm:read', environmentId)) requests.push(swarmInfoQuery.refetch());
+ if (hasPermission('swarm:unlock', environmentId)) requests.push(joinTokensQuery.refetch(), unlockKeyQuery.refetch());
+ await Promise.all(requests);
} finally {
- isLoading.refresh = false;
+ if (environmentId === currentEnvId) isLoading.refresh = false;
}
}
- useEnvironmentRefresh(refresh);
-
- $effect(() => {
- refresh();
+ useEnvironmentRefresh(() => {
+ showManagerToken = false;
+ showWorkerToken = false;
+ securityDialogOpen = false;
+ easyJoinDialogOpen = false;
+ specDraft = null;
+ updateForm.version = '';
+ updateForm.rotateWorkerToken = false;
+ updateForm.rotateManagerToken = false;
+ updateForm.rotateManagerUnlockKey = false;
+ unlockInput = '';
+ joinForm.joinToken = '';
+ isLoading.refresh = false;
});
async function handleInit() {
@@ -230,7 +270,7 @@
}
async function handleUpdateSpec() {
- const spec = parseObjectJSON(updateForm.spec, m.swarm_cluster_spec_label());
+ const spec = parseObjectJSON(updateSpec, m.swarm_cluster_spec_label());
if (!spec) return;
const parsedVersion = Number.parseInt(updateForm.version, 10);
@@ -264,7 +304,10 @@
id: 'easy-join',
action: 'create' as const,
label: m.swarm_easy_join_action(),
- onclick: () => (easyJoinDialogOpen = true)
+ onclick: () => {
+ easyJoinSession += 1;
+ easyJoinDialogOpen = true;
+ }
}
]
: []),
@@ -460,7 +503,7 @@
<Textarea
rows={22}
placeholder={m.swarm_cluster_spec_placeholder()}
- bind:value={updateForm.spec}
+ bind:value={() => updateSpec, (value) => (specDraft = value)}
class="min-h-[34rem] font-mono text-xs"
/>
<div class="flex justify-end border-t pt-4">
@@ -627,6 +670,8 @@
{/snippet}
</ResponsiveDialog>
- <EasyJoinDialog bind:open={easyJoinDialogOpen} onComplete={refresh} />
+ {#key `${easyJoinSession}:${currentEnvId}`}
+ <EasyJoinDialog bind:open={easyJoinDialogOpen} onComplete={refresh} />
+ {/key}
{/snippet}
</ResourcePageLayout>
diff --git a/frontend/src/routes/(app)/swarm/cluster/easy-join-dialog.svelte b/frontend/src/routes/(app)/swarm/cluster/easy-join-dialog.svelte
index 8978d121d..143f2f142 100644
--- a/frontend/src/routes/(app)/swarm/cluster/easy-join-dialog.svelte
+++ b/frontend/src/routes/(app)/swarm/cluster/easy-join-dialog.svelte
@@ -1,5 +1,11 @@
<script lang="ts">
import { tryCatch } from '#lib/utils/try-catch.js';
+ import { createQuery } from '@tanstack/svelte-query';
+ import { queryKeys } from '#lib/query/query-keys.js';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+ import userStore from '#lib/stores/user-store.js';
+ import { hasPermission } from '#lib/utils/auth.js';
+ import { onDestroy } from 'svelte';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import * as Alert from '#lib/components/ui/alert/index.js';
@@ -19,52 +25,51 @@
};
let { open = $bindable(false), managerEnvironmentId, targetEnvironmentId, onComplete }: Props = $props();
- let candidates = $state<SwarmJoinCandidate[]>([]);
- let targets = $state<Record<string, SwarmJoinEnvironmentTarget>>({});
- let results = $state<SwarmJoinEnvironmentResult[]>([]);
- let errorMessage = $state('');
- let isLoading = $state(false);
- let loaded = $state(false);
-
- $effect(() => {
- if (!open) {
- loaded = false;
- return;
- }
- if (loaded) return;
- loaded = true;
- void loadCandidates();
+ const requestedManagerId = $derived(managerEnvironmentId ?? environmentStore.selected?.id);
+ const candidatesQuery = createQuery(() => {
+ const environmentId = requestedManagerId;
+ return {
+ queryKey: queryKeys.swarm.joinCandidates(environmentId ?? null, $userStore),
+ queryFn: async () => {
+ await environmentStore.ready;
+ return swarmService.getSwarmJoinCandidates(environmentId!);
+ },
+ enabled: open && !!environmentId && hasPermission('swarm:join', environmentId)
+ };
});
-
- async function loadCandidates() {
- isLoading = true;
- errorMessage = '';
- candidates = [];
- targets = {};
- results = [];
- try {
- const operationResult = await tryCatch(
- (async () => {
- const candidateData = await swarmService.getSwarmJoinCandidates(managerEnvironmentId);
- candidates = targetEnvironmentId
- ? candidateData.filter((candidate) => candidate.environmentId === targetEnvironmentId)
- : candidateData;
- if (targetEnvironmentId && candidates[0]) toggleCandidate(candidates[0], true);
- })()
- );
- if (operationResult.error !== null) {
- const error = operationResult.error;
-
- errorMessage = extractApiErrorMessage(error);
+ const candidates = $derived(
+ (candidatesQuery.data ?? []).filter((candidate) => !targetEnvironmentId || candidate.environmentId === targetEnvironmentId)
+ );
+ let targetDraft = $state<Record<string, SwarmJoinEnvironmentTarget> | null>(null);
+ const targets = $derived.by(() => {
+ if (targetDraft) return targetDraft;
+ if (!targetEnvironmentId || !candidates[0]) return {};
+ const candidate = candidates[0];
+ return {
+ [candidate.environmentId]: {
+ environmentId: candidate.environmentId,
+ role: 'worker' as const,
+ availability: 'active' as const
}
- } finally {
- isLoading = false;
- }
- }
+ };
+ });
+ let results = $state<SwarmJoinEnvironmentResult[]>([]);
+ let mutationError = $state('');
+ const errorMessage = $derived.by(() => {
+ if (mutationError) return mutationError;
+ if (candidatesQuery.error) return extractApiErrorMessage(candidatesQuery.error);
+ return '';
+ });
+ let isJoining = $state(false);
+ const isLoading = $derived(candidatesQuery.isFetching || isJoining);
+ let destroyed = false;
+ onDestroy(() => {
+ destroyed = true;
+ });
function toggleCandidate(candidate: SwarmJoinCandidate, selected: boolean) {
if (selected) {
- targets = {
+ targetDraft = {
...targets,
[candidate.environmentId]: {
environmentId: candidate.environmentId,
@@ -76,42 +81,42 @@
}
const next = { ...targets };
delete next[candidate.environmentId];
- targets = next;
+ targetDraft = next;
}
function updateTarget(environmentId: string, update: Partial<SwarmJoinEnvironmentTarget>) {
const current = targets[environmentId];
if (!current) return;
- targets = { ...targets, [environmentId]: { ...current, ...update } };
+ targetDraft = { ...targets, [environmentId]: { ...current, ...update } };
}
async function joinSelected() {
+ const environmentId = requestedManagerId;
+ if (!environmentId) return;
const selectedTargets = Object.values(targets);
if (selectedTargets.length === 0) {
- errorMessage = m.swarm_easy_join_targets_required();
+ mutationError = m.swarm_easy_join_targets_required();
return;
}
- isLoading = true;
- errorMessage = '';
+ isJoining = true;
+ mutationError = '';
results = [];
try {
const operationResult = await tryCatch(
(async () => {
- const response = await swarmService.joinEnvironments(
- { remoteAddrs: [], targets: selectedTargets },
- managerEnvironmentId
- );
+ const response = await swarmService.joinEnvironments({ remoteAddrs: [], targets: selectedTargets }, environmentId);
+ if (destroyed || environmentId !== requestedManagerId) return;
results = response.results;
await onComplete?.();
})()
);
- if (operationResult.error !== null) {
+ if (operationResult.error !== null && !destroyed && environmentId === requestedManagerId) {
const error = operationResult.error;
- errorMessage = extractApiErrorMessage(error);
+ mutationError = extractApiErrorMessage(error);
}
} finally {
- isLoading = false;
+ isJoining = false;
}
}
diff --git a/frontend/src/routes/(app)/swarm/nodes/+page.svelte b/frontend/src/routes/(app)/swarm/nodes/+page.svelte
index 7df47bbdb..38c25da58 100644
--- a/frontend/src/routes/(app)/swarm/nodes/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/nodes/+page.svelte
@@ -1,4 +1,6 @@
<script lang="ts">
+ import { onMount } from 'svelte';
+ import userStore from '#lib/stores/user-store.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import * as Alert from '#lib/components/ui/alert/index.js';
@@ -18,14 +20,16 @@
let nodes = $derived(data.nodes);
let requestOptions = $derived(data.requestOptions);
let isLoading = $state({ refresh: false });
- let reconciledEnvironmentId = $state<string | null>(null);
+
const currentEnvironmentId = $derived(environmentStore.selected?.id ?? null);
- const canManageNodes = $derived(hasPermission('swarm:nodes', currentEnvironmentId ?? undefined));
async function refresh() {
+ const environmentId = await environmentStore.getCurrentEnvironmentId();
await simpleRefresh(
() => swarmService.getNodes(requestOptions),
- (data) => (nodes = data),
+ (data) => {
+ if (environmentId === currentEnvironmentId) nodes = data;
+ },
m.common_refresh_failed({ resource: m.nodes() }),
(loading) => (isLoading.refresh = loading)
);
@@ -33,11 +37,30 @@
useEnvironmentRefresh(refresh);
- $effect(() => {
- const environmentId = currentEnvironmentId;
- if (!environmentId || !canManageNodes || reconciledEnvironmentId === environmentId) return;
- reconciledEnvironmentId = environmentId;
- void tryCatch(swarmService.reconcileNodeAgents().then(refresh)).then((result) => (result.error ? undefined : result.data));
+ onMount(() => {
+ let active = true;
+ let reconciledEnvironmentId: string | null = null;
+ async function reconcileSelectedEnvironment() {
+ await environmentStore.ready;
+ const environmentId = environmentStore.selected?.id;
+ if (!active || !environmentId || !hasPermission('swarm:nodes', environmentId) || reconciledEnvironmentId === environmentId)
+ return;
+ reconciledEnvironmentId = environmentId;
+ const result = await tryCatch(swarmService.reconcileNodeAgents());
+ if (!active || environmentId !== environmentStore.selected?.id || result.error !== null) return;
+ await refresh();
+ }
+ const unsubscribeUser = userStore.subscribe(() => {
+ void reconcileSelectedEnvironment();
+ });
+ const unsubscribeEnvironment = environmentStore.subscribeSelected(() => {
+ void reconcileSelectedEnvironment();
+ });
+ return () => {
+ active = false;
+ unsubscribeUser();
+ unsubscribeEnvironment();
+ };
});
const totalNodes = $derived(nodes?.pagination?.totalItems ?? nodes?.data?.length ?? 0);
diff --git a/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte b/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte
index e83024d89..78da12dbb 100644
--- a/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte
+++ b/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte
@@ -64,11 +64,15 @@
return 'gray';
}
- async function refreshNodes() {
- nodes = await swarmService.getNodes(requestOptions);
+ async function refreshNodes(options = requestOptions) {
+ const environmentId = await environmentStore.getCurrentEnvironmentId();
+ const result = await swarmService.getNodes(options);
+ if (environmentId !== currentEnvId) return nodes;
+ nodes = result;
if (selectedNode) {
selectedNode = nodes.data.find((node) => node.id === selectedNode?.id) ?? selectedNode;
}
+ return nodes;
}
async function loadAgentDeployment(node: SwarmNodeSummary, rotate = false) {
@@ -483,7 +487,7 @@
bind:requestOptions
bind:mobileFieldVisibility
selectionDisabled={true}
- onRefresh={async (options) => (nodes = await swarmService.getNodes(options))}
+ onRefresh={refreshNodes}
{columns}
{mobileFields}
rowActions={RowActions}
diff --git a/frontend/src/routes/(app)/swarm/services/components/ServiceLogsPanel.svelte b/frontend/src/routes/(app)/swarm/services/components/ServiceLogsPanel.svelte
index af018bbb0..f68882522 100644
--- a/frontend/src/routes/(app)/swarm/services/components/ServiceLogsPanel.svelte
+++ b/frontend/src/routes/(app)/swarm/services/components/ServiceLogsPanel.svelte
@@ -2,6 +2,7 @@
import * as Card from '#lib/components/ui/card/index.js';
import LogViewer from '#lib/components/logs/log-viewer.svelte';
import LogControls from '#lib/components/logs/log-controls.svelte';
+ import { UseLogPreferences } from '#lib/hooks/use-log-preferences.svelte.js';
import LogPanelTitle from '#lib/components/logs/log-panel-title.svelte';
import { m } from '#lib/paraglide/messages.js';
import { refreshLogViewerStream, startLogViewerStream, stopLogViewerStream } from '#lib/utils/log-viewer.js';
@@ -16,9 +17,8 @@
let isStreaming = $state(false);
let viewer = $state<ReturnType<typeof LogViewer>>();
let autoScroll = $state(true);
- let autoStartLogs = $state(false);
+ const preferences = new UseLogPreferences();
let logSearchTerm = $state('');
- let showParsedJson = $state(false);
function handleStart() {
startLogViewerStream(viewer);
@@ -41,7 +41,7 @@
}
$effect(() => {
- if (autoStartLogs && !isStreaming && serviceId && viewer) {
+ if (preferences.autoStartLogs && !isStreaming && serviceId && viewer) {
viewer.startLogStream();
}
});
@@ -56,8 +56,7 @@
<LogControls
bind:searchTerm={logSearchTerm}
bind:autoScroll
- bind:autoStartLogs
- bind:showParsedJson
+ {preferences}
{isStreaming}
disabled={!serviceId}
onStart={handleStart}
@@ -74,7 +73,8 @@
bind:autoScroll
type="service"
{serviceId}
- bind:showParsedJson
+ bind:showParsedJson={preferences.showParsedJson}
+ tailLines={preferences.tailLines}
maxLines={500}
showTimestamps={true}
height="calc(100vh - 320px)"
diff --git a/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.svelte b/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.svelte
index e346d5000..7c5cde9a8 100644
--- a/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.svelte
+++ b/frontend/src/routes/(app)/swarm/services/components/ServiceTasksPanel.svelte
@@ -1,12 +1,15 @@
<script lang="ts">
- import { tryCatch } from '#lib/utils/try-catch.js';
+ import { createQuery } from '@tanstack/svelte-query';
+ import { queryKeys } from '#lib/query/query-keys.js';
+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';
+ import userStore from '#lib/stores/user-store.js';
+ import { hasPermission } from '#lib/utils/auth.js';
import * as Card from '#lib/components/ui/card/index.js';
import { Badge } from '#lib/components/ui/badge/index.js';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import { m } from '#lib/paraglide/messages.js';
import { swarmService } from '#lib/services/swarm-service.js';
- import type { SwarmTaskSummary } from '#lib/types/swarm.js';
import { getSwarmTaskStateVariant, sortSwarmTasks } from '#lib/utils/swarm-tasks.js';
import { JobsIcon, ConnectionIcon } from '#lib/icons/index.js';
@@ -18,37 +21,22 @@
serviceId: string;
} = $props();
- let tasks = $state<SwarmTaskSummary[]>([]);
- let isLoading = $state(false);
- let hasLoaded = $state(false);
-
- async function loadTasks() {
- isLoading = true;
- try {
- const operationResult = await tryCatch(
- (async () => {
- const result = await swarmService.getServiceTasks(serviceId, {
- pagination: { page: 1, limit: 100 }
- });
- tasks = sortSwarmTasks(result.data ?? []);
- })()
- );
- if (operationResult.error !== null) {
- const err = operationResult.error;
-
- console.error(m.swarm_service_tasks_load_failed_log(), err);
- }
- } finally {
- isLoading = false;
- hasLoaded = true;
- }
- }
-
- $effect(() => {
- if (serviceName && serviceId && !hasLoaded) {
- loadTasks();
- }
+ const tasksQuery = createQuery(() => {
+ const environmentId = environmentStore.selected?.id;
+ const requestedServiceId = serviceId;
+ $userStore;
+ return {
+ queryKey: queryKeys.swarm.serviceTasks(environmentId ?? '', requestedServiceId),
+ queryFn: async () => {
+ await environmentStore.ready;
+ return swarmService.getServiceTasks(requestedServiceId, { pagination: { page: 1, limit: 100 } });
+ },
+ enabled: !!environmentId && !!serviceName && !!requestedServiceId && hasPermission('swarm:read', environmentId)
+ };
});
+ const tasks = $derived(sortSwarmTasks(tasksQuery.data?.data ?? []));
+ const isLoading = $derived(tasksQuery.isFetching);
+ const hasLoaded = $derived(tasksQuery.isFetched);
</script>
<Card.Root>
@@ -62,7 +50,7 @@
{m.swarm_service_tasks_count({ count: tasks.length })}
</Card.Description>
</div>
- <ArcaneButton action="refresh" size="sm" onclick={loadTasks} disabled={isLoading}>
+ <ArcaneButton action="refresh" size="sm" onclick={() => tasksQuery.refetch()} disabled={isLoading}>
{m.common_refresh()}
</ArcaneButton>
</div>
diff --git a/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte
index a8efeb2cf..b2b42a2f9 100644
--- a/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/stacks/[name]/+page.svelte
@@ -287,69 +287,71 @@
{#if sourceState === 'available' && source}
{@const stackSource = source}
<div class="flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border border-border bg-card">
- <ResizableSplit
- class="min-h-0 flex-1"
- variant="flush"
- firstClass="bg-muted/20 border-border flex min-h-0 flex-col border-b lg:border-r lg:border-b-0"
- secondClass="flex min-h-0 flex-col"
- bind:size={sourceTreeWidth}
- minSize={200}
- maxSize={480}
- minSecondSize={360}
- defaultRatio={0.2}
- stackBelow={1024}
- ariaLabel={m.compose_editor_resize_files_panel()}
- persistKey={`arcane.swarm.split:${stackName}:source`}
- >
- {#snippet first()}
- <WorkspaceFileTreePanel
- leadingRows={sourceWorkspaceLeadingRows}
- entries={[]}
- selectedFile={selectedSourceFile}
- onSelect={openSourceTab}
- />
- {/snippet}
-
- {#snippet second()}
- <div class="flex h-full min-h-0 flex-1 flex-col">
- <EditorTabStrip
- tabs={sourceTabs}
- activeKey={activeSourceTab}
+ {#key `arcane.swarm.split:${stackName}:source`}
+ <ResizableSplit
+ class="min-h-0 flex-1"
+ variant="flush"
+ firstClass="bg-muted/20 border-border flex min-h-0 flex-col border-b lg:border-r lg:border-b-0"
+ secondClass="flex min-h-0 flex-col"
+ bind:size={sourceTreeWidth}
+ minSize={200}
+ maxSize={480}
+ minSecondSize={360}
+ defaultRatio={0.2}
+ stackBelow={1024}
+ ariaLabel={m.compose_editor_resize_files_panel()}
+ persistKey={`arcane.swarm.split:${stackName}:source`}
+ >
+ {#snippet first()}
+ <WorkspaceFileTreePanel
+ leadingRows={sourceWorkspaceLeadingRows}
+ entries={[]}
+ selectedFile={selectedSourceFile}
onSelect={openSourceTab}
- onClose={closeSourceTab}
/>
- <div class="relative min-h-0 flex-1">
- {#key activeSourceTab}
- {#if activeSourceTab === 'compose'}
- <div class="absolute inset-0 min-h-0 w-full min-w-0">
- <CodeEditor
- value={stackSource.composeContent}
- language="yaml"
- readOnly={true}
- fontSize="13px"
- fileId={`swarm-stack-source:${stackName}:compose.yaml`}
- />
- </div>
- {:else if stackSource.envContent?.trim()}
- <div class="absolute inset-0 min-h-0 w-full min-w-0">
- <CodeEditor
- value={stackSource.envContent}
- language="env"
- readOnly={true}
- fontSize="13px"
- fileId={`swarm-stack-source:${stackName}:.env`}
- />
- </div>
- {:else}
- <div class="flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground">
- No saved `.env` file was stored for this stack.
- </div>
- {/if}
- {/key}
+ {/snippet}
+
+ {#snippet second()}
+ <div class="flex h-full min-h-0 flex-1 flex-col">
+ <EditorTabStrip
+ tabs={sourceTabs}
+ activeKey={activeSourceTab}
+ onSelect={openSourceTab}
+ onClose={closeSourceTab}
+ />
+ <div class="relative min-h-0 flex-1">
+ {#key activeSourceTab}
+ {#if activeSourceTab === 'compose'}
+ <div class="absolute inset-0 min-h-0 w-full min-w-0">
+ <CodeEditor
+ value={stackSource.composeContent}
+ language="yaml"
+ readOnly={true}
+ fontSize="13px"
+ fileId={`swarm-stack-source:${stackName}:compose.yaml`}
+ />
+ </div>
+ {:else if stackSource.envContent?.trim()}
+ <div class="absolute inset-0 min-h-0 w-full min-w-0">
+ <CodeEditor
+ value={stackSource.envContent}
+ language="env"
+ readOnly={true}
+ fontSize="13px"
+ fileId={`swarm-stack-source:${stackName}:.env`}
+ />
+ </div>
+ {:else}
+ <div class="flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground">
+ No saved `.env` file was stored for this stack.
+ </div>
+ {/if}
+ {/key}
+ </div>
</div>
- </div>
- {/snippet}
- </ResizableSplit>
+ {/snippet}
+ </ResizableSplit>
+ {/key}
</div>
{:else if sourceState === 'loading'}
<Card.Root variant="subtle">
diff --git a/frontend/src/routes/(app)/swarm/tasks/+page.ts b/frontend/src/routes/(app)/swarm/tasks/+page.ts
index a1d76a8b6..2a1852b54 100644
--- a/frontend/src/routes/(app)/swarm/tasks/+page.ts
+++ b/frontend/src/routes/(app)/swarm/tasks/+page.ts
@@ -21,7 +21,9 @@ export const load: PageLoad = async ({ url }) => {
requestOptions.search = searchParam;
}
- const tasks = nodeId ? await swarmService.getNodeTasks(nodeId, requestOptions) : await swarmService.getTasks(requestOptions);
+ let tasks;
+ if (nodeId) tasks = await swarmService.getNodeTasks(nodeId, requestOptions);
+ else tasks = await swarmService.getTasks(requestOptions);
return {
tasks,
diff --git a/frontend/src/routes/(app)/updates/+page.svelte b/frontend/src/routes/(app)/updates/+page.svelte
index 786b68e10..d5c7434de 100644
--- a/frontend/src/routes/(app)/updates/+page.svelte
+++ b/frontend/src/routes/(app)/updates/+page.svelte
@@ -110,12 +110,15 @@
const excludedContainers = $derived(settingsQuery.data?.autoUpdateExcludedContainers ?? '');
- const projectUpdateDetailsQuery = createQuery<Record<string, ImageUpdateInfoDto>>(() => ({
- queryKey: ['updates', 'projects', 'details', envId, projectUpdatedImageRefs],
- queryFn: () =>
- projectUpdatedImageRefs.length > 0 ? imageService.getUpdateInfoByRefs(projectUpdatedImageRefs) : Promise.resolve({}),
- enabled: projectUpdatedImageRefs.length > 0
- }));
+ const projectUpdateDetailsQuery = createQuery<Record<string, ImageUpdateInfoDto>>(() => {
+ const environmentId = envId;
+ const imageRefs = projectUpdatedImageRefs;
+ return {
+ queryKey: ['updates', 'projects', 'details', environmentId, imageRefs],
+ queryFn: () => imageService.getUpdateInfoByRefs(imageRefs),
+ enabled: imageRefs.length > 0
+ };
+ });
const checkUpdatesMutation = createMutation(() => ({
mutationKey: ['updates', 'check-all', envId],
diff --git a/frontend/src/routes/(app)/updates/+page.ts b/frontend/src/routes/(app)/updates/+page.ts
index f12c697eb..6606c4d28 100644
--- a/frontend/src/routes/(app)/updates/+page.ts
+++ b/frontend/src/routes/(app)/updates/+page.ts
@@ -34,16 +34,16 @@ export const load: PageLoad = async ({ parent }) => {
const operationResult = await tryCatch(
(async () =>
Promise.all([
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.containers.list(envId, containerRequestOptions),
queryFn: () => containerService.getContainersForEnvironment(envId, containerRequestOptions)
}),
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.projects.list(envId, projectRequestOptions),
queryFn: () => projectService.getProjectsForEnvironment(envId, projectRequestOptions)
}),
// `autoUpdateExcludedContainers` drives the ignored state on container rows.
- queryClient.fetchQuery({
+ queryClient.query({
queryKey: queryKeys.settings.byEnvironment(envId),
queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
})
diff --git a/frontend/src/routes/(app)/volumes/+page.svelte b/frontend/src/routes/(app)/volumes/+page.svelte
index 7ed8e1e62..1c1aa86b5 100644
--- a/frontend/src/routes/(app)/volumes/+page.svelte
+++ b/frontend/src/routes/(app)/volumes/+page.svelte
@@ -11,33 +11,35 @@
import { hasPermission } from '#lib/utils/auth.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { untrack } from 'svelte';
+ import { useEnvironmentRefresh } from '#lib/hooks/use-environment-refresh.svelte.js';
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '#lib/layouts/index.js';
- import { createMutation, createQuery, useQueryClient, keepPreviousData } from '@tanstack/svelte-query';
+ import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
let { data } = $props();
const queryClient = useQueryClient();
- const pageState = new ResourceListPageState(
- untrack(() => data.volumes),
- untrack(() => data.volumeRequestOptions)
- );
- let previousEnvId = untrack(() => pageState.envId);
- let displayedEnvId = $state<string | null>(untrack(() => (data.envId === pageState.envId ? data.envId : null)));
- const resourcesReady = $derived(displayedEnvId === pageState.envId);
+ const pageState = new ResourceListPageState(untrack(() => data.volumeRequestOptions));
const countsFallback: VolumeUsageCounts = { inuse: 0, unused: 0, total: 0 };
const volumesQuery = createQuery(() => {
const queryEnvId = pageState.envId;
+ const options = pageState.requestOptions;
return {
- queryKey: queryKeys.volumes.table(queryEnvId, pageState.requestOptions),
- queryFn: () => volumeService.getVolumesForEnvironment(queryEnvId, pageState.requestOptions),
- placeholderData: keepPreviousData,
+ queryKey: queryKeys.volumes.table(queryEnvId, options),
+ queryFn: () => volumeService.getVolumesForEnvironment(queryEnvId, options),
+ placeholderData: (previous, query) => {
+ if (query?.queryKey[1] === queryEnvId) return previous;
+ return undefined;
+ },
initialData: data.envId === queryEnvId ? data.volumes : undefined,
select: (value) => ({ envId: queryEnvId, value })
};
});
+ const resourcesReady = $derived(volumesQuery.data?.envId === pageState.envId);
+ const volumes = $derived(volumesQuery.data?.value ?? data.volumes);
+
const createVolumeMutation = createMutation(() => ({
mutationKey: ['volumes', 'create', pageState.envId],
mutationFn: ({ options, requestedEnvId }: { options: VolumeCreateRequest; requestedEnvId: string }) =>
@@ -59,17 +61,7 @@
}
}));
- $effect(() => {
- if (volumesQuery.data?.envId === pageState.envId) {
- pageState.items = volumesQuery.data.value;
- displayedEnvId = pageState.envId;
- }
- });
-
- $effect(() => {
- if (pageState.envId === previousEnvId) return;
- previousEnvId = pageState.envId;
- displayedEnvId = null;
+ useEnvironmentRefresh(() => {
pageState.selectedIds = [];
pageState.isCreateDialogOpen = false;
});
@@ -80,15 +72,10 @@
async function loadVolumes(options = pageState.requestOptions, requestedEnvId = pageState.envId) {
pageState.requestOptions = options;
- const next = await queryClient.fetchQuery({
+ await queryClient.query({
queryKey: queryKeys.volumes.table(requestedEnvId, options),
queryFn: () => volumeService.getVolumesForEnvironment(requestedEnvId, options)
});
- if (requestedEnvId !== pageState.envId) {
- return;
- }
- pageState.items = next;
- displayedEnvId = requestedEnvId;
}
async function refresh() {
@@ -96,7 +83,10 @@
}
const isRefreshing = $derived(volumesQuery.isFetching && !volumesQuery.isPending);
- const volumeUsageCounts = $derived(resourcesReady ? (pageState.items.counts ?? countsFallback) : countsFallback);
+ const volumeUsageCounts = $derived.by(() => {
+ if (resourcesReady) return volumes.counts ?? countsFallback;
+ return countsFallback;
+ });
const canCreateVolume = $derived(hasPermission('volumes:create', pageState.envId));
@@ -142,12 +132,17 @@
<ResourcePageLayout title={m.resource_volumes_cap()} subtitle={m.volumes_subtitle()} {actionButtons} {statCards}>
{#snippet mainContent()}
{#if resourcesReady}
- <VolumeTable
- bind:volumes={pageState.items}
- bind:selectedIds={pageState.selectedIds}
- bind:requestOptions={pageState.requestOptions}
- onRefreshData={loadVolumes}
- />
+ {#key pageState.envId}
+ <VolumeTable
+ bind:volumes={
+ () => volumes,
+ (value) => queryClient.setQueryData(queryKeys.volumes.table(pageState.envId, pageState.requestOptions), value)
+ }
+ bind:selectedIds={pageState.selectedIds}
+ bind:requestOptions={pageState.requestOptions}
+ onRefreshData={loadVolumes}
+ />
+ {/key}
{/if}
{/snippet}
diff --git a/frontend/src/routes/(app)/volumes/+page.ts b/frontend/src/routes/(app)/volumes/+page.ts
index 7ed3a4ca8..4c51b3237 100644
--- a/frontend/src/routes/(app)/volumes/+page.ts
+++ b/frontend/src/routes/(app)/volumes/+page.ts
@@ -25,7 +25,7 @@ export const load: PageLoad = async ({ parent }) => {
);
// Single API call - counts are included in the response
- const volumes = await queryClient.fetchQuery({
+ const volumes = await queryClient.query({
queryKey: queryKeys.volumes.table(envId, volumeRequestOptions),
queryFn: () => volumeService.getVolumesForEnvironment(envId, volumeRequestOptions)
});
diff --git a/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte b/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte
index f1e7f2bc0..ff6ad1547 100644
--- a/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte
+++ b/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte
@@ -14,7 +14,8 @@
FileTextIcon,
AlertIcon
} from '#lib/icons/index.js';
- import { goto } from '$app/navigation';
+ import { afterNavigate, goto } from '$app/navigation';
+ import { onMount, tick } from 'svelte';
import { Badge } from '#lib/components/ui/badge/index.js';
import { formatDateTimeShort, truncateString } from '#lib/utils/formatting.js';
import { openConfirmDialog } from '#lib/components/confirm-dialog//index.js';
@@ -114,16 +115,30 @@
let workspaceTreePaneWidth = $state(420);
type VolumeWorkspaceUIPrefs = { selectedFile: string; openTabs: string[] };
let workspacePrefs: PersistedState<VolumeWorkspaceUIPrefs> | null = null;
- let lastWorkspacePrefsKey = $state('');
+ let lastWorkspacePrefsKey = '';
let showWorkspaceRestore = $state(false);
let workspaceRestorePath = $state('');
let workspaceBackups = $state<BackupEntry[]>([]);
let selectedWorkspaceBackupId = $state('');
let loadingWorkspaceBackups = $state(false);
- let checkingWorkspaceBackup = $state(false);
- let workspaceBackupHasPath = $state<boolean | null>(null);
- let lastWorkspaceBackupCheck = '';
+ const workspaceBackupPathQuery = createQuery(() => {
+ const environmentId = currentEnvId;
+ const volumeName = volume.name;
+ const backupId = selectedWorkspaceBackupId;
+ const path = workspaceRestorePath;
+ return {
+ queryKey: queryKeys.volumes.backupHasPath(environmentId, volumeName, backupId, path),
+ queryFn: () => volumeBackupService.backupHasPath(backupId, `/${path}`),
+ enabled: showWorkspaceRestore && !!backupId && !!path && canReadVolume && canBackupVolume,
+ retry: false
+ };
+ });
+ const checkingWorkspaceBackup = $derived(workspaceBackupPathQuery.isFetching);
+ const workspaceBackupHasPath = $derived.by(() => {
+ if (workspaceBackupPathQuery.isFetching || workspaceBackupPathQuery.error) return null;
+ return workspaceBackupPathQuery.data ?? null;
+ });
const workspaceQuery = createQuery(() => ({
queryKey: queryKeys.volumes.workspace(currentEnvId, volume.name),
@@ -206,11 +221,12 @@
activeWorkspaceTab.startsWith('file:') ? workspaceFileMetadata[activeWorkspaceTab.slice(5)] : undefined
);
- $effect(() => {
+ afterNavigate(() => {
+ initializeVolumePreferences();
if (selectedTab === 'workspace') workspaceRequested = true;
});
- $effect(() => {
+ function initializeVolumePreferences() {
const key = `arcane.volume.workspace.ui:${currentEnvId}:${volume.name}`;
if (lastWorkspacePrefsKey === key) return;
lastWorkspacePrefsKey = key;
@@ -224,7 +240,8 @@
);
selectedWorkspaceFile = workspacePrefs.current.selectedFile;
openWorkspaceTabs = workspacePrefs.current.openTabs;
- });
+ loadSelectedWorkspaceFile();
+ }
function persistWorkspacePrefs() {
if (!workspacePrefs) return;
@@ -243,6 +260,7 @@
selectedWorkspaceFile = remaining[Math.min(Math.max(index - 1, 0), remaining.length - 1)] ?? '';
}
persistWorkspacePrefs();
+ loadSelectedWorkspaceFile();
}
function openWorkspaceFile(key: string) {
@@ -252,11 +270,13 @@
if (entry.isDirectory) {
selectedWorkspaceFile = key;
persistWorkspacePrefs();
+ loadSelectedWorkspaceFile();
return;
}
if (!openWorkspaceTabs.includes(key)) openWorkspaceTabs = [...openWorkspaceTabs, key];
selectedWorkspaceFile = key;
persistWorkspacePrefs();
+ loadSelectedWorkspaceFile();
}
async function loadWorkspaceFile(relativePath: string) {
@@ -297,11 +317,18 @@
workspaceFileLoading = { ...workspaceFileLoading, [relativePath]: true };
workspaceFileLoadErrors = removeWorkspaceFileRecord(workspaceFileLoadErrors, relativePath);
const loadVersion = workspaceFileLoadVersions.get(relativePath) ?? 0;
+ const requestedEnvId = currentEnvId;
+ const requestedVolumeName = volume.name;
try {
const operationResult = await tryCatch(
(async () => {
- const file = await volumeWorkspaceService.getWorkspaceFile(volume.name, relativePath, currentEnvId);
- if (loadVersion !== (workspaceFileLoadVersions.get(relativePath) ?? 0)) return;
+ const file = await volumeWorkspaceService.getWorkspaceFile(requestedVolumeName, relativePath, requestedEnvId);
+ if (
+ requestedEnvId !== currentEnvId ||
+ requestedVolumeName !== volume.name ||
+ loadVersion !== (workspaceFileLoadVersions.get(relativePath) ?? 0)
+ )
+ return;
workspaceFileMetadata = { ...workspaceFileMetadata, [relativePath]: file };
if (file.editable) {
const content = file.content ?? '';
@@ -314,23 +341,66 @@
);
if (operationResult.error !== null) {
const error = operationResult.error;
- if (loadVersion !== (workspaceFileLoadVersions.get(relativePath) ?? 0)) return;
+ if (
+ requestedEnvId !== currentEnvId ||
+ requestedVolumeName !== volume.name ||
+ loadVersion !== (workspaceFileLoadVersions.get(relativePath) ?? 0)
+ )
+ return;
workspaceFileLoadErrors = {
...workspaceFileLoadErrors,
[relativePath]: error instanceof Error ? error.message : String(error)
};
}
} finally {
- if (loadVersion === (workspaceFileLoadVersions.get(relativePath) ?? 0)) {
+ if (
+ requestedEnvId === currentEnvId &&
+ requestedVolumeName === volume.name &&
+ loadVersion === (workspaceFileLoadVersions.get(relativePath) ?? 0)
+ ) {
workspaceFileLoading = removeWorkspaceFileRecord(workspaceFileLoading, relativePath);
}
}
}
- $effect(() => {
+ function loadSelectedWorkspaceFile() {
if (!activeWorkspaceTab.startsWith('file:')) return;
const relativePath = activeWorkspaceTab.slice(5);
if (!workspaceFileMetadata[relativePath] && !workspaceFileLoadErrors[relativePath]) void loadWorkspaceFile(relativePath);
+ }
+
+ onMount(() => {
+ let active = true;
+ const cache = queryClient.getQueryCache();
+ const loadAfterUpdate = async () => {
+ await tick();
+ if (!active) return;
+ initializeVolumePreferences();
+ loadSelectedWorkspaceFile();
+ };
+ const unsubscribe = cache.subscribe((event) => {
+ const backupPath = cache.find({
+ queryKey: queryKeys.volumes.backupHasPath(currentEnvId, volume.name, selectedWorkspaceBackupId, workspaceRestorePath),
+ exact: true
+ });
+ if (event.query === backupPath && (event.type === 'updated' || event.type === 'observerResultsUpdated')) {
+ notifyWorkspaceBackupError(event.query.state.error);
+ }
+ if (event.type !== 'updated' || event.action.type !== 'success') return;
+ if (event.query === cache.find({ queryKey: queryKeys.volumes.workspace(currentEnvId, volume.name), exact: true })) {
+ void loadAfterUpdate();
+ }
+ });
+ const unsubscribeEnvironment = environmentStore.subscribeSelected(() => {
+ void loadAfterUpdate();
+ });
+ void loadAfterUpdate();
+ notifyWorkspaceBackupError(workspaceBackupPathQuery.error);
+ return () => {
+ active = false;
+ unsubscribe();
+ unsubscribeEnvironment();
+ };
});
function createVolumeWorkspaceFile(parentPath: string, name: string) {
@@ -370,6 +440,7 @@
workspaceFileChanges = [...workspaceFileChanges, { operation: 'create_folder', relativePath }];
selectedWorkspaceFile = `file:${relativePath}`;
persistWorkspacePrefs();
+ loadSelectedWorkspaceFile();
}
function remapVolumeWorkspaceState(oldPath: string, newPath: string) {
@@ -385,6 +456,7 @@
const remappedSelection = remapSelectedWorkspaceFileKey(selectedWorkspaceFile, oldPath, newPath);
if (remappedSelection) selectedWorkspaceFile = remappedSelection;
persistWorkspacePrefs();
+ loadSelectedWorkspaceFile();
}
function renameVolumeWorkspaceFile(relativePath: string, newName: string) {
@@ -427,6 +499,7 @@
openWorkspaceTabs = openWorkspaceTabs.filter((tab) => !isWorkspaceFileSelectionUnder(tab, relativePath));
if (isWorkspaceFileSelectionUnder(selectedWorkspaceFile, relativePath)) selectedWorkspaceFile = openWorkspaceTabs[0] ?? '';
persistWorkspacePrefs();
+ loadSelectedWorkspaceFile();
}
function deleteVolumeWorkspaceFile(relativePath: string) {
@@ -572,17 +645,18 @@
}
async function openWorkspaceRestoreDialog(relativePath: string) {
+ const environmentId = currentEnvId;
+ const name = volume.name;
workspaceRestorePath = relativePath;
workspaceBackups = [];
selectedWorkspaceBackupId = '';
- workspaceBackupHasPath = null;
- lastWorkspaceBackupCheck = '';
showWorkspaceRestore = true;
loadingWorkspaceBackups = true;
try {
const operationResult = await tryCatch(
(async () => {
- const response = await volumeBackupService.listBackups(volume.name, { pagination: { page: 1, limit: 100 } });
+ const response = await volumeBackupService.listBackups(name, { pagination: { page: 1, limit: 100 } });
+ if (environmentId !== currentEnvId || name !== volume.name || workspaceRestorePath !== relativePath) return;
workspaceBackups = response.data;
selectedWorkspaceBackupId = response.data[0]?.id ?? '';
})()
@@ -597,33 +671,14 @@
}
}
- async function checkWorkspaceBackupPath(backupId: string, relativePath: string) {
- const key = `${backupId}:${relativePath}`;
- if (!backupId || !relativePath || key === lastWorkspaceBackupCheck) return;
- lastWorkspaceBackupCheck = key;
- checkingWorkspaceBackup = true;
- workspaceBackupHasPath = null;
- try {
- const operationResult = await tryCatch((async () => volumeBackupService.backupHasPath(backupId, `/${relativePath}`))());
- if (operationResult.error !== null) {
- const error = operationResult.error;
-
- workspaceBackupHasPath = null;
- toast.error(error instanceof Error ? error.message : m.common_failed());
- } else {
- workspaceBackupHasPath = operationResult.data;
- }
- } finally {
- checkingWorkspaceBackup = false;
- }
+ let lastWorkspaceBackupError: unknown;
+ function notifyWorkspaceBackupError(error: unknown) {
+ if (!showWorkspaceRestore || !error || error === lastWorkspaceBackupError) return;
+ lastWorkspaceBackupError = error;
+ if (error instanceof Error) toast.error(error.message);
+ else toast.error(m.common_failed());
}
- $effect(() => {
- if (showWorkspaceRestore && selectedWorkspaceBackupId && workspaceRestorePath) {
- void checkWorkspaceBackupPath(selectedWorkspaceBackupId, workspaceRestorePath);
- }
- });
-
function stageWorkspaceRestore() {
if (!workspaceRestorePath || !selectedWorkspaceBackupId || workspaceBackupHasPath !== true) return;
workspaceFileChanges = [
@@ -712,6 +767,7 @@
});
function onTabChange(value: string) {
+ if (value === 'workspace') workspaceRequested = true;
urlTab.select(value);
}
</script>
@@ -852,8 +908,6 @@
value={selectedWorkspaceBackupId}
onValueChange={(value) => {
selectedWorkspaceBackupId = value;
- workspaceBackupHasPath = null;
- lastWorkspaceBackupCheck = '';
}}
>
<Select.Trigger id="workspace-restore-backup" class="h-10 w-full overflow-hidden">
@@ -904,40 +958,42 @@
</Alert.Root>
{/if}
<div class="flex h-[calc(100vh-15rem)] min-h-[32rem] flex-col overflow-hidden rounded-lg border border-border bg-card">
- <ResizableSplit
- class="h-full min-h-0 flex-1"
- {...composeTreeSplitProps}
- bind:size={workspaceTreePaneWidth}
- ariaLabel={m.compose_editor_resize_files_panel()}
- persistKey={`arcane.volume.workspace.split:${currentEnvId}:${volume.name}`}
- >
- {#snippet first()}
- {@render volumeWorkspaceTree()}
- {/snippet}
+ {#key `arcane.volume.workspace.split:${currentEnvId}:${volume.name}`}
+ <ResizableSplit
+ class="h-full min-h-0 flex-1"
+ {...composeTreeSplitProps}
+ bind:size={workspaceTreePaneWidth}
+ ariaLabel={m.compose_editor_resize_files_panel()}
+ persistKey={`arcane.volume.workspace.split:${currentEnvId}:${volume.name}`}
+ >
+ {#snippet first()}
+ {@render volumeWorkspaceTree()}
+ {/snippet}
- {#snippet second()}
- <div class="flex h-full min-h-0 flex-1 flex-col">
- {#if workspaceTabs.length > 0}
- <EditorTabStrip
- tabs={workspaceTabs}
- activeKey={activeWorkspaceTab}
- onSelect={openWorkspaceFile}
- onClose={closeWorkspaceTab}
- />
- {/if}
- <div class="flex min-h-0 flex-1 flex-col">
- {#if !activeWorkspaceTab}
- <div class="flex h-full items-center justify-center px-4 text-sm text-muted-foreground">
- {m.volumes_workspace_select_file()}
- </div>
- {:else}
- {@const relativePath = activeWorkspaceTab.slice(5)}
- {@render volumeWorkspaceFileEditor(volume, relativePath)}
+ {#snippet second()}
+ <div class="flex h-full min-h-0 flex-1 flex-col">
+ {#if workspaceTabs.length > 0}
+ <EditorTabStrip
+ tabs={workspaceTabs}
+ activeKey={activeWorkspaceTab}
+ onSelect={openWorkspaceFile}
+ onClose={closeWorkspaceTab}
+ />
{/if}
+ <div class="flex min-h-0 flex-1 flex-col">
+ {#if !activeWorkspaceTab}
+ <div class="flex h-full items-center justify-center px-4 text-sm text-muted-foreground">
+ {m.volumes_workspace_select_file()}
+ </div>
+ {:else}
+ {@const relativePath = activeWorkspaceTab.slice(5)}
+ {@render volumeWorkspaceFileEditor(volume, relativePath)}
+ {/if}
+ </div>
</div>
- </div>
- {/snippet}
- </ResizableSplit>
+ {/snippet}
+ </ResizableSplit>
+ {/key}
</div>
</div>
{/if}
@@ -1018,7 +1074,9 @@
{:else if tab === 'workspace'}
{@render volumeWorkspace(volume)}
{:else if tab === 'backups'}
- <BackupList volumeName={volume.name} {hasWorkspaceChanges} onWorkspaceRestored={refreshRestoredVolumeWorkspace} />
+ {#key `${currentEnvId}:${volume.name}`}
+ <BackupList volumeName={volume.name} {hasWorkspaceChanges} onWorkspaceRestored={refreshRestoredVolumeWorkspace} />
+ {/key}
{/if}
</div>
{/snippet}
diff --git a/frontend/src/routes/(app)/volumes/[volumeName]/+page.ts b/frontend/src/routes/(app)/volumes/[volumeName]/+page.ts
index 4aac847e0..337b423ad 100644
--- a/frontend/src/routes/(app)/volumes/[volumeName]/+page.ts
+++ b/frontend/src/routes/(app)/volumes/[volumeName]/+page.ts
@@ -14,7 +14,7 @@ export const load: PageLoad = async ({ params, parent }) => {
const operationResult = await tryCatch(
(async () => {
- const volume = await queryClient.fetchQuery({
+ const volume = await queryClient.query({
queryKey: queryKeys.volumes.detail(envId, volumeName),
queryFn: () => volumeService.getVolumeForEnvironment(envId, volumeName)
});
@@ -25,7 +25,7 @@ export const load: PageLoad = async ({ params, parent }) => {
volume.containers.map(async (id: string) => {
const operationResult = await tryCatch(
(async () => {
- const c = await queryClient.fetchQuery({
+ const c = await queryClient.query({
queryKey: queryKeys.containers.detail(envId, id),
queryFn: () => containerService.getContainerForEnvironment(envId, id)
});
diff --git a/frontend/src/routes/(app)/volumes/components/rename-volume-dialog.svelte b/frontend/src/routes/(app)/volumes/components/rename-volume-dialog.svelte
index 017b6e77c..036c046bb 100644
--- a/frontend/src/routes/(app)/volumes/components/rename-volume-dialog.svelte
+++ b/frontend/src/routes/(app)/volumes/components/rename-volume-dialog.svelte
@@ -1,4 +1,5 @@
<script lang="ts">
+ import { untrack } from 'svelte';
import * as Alert from '#lib/components/ui/alert/index.js';
import TextInputWithLabel from '#lib/components/form/text-input-with-label.svelte';
import SheetFooterActions from '#lib/components/sheets/sheet-footer-actions.svelte';
@@ -20,19 +21,13 @@
onSubmit: (newName: string) => void;
} = $props();
- let newName = $state('');
+ let newName = $state(untrack(() => volume?.name ?? ''));
let error = $state<string | null>(null);
const isManaged = $derived(Boolean(getManagedByLabel(volume?.labels)));
const normalizedName = $derived(newName.trim());
const canRename = $derived(Boolean(volume && normalizedName && normalizedName !== volume.name));
- $effect(() => {
- if (!open) return;
- newName = volume?.name ?? '';
- error = null;
- });
-
function handleOpenChange(isOpen: boolean) {
if (!isOpen) error = null;
}
diff --git a/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte b/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
index 2b6fd4bbb..735d8b9bc 100644
--- a/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
+++ b/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
@@ -8,7 +8,7 @@
import { volumeService } from '#lib/services/volume-service.js';
import type { BackupEntry, CreateVolumeBackupRequest, VolumeBackupPolicy } from '#lib/types/shared.js';
import type { S3Destination } from '#lib/types/s3-destination.js';
- import { onMount } from 'svelte';
+ import { onMount, onDestroy } from 'svelte';
import { useBackupActivity } from '#lib/hooks/use-backup-activity.svelte.js';
import { activityStore } from '#lib/stores/activity.store.svelte.js';
import {
@@ -95,6 +95,7 @@
let backupPolicies = $state<VolumeBackupPolicy[]>([]);
let s3Destinations = $state<S3Destination[]>([]);
let showBackupPolicy = $state(false);
+ let policySession = $state(0);
let editingBackupPolicyId = $state<string | undefined>();
let showS3DestinationDialog = $state(false);
let onDemandDestination = $state<'s3' | 'local_s3'>('s3');
@@ -117,23 +118,30 @@
let backupFilesSearch = $state('');
let selectedPaths = $state<string[]>([]);
let selectAllBackupFiles = $state(false);
- async function loadData(options: SearchPaginationSortRequest): Promise<VolumeBackupListResponse> {
- const operationResult = await tryCatch(
- (async () => {
- const result = await volumeBackupService.listBackups(volumeName, options);
- backupsPaginated = result;
- backupWarnings = result.warnings ?? [];
- return result;
- })()
- );
- if (operationResult.error !== null) {
- const error = operationResult.error;
+ let backupLoadVersion = 0;
+ let active = true;
+ onDestroy(() => {
+ active = false;
+ backupLoadVersion += 1;
+ });
- toast.error(error instanceof Error ? error.message : m.volumes_backup_load_failed());
+ async function loadData(options: SearchPaginationSortRequest): Promise<VolumeBackupListResponse> {
+ await environmentStore.ready;
+ if (!active) return backupsPaginated;
+ const environmentId = currentEnvId;
+ const name = volumeName;
+ const version = ++backupLoadVersion;
+ const result = await tryCatch(volumeBackupService.listBackups(name, options, environmentId));
+ if (version !== backupLoadVersion || environmentId !== currentEnvId || name !== volumeName) return backupsPaginated;
+ if (result.error !== null) {
+ let message: string = m.volumes_backup_load_failed();
+ if (result.error instanceof Error) message = result.error.message;
+ toast.error(message);
return backupsPaginated;
- } else {
- return operationResult.data;
}
+ backupsPaginated = result.data;
+ backupWarnings = result.data.warnings ?? [];
+ return result.data;
}
const backupActivity = useBackupActivity(
@@ -177,14 +185,20 @@
async function handleCreate(request?: CreateVolumeBackupRequest) {
if (creating || backupActivity.activeIds.length) return false;
creating = true;
+ const environmentId = currentEnvId;
+ const name = volumeName;
+ const tracksActivities = canReadActivities;
try {
const operationResult = await tryCatch(
(async () => {
- const result = await volumeBackupService.createBackup(volumeName, request);
+ const result = await volumeBackupService.createBackup(name, request);
+ if (!active || environmentId !== currentEnvId || name !== volumeName) return false;
showS3DestinationDialog = false;
onDemandS3DestinationId = '';
creating = false;
- backupActivity.accepted(canReadActivities ? extractActivityId(result) : result.id);
+ let activityId: string | undefined = result.id;
+ if (tracksActivities) activityId = extractActivityId(result);
+ backupActivity.accepted(activityId);
toast.success(
m.backups_started(),
canReadActivities ? activityToastOptions(extractActivityId(result), false) : undefined
@@ -296,7 +310,9 @@
function openRestoreFilesDialog(backup: BackupEntry) {
restoreTarget = backup;
- // The picker clears its selection and search when it sees the new provider.
+ selectedPaths = [];
+ selectAllBackupFiles = false;
+ backupFilesSearch = '';
backupFileProvider = {
browse: (request) => volumeBackupService.browseBackupFiles(backup.id, request)
};
@@ -304,6 +320,7 @@
}
async function handleRestore(backup: BackupEntry) {
+ const name = volumeName;
// Check if volume is in use
let usageWarning = '';
const operationResult = await tryCatch(
@@ -330,7 +347,7 @@
action: async () => {
const operationResult = await tryCatch(
(async () => {
- const result = await volumeBackupService.restoreBackup(volumeName, backup.id);
+ const result = await volumeBackupService.restoreBackup(name, backup.id);
await onWorkspaceRestored?.();
toast.success(m.volumes_backup_restore_success(), activityToastOptions(extractActivityId(result)));
await loadData(requestOptions);
@@ -350,12 +367,14 @@
if (!restoreTarget) return;
if (!selectAllBackupFiles && !selectedPaths.length) return;
+ const name = volumeName;
+ const backupId = restoreTarget.id;
const selection = { paths: [...selectedPaths], selectAll: selectAllBackupFiles };
restoringFiles = true;
try {
const operationResult = await tryCatch(
(async () => {
- const result = await volumeBackupService.restoreBackupFiles(volumeName, restoreTarget.id, {
+ const result = await volumeBackupService.restoreBackupFiles(name, backupId, {
...selection,
search: selection.selectAll ? backupFilesSearch.trim() : undefined
});
@@ -379,13 +398,17 @@
}
onMount(async () => {
+ await environmentStore.ready;
+ const environmentId = currentEnvId;
+ const name = volumeName;
const [collection, destinations] = await Promise.all([
- volumeBackupService.getPolicies(volumeName),
+ volumeBackupService.getPolicies(name),
canBackupVolume
? tryCatch(s3DestinationService.listAll()).then((result) => (result.error ? [] : result.data))
: Promise.resolve([]),
loadData(requestOptions)
]);
+ if (!active || environmentId !== currentEnvId || name !== volumeName) return;
backupPolicies = collection.policies;
s3Destinations = destinations;
});
@@ -514,6 +537,7 @@
customLabel={m.volume_backup_add_schedule()}
onclick={() => {
editingBackupPolicyId = undefined;
+ policySession += 1;
showBackupPolicy = true;
}}
size="sm"
@@ -638,6 +662,7 @@
onEdit={canBackupVolume
? () => {
editingBackupPolicyId = policy.id;
+ policySession += 1;
showBackupPolicy = true;
}
: undefined}
@@ -679,9 +704,6 @@
<ResponsiveDialog
bind:open={showRestoreFiles}
- onOpenChange={(open) => {
- if (!open) backupFileProvider = null;
- }}
title={m.volume_restore_files()}
description={m.volumes_backup_restore_desc()}
contentClass="sm:max-w-[640px]"
@@ -696,12 +718,14 @@
</Alert.Root>
{#if backupFileProvider}
- <BackupFilePicker
- provider={backupFileProvider}
- bind:selectedPaths
- bind:selectAll={selectAllBackupFiles}
- bind:search={backupFilesSearch}
- />
+ {#key backupFileProvider}
+ <BackupFilePicker
+ provider={backupFileProvider}
+ bind:selectedPaths
+ bind:selectAll={selectAllBackupFiles}
+ bind:search={backupFilesSearch}
+ />
+ {/key}
{/if}
<Alert.Root variant="warning" class="py-2 [&>svg]:top-2">
@@ -727,7 +751,6 @@
action="cancel"
onclick={() => {
showRestoreFiles = false;
- backupFileProvider = null;
}}
/>
{#if canBackupVolume}
@@ -775,21 +798,25 @@
{/snippet}
</ResponsiveDialog>
-<BackupPolicyDialog
- bind:open={showBackupPolicy}
- idPrefix="volume-backup-policy"
- policies={backupPolicies}
- policyId={editingBackupPolicyId}
- addTitle={m.volume_backup_add_schedule()}
- description={m.volume_backup_policy_description()}
- enabledDescription={m.volume_backup_policy_enabled_description()}
- defaultSchedule="0 0 2 * * *"
- showStopContainers
- updatePolicies={async (policies) => (await volumeBackupService.updatePolicies(volumeName, policies)).policies}
- messages={{
- saved: m.volume_backup_policy_saved(),
- saveFailed: m.volume_backup_policy_save_failed(),
- removed: m.volume_backup_schedule_removed()
- }}
- onSaved={(policies) => (backupPolicies = policies)}
-/>
+{#if policySession > 0}
+ {#key policySession}
+ <BackupPolicyDialog
+ bind:open={showBackupPolicy}
+ idPrefix="volume-backup-policy"
+ policies={backupPolicies}
+ policyId={editingBackupPolicyId}
+ addTitle={m.volume_backup_add_schedule()}
+ description={m.volume_backup_policy_description()}
+ enabledDescription={m.volume_backup_policy_enabled_description()}
+ defaultSchedule="0 0 2 * * *"
+ showStopContainers
+ updatePolicies={async (policies) => (await volumeBackupService.updatePolicies(volumeName, policies)).policies}
+ messages={{
+ saved: m.volume_backup_policy_saved(),
+ saveFailed: m.volume_backup_policy_save_failed(),
+ removed: m.volume_backup_schedule_removed()
+ }}
+ onSaved={(policies) => (backupPolicies = policies)}
+ />
+ {/key}
+{/if}
diff --git a/frontend/src/routes/(app)/volumes/volume-table.svelte b/frontend/src/routes/(app)/volumes/volume-table.svelte
index 0c7ed227a..524cedf0c 100644
--- a/frontend/src/routes/(app)/volumes/volume-table.svelte
+++ b/frontend/src/routes/(app)/volumes/volume-table.svelte
@@ -20,8 +20,9 @@
import { TrashIcon, InspectIcon, VolumesIcon, CalendarIcon, EditIcon } from '#lib/icons/index.js';
import { Spinner } from '#lib/components/ui/spinner/index.js';
import settingsStore from '#lib/stores/config-store.js';
- import { untrack } from 'svelte';
- import { SvelteMap } from 'svelte/reactivity';
+ import { onMount } from 'svelte';
+ import { createQuery, useQueryClient } from '@tanstack/svelte-query';
+ import { queryKeys } from '#lib/query/query-keys.js';
import type { ColumnVisibilityState } from '@tanstack/table-core';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { hasPermission } from '#lib/utils/auth.js';
@@ -48,6 +49,7 @@
});
let volumeToRename = $state<VolumeSummaryDto | null>(null);
let renameDialogOpen = $state(false);
+ let renameSession = $state(0);
let renameEnvironmentId = $state('0');
const currentEnvId = $derived(environmentStore.selected?.id || '0');
@@ -61,6 +63,7 @@
$userStore;
return hasPermission('volumes:rename', currentEnvId);
});
+ let tablePreferences = $state<{ persistCustomSettings(settings: Record<string, unknown>): void }>();
let customSettings = $state<Record<string, unknown>>({});
let showInternal = $derived.by(() => {
return (customSettings['showInternalVolumes'] as boolean) ?? false;
@@ -72,8 +75,8 @@
} else {
volumes = await volumeService.getVolumes(options);
}
- if (refreshSizes && tablePreferencesReady && columnVisibility['size'] !== false) {
- void loadVolumeSizes(currentEnvId);
+ if (refreshSizes && sizesEnabled) {
+ await sizesQuery.refetch({ cancelRefetch: false });
}
}
@@ -87,6 +90,7 @@
if (value === currentSetting && value === currentRequest) return;
customSettings = { ...customSettings, showInternalVolumes: value };
+ tablePreferences?.persistCustomSettings(customSettings);
const nextOptions: SearchPaginationSortRequest = {
...requestOptions,
includeInternal: value,
@@ -100,52 +104,52 @@
const isBackupVolumeName = (name?: string) => (name ?? '') === backupVolumeName;
const isBackupVolume = (item: VolumeSummaryDto) => isBackupVolumeName(item.name);
- // Lazy load volume sizes - this is a slow operation
- let sizesMap = new SvelteMap<string, VolumeSizeInfo>();
- let sizeLoadPromises = new SvelteMap<string, Promise<void>>();
- let sizesLoading = $state(false);
let columnVisibility = $state<ColumnVisibilityState>({});
let tablePreferencesReady = $state(false);
-
- function loadVolumeSizes(environmentId: string): Promise<void> {
- const existing = sizeLoadPromises.get(environmentId);
- if (existing) return existing;
-
- const request = (async () => {
- if (currentEnvId === environmentId) {
- sizesLoading = true;
+ const queryClient = useQueryClient();
+ const sizesEnabled = $derived.by(() => {
+ $userStore;
+ return (
+ tablePreferencesReady &&
+ !!environmentStore.selected?.id &&
+ columnVisibility['size'] !== false &&
+ hasPermission('volumes:read', currentEnvId)
+ );
+ });
+ const sizesQuery = createQuery(() => {
+ const environmentId = currentEnvId;
+ return {
+ queryKey: queryKeys.volumes.sizes(environmentId),
+ queryFn: () => volumeService.getVolumeSizes(environmentId),
+ enabled: sizesEnabled,
+ refetchOnWindowFocus: false,
+ retry: false
+ };
+ });
+ const sizesMap = $derived.by(() => {
+ const sizes = new Map<string, VolumeSizeInfo>();
+ if (!sizesEnabled) return sizes;
+ for (const size of sizesQuery.data ?? []) sizes.set(size.name, size);
+ return sizes;
+ });
+ const sizesLoading = $derived(sizesEnabled && sizesQuery.isFetching);
+
+ onMount(() => {
+ const cache = queryClient.getQueryCache();
+ return cache.subscribe((event) => {
+ if (event.type !== 'updated') return;
+ if (event.query !== cache.find({ queryKey: queryKeys.volumes.sizes(currentEnvId), exact: true })) return;
+ if (event.action.type === 'error') {
+ console.error('Failed to load volume sizes:', event.query.state.error);
+ return;
}
- try {
- const operationResult = await tryCatch(
- (async () => {
- const sizes = await volumeService.getVolumeSizes(environmentId);
- if (currentEnvId !== environmentId || columnVisibility['size'] === false) return;
-
- sizesMap.clear();
- for (const s of sizes) {
- sizesMap.set(s.name, s);
- }
-
- if (requestOptions?.sort?.column === 'size') {
- await refreshVolumes(requestOptions, false);
- }
- })()
- );
- if (operationResult.error !== null) {
- const error = operationResult.error;
- console.error('Failed to load volume sizes:', error);
- }
- } finally {
- sizeLoadPromises.delete(environmentId);
- if (currentEnvId === environmentId) {
- sizesLoading = false;
- }
+ if (event.action.type === 'success' && sizesEnabled && requestOptions?.sort?.column === 'size') {
+ void tryCatch(refreshVolumes(requestOptions, false)).then((result) => {
+ if (result.error) console.error('Failed to refresh volume size sorting:', result.error);
+ });
}
- })();
-
- sizeLoadPromises.set(environmentId, request);
- return request;
- }
+ });
+ });
async function handleRemoveVolumeConfirm(name: string) {
const safeName = name?.trim() || m.common_unknown();
@@ -178,6 +182,7 @@
function handleRenameVolume(item: VolumeSummaryDto) {
volumeToRename = item;
renameEnvironmentId = currentEnvId;
+ renameSession += 1;
renameDialogOpen = true;
}
@@ -192,7 +197,6 @@
onSuccess: async (data) => {
toast.success(m.volumes_rename_success({ oldName, newName }), activityToastOptions(extractActivityId(data)));
renameDialogOpen = false;
- volumeToRename = null;
if (renameEnvironmentId === currentEnvId) await refreshVolumes();
}
});
@@ -258,32 +262,6 @@
]);
let mobileFieldVisibility = $state<Record<string, boolean>>({});
-
- let persistedSettingsApplied = false;
- $effect(() => {
- if (!tablePreferencesReady) return;
-
- const environmentId = currentEnvId;
- const sizeVisible = columnVisibility['size'] !== false;
- if (!sizeVisible) {
- sizesMap.clear();
- sizesLoading = false;
- } else {
- untrack(() => {
- sizesMap.clear();
- void loadVolumeSizes(environmentId);
- });
- }
-
- if (!persistedSettingsApplied) {
- persistedSettingsApplied = true;
- const persistedInternal = (customSettings['showInternalVolumes'] as boolean) ?? false;
- const currentInternal = requestOptions?.includeInternal ?? false;
- if (persistedInternal !== currentInternal) {
- untrack(() => setShowInternal(persistedInternal));
- }
- }
- });
</script>
{#snippet NameCell({ item }: { item: VolumeSummaryDto })}
@@ -391,6 +369,7 @@
{/snippet}
<ArcaneTable
+ bind:this={tablePreferences}
persistKey="arcane-volumes-table"
items={volumes}
bind:requestOptions
@@ -398,7 +377,16 @@
bind:mobileFieldVisibility
bind:customSettings
bind:columnVisibility
- bind:preferencesReady={tablePreferencesReady}
+ bind:preferencesReady={
+ () => tablePreferencesReady,
+ (ready) => {
+ const wasReady = tablePreferencesReady;
+ tablePreferencesReady = ready;
+ if (!ready || wasReady) return;
+ const persistedInternal = (customSettings['showInternalVolumes'] as boolean) ?? false;
+ if (persistedInternal !== (requestOptions?.includeInternal ?? false)) setShowInternal(persistedInternal);
+ }
+ }
hiddenSortFallback={{ column: 'name', direction: 'asc' }}
{bulkActions}
onRefresh={async (options) => {
@@ -413,12 +401,16 @@
customViewOptions={CustomViewOptions}
/>
-<RenameVolumeDialog
- bind:open={renameDialogOpen}
- volume={volumeToRename}
- isLoading={isLoading.renaming}
- onSubmit={handleRenameSubmit}
-/>
+{#if renameSession > 0}
+ {#key renameSession}
+ <RenameVolumeDialog
+ bind:open={renameDialogOpen}
+ volume={volumeToRename}
+ isLoading={isLoading.renaming}
+ onSubmit={handleRenameSubmit}
+ />
+ {/key}
+{/if}
{#snippet CustomViewOptions()}
<DropdownMenu.CheckboxItem checked={showInternal} onCheckedChange={(v) => setShowInternal(!!v)}>
diff --git a/frontend/src/routes/(auth)/oidc/callback/+page.svelte b/frontend/src/routes/(auth)/oidc/callback/+page.svelte
index 406ae1901..3f871cc26 100644
--- a/frontend/src/routes/(auth)/oidc/callback/+page.svelte
+++ b/frontend/src/routes/(auth)/oidc/callback/+page.svelte
@@ -55,7 +55,7 @@
await refreshAll();
const operationResult = await tryCatch(
(async () => {
- const settings = await queryClient.fetchQuery({
+ const settings = await queryClient.query({
queryKey: queryKeys.settings.global(),
queryFn: () => settingsService.getSettings()
});
diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.ts
index 2cfe456a2..a8c6d2892 100644
--- a/frontend/src/routes/+layout.ts
+++ b/frontend/src/routes/+layout.ts
@@ -40,7 +40,7 @@ let authenticatedUserId: string | null | undefined;
export const load: LayoutLoad = async ({ url }) => {
const versionInformationRequest = versionService.getVersionInformation();
const autoLoginConfigRequest = browser
- ? queryClient.fetchQuery({
+ ? queryClient.query({
queryKey: queryKeys.auth.autoLoginConfig(),
queryFn: () => authService.getAutoLoginConfig()
})
@@ -55,7 +55,7 @@ export const load: LayoutLoad = async ({ url }) => {
settingsStore.autoLoginEnabled.set(true);
settingsStore.autoLoginEnabled.clearDisabledCache();
if (!user) {
- user = await queryClient.fetchQuery({
+ user = await queryClient.query({
queryKey: queryKeys.auth.autoLoginAttempt(),
queryFn: () => authService.attemptAutoLogin()
});
@@ -151,7 +151,7 @@ export const load: LayoutLoad = async ({ url }) => {
currentDigest: info.currentDigest,
displayVersion: info.displayVersion,
revision: info.revision,
- shortRevision: info.shortRevision || (info.revision?.slice(0, 8) ?? 'unknown'),
+ shortRevision: info.shortRevision || 'unknown',
goVersion: info.goVersion || 'unknown',
nodeVersion: info.nodeVersion || 'unknown',
svelteKitVersion: info.svelteKitVersion || 'unknown',
diff --git a/tests/spec/environment-settings.spec.ts b/tests/spec/environment-settings.spec.ts
index e0d4e2782..42ed726fd 100644
--- a/tests/spec/environment-settings.spec.ts
+++ b/tests/spec/environment-settings.spec.ts
@@ -33,13 +33,23 @@ async function createDirectEnvironmentViaUI(page: Page, environmentName: string)
const dialog = page.getByRole('dialog');
await dialog.getByLabel('Name', { exact: true }).fill(environmentName);
await dialog.getByLabel('Agent Address', { exact: true }).fill('localhost:3552');
+ const createResponsePromise = page.waitForResponse(
+ (response) =>
+ response.request().method() === 'POST' &&
+ new URL(response.url()).pathname === '/api/environments'
+ );
await page.getByRole('button', { name: 'Generate Agent Configuration', exact: true }).click();
+ const createResponse = await createResponsePromise;
+ expect(createResponse.ok(), await createResponse.text()).toBeTruthy();
+ const created: { data: { id: string } } = await createResponse.json();
+ expect(created.data.id).toBeTruthy();
await expect(
page.getByRole('heading', { name: 'Environment Created Successfully', exact: true })
).toBeVisible();
await page.getByRole('button', { name: 'Done', exact: true }).click();
await expect(page.getByRole('button', { name: environmentName, exact: true })).toBeVisible();
+ return created.data.id;
}
async function deleteEnvironmentViaUI(page: Page, environmentName: string) {
@@ -136,11 +146,10 @@ test.describe('Environment Settings UI', () => {
let environmentId = '';
try {
- await createDirectEnvironmentViaUI(page, envName);
+ environmentId = await createDirectEnvironmentViaUI(page, envName);
await page.getByRole('button', { name: envName, exact: true }).click();
await expect(page).toHaveURL(/\/environments\/[^/?]+\?tab=[a-z]+$/);
- environmentId = new URL(page.url()).pathname.split('/').pop()!;
await renameEnvironmentInHeader(page, updatedName);
await saveAndWaitForPut(page, `/api/environments/${environmentId}`);
diff --git a/tests/spec/images.spec.ts b/tests/spec/images.spec.ts
index ea43acd95..33f713dbf 100644
--- a/tests/spec/images.spec.ts
+++ b/tests/spec/images.spec.ts
@@ -380,12 +380,14 @@ test.describe('Images Page', () => {
}
);
- const imageRow = page
- .getByRole('row')
- .filter({
- has: page.getByRole('link', { name: removableImage.repo, exact: true })
- })
- .first();
+ // The API list and the UI use different sorting, so the selected image may be on another page.
+ const search = page.getByRole('textbox', { name: 'Search…', exact: true });
+ await search.fill(removableImage.id);
+ await search.press('Enter');
+
+ const imageRow = getImageRows(page).filter({
+ has: page.locator(`a[href="/images/${removableImage.id}"]`)
+ });
const menu = await openRowActionsMenu(page, imageRow);
await menu.getByRole('menuitem', { name: 'Remove', exact: true }).click();