Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: prevent stale data across environment switches (#3228)
Kyle Mendell787e5588fa58
diff --git a/backend/internal/services/image_update_service.go b/backend/internal/services/image_update_service.goindex 4ea810bcd..5abcd88a5 100644--- a/backend/internal/services/image_update_service.go+++ b/backend/internal/services/image_update_service.go@@ -1474,19 +1474,14 @@ func (s *ImageUpdateService) CleanupOrphanedRecords(ctx context.Context) error {}func (s *ImageUpdateService) GetUpdateSummary(ctx context.Context) (*imageupdate.Summary, error) {- dockerClient, err := s.dockerClientInternal(ctx)- if err != nil {- return nil, err+ if s == nil || s.dockerService == nil {+ return nil, errors.New("docker service unavailable")}- apiCtx, cancel := s.dockerAPIContextInternal(ctx)- defer cancel()-- dockerImagesResult, err := dockerClient.ImageList(apiCtx, client.ImageListOptions{})+ dockerImages, err := s.dockerService.listImagesInternal(ctx)if err != nil {- return nil, fmt.Errorf("failed to list Docker images: %w", err)+ return nil, err}- dockerImages := dockerImagesResult.ItemsliveImageIDs := make([]string, 0, len(dockerImages))for _, img := range dockerImages {diff --git a/frontend/src/lib/components/action-buttons.svelte b/frontend/src/lib/components/action-buttons.svelteindex aa39f85cb..bd58b1a34 100644--- a/frontend/src/lib/components/action-buttons.svelte+++ b/frontend/src/lib/components/action-buttons.svelte@@ -12,9 +12,10 @@import { m } from '$lib/paraglide/messages';import settingsStore from '$lib/stores/config-store';import { deployOptionsStore } from '$lib/stores/deploy-options.store.svelte';- import { containerService, type ContainerDetailsResponse } from '$lib/services/container-service';+ import { containerService } from '$lib/services/container-service';import { projectService, type DeployProjectOptions } from '$lib/services/project-service';import type { Project } from '$lib/types/swarm';+ import type { ContainerDetailsDto } from '$lib/types/docker';import { EllipsisIcon } from '$lib/icons';import { createMutation } from '@tanstack/svelte-query';import { hasPermission } from '$lib/utils/auth';@@ -150,7 +151,7 @@mutationFn: () =>tryCatch((type === 'container' ? containerService.redeployContainer(id) : projectService.redeployProject(id)) as Promise<- ContainerDetailsResponse | Project+ ContainerDetailsDto | Project>),onMutate: () => setLoading('redeploy', true),@@ -289,9 +290,9 @@result,message: m.common_action_failed_with_type({ action: m.common_redeploy(), type }),onSuccess: async (data) => {- const containerData = data as ContainerDetailsResponse;- if (type === 'container' && containerData?.data?.id) {- goto(`/containers/${containerData.data.id}`);+ const containerData = data as ContainerDetailsDto;+ if (type === 'container' && containerData?.id) {+ goto(`/containers/${containerData.id}`);} else if (type === 'container') {goto('/containers');} else {diff --git a/frontend/src/lib/services/container-service.ts b/frontend/src/lib/services/container-service.tsindex aa306220b..60efff17e 100644--- a/frontend/src/lib/services/container-service.ts+++ b/frontend/src/lib/services/container-service.ts@@ -19,11 +19,6 @@ export type ContainerListRequestOptions = SearchPaginationSortRequest & {groupByProject?: boolean;};-export interface ContainerDetailsResponse {- success: boolean;- data: ContainerDetailsDto;-}-class ContainerService extends BaseAPIService {private async resolveEnvironmentId(environmentId?: string): Promise<string> {return environmentId ?? (await environmentStore.getCurrentEnvironmentId());@@ -70,8 +65,8 @@ class ContainerService extends BaseAPIService {return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/start`));}- async createContainer(options: ContainerCreateRequest): Promise<any> {- const envId = await environmentStore.getCurrentEnvironmentId();+ async createContainer(options: ContainerCreateRequest, environmentId?: string): Promise<any> {+ const envId = await this.resolveEnvironmentId(environmentId);return this.handleResponse(this.api.post(`/environments/${envId}/containers`, options));}@@ -121,7 +116,7 @@ class ContainerService extends BaseAPIService {return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/update`));}- async redeployContainer(containerId: string): Promise<ContainerDetailsResponse> {+ async redeployContainer(containerId: string): Promise<ContainerDetailsDto> {const envId = await environmentStore.getCurrentEnvironmentId();return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/redeploy`));}diff --git a/frontend/src/lib/services/image-service.ts b/frontend/src/lib/services/image-service.tsindex eef830b30..957a13cdd 100644--- a/frontend/src/lib/services/image-service.ts+++ b/frontend/src/lib/services/image-service.ts@@ -147,8 +147,8 @@ class ImageService extends BaseAPIService {return this.handleResponse(this.api.delete(`/environments/${envId}/images/${imageId}`, { params: options }));}- async pruneImages(options: PruneImagesOptions): Promise<any> {- const envId = await environmentStore.getCurrentEnvironmentId();+ async pruneImages(options: PruneImagesOptions, environmentId?: string): Promise<any> {+ const envId = await this.resolveEnvironmentId(environmentId);return this.handleResponse(this.api.post(`/environments/${envId}/images/prune`, options));}@@ -157,8 +157,8 @@ class ImageService extends BaseAPIService {return this.handleResponse(this.api.post(`/environments/${envId}/image-updates/check/${imageId}`, {}));}- async checkAllImages(): Promise<Record<string, ImageUpdateInfoDto>> {- const envId = await environmentStore.getCurrentEnvironmentId();+ async checkAllImages(environmentId?: string): Promise<Record<string, ImageUpdateInfoDto>> {+ const envId = await this.resolveEnvironmentId(environmentId);return this.handleResponse(this.api.post(`/environments/${envId}/image-updates/check-all`, {}));}@@ -180,13 +180,13 @@ class ImageService extends BaseAPIService {);}- async runAutoUpdate(options?: AutoUpdateCheck): Promise<AutoUpdateResult> {- const envId = await environmentStore.getCurrentEnvironmentId();+ async runAutoUpdate(options?: AutoUpdateCheck, environmentId?: string): Promise<AutoUpdateResult> {+ const envId = await this.resolveEnvironmentId(environmentId);return this.handleResponse(this.api.post(`/environments/${envId}/updater/run`, options));}- async uploadImage(file: File): Promise<any> {- const envId = await environmentStore.getCurrentEnvironmentId();+ async uploadImage(file: File, environmentId?: string): Promise<any> {+ const envId = await this.resolveEnvironmentId(environmentId);const formData = new FormData();formData.append('file', file);return this.handleResponse(this.api.post(`/environments/${envId}/images/upload`, formData));diff --git a/frontend/src/lib/services/network-service.ts b/frontend/src/lib/services/network-service.tsindex 9cdfec142..05cec2a3d 100644--- a/frontend/src/lib/services/network-service.ts+++ b/frontend/src/lib/services/network-service.ts@@ -57,8 +57,8 @@ class NetworkService extends BaseAPIService {return this.handleResponse(this.api.get(`/environments/${envId}/networks/topology`));}- async createNetwork(name: string, options: NetworkCreateOptions): Promise<any> {- const envId = await environmentStore.getCurrentEnvironmentId();+ async createNetwork(name: string, options: NetworkCreateOptions, environmentId?: string): Promise<any> {+ const envId = await this.resolveEnvironmentId(environmentId);const request: NetworkCreateRequest = {name,optionsdiff --git a/frontend/src/lib/services/volume-service.ts b/frontend/src/lib/services/volume-service.tsindex fff5d622f..f9bf3c98e 100644--- a/frontend/src/lib/services/volume-service.ts+++ b/frontend/src/lib/services/volume-service.ts@@ -58,8 +58,8 @@ class VolumeService extends BaseAPIService {return res.data.data;}- async createVolume(options: VolumeCreateRequest): Promise<any> {- const envId = await environmentStore.getCurrentEnvironmentId();+ async createVolume(options: VolumeCreateRequest, environmentId?: string): Promise<any> {+ const envId = await this.resolveEnvironmentId(environmentId);return this.handleResponse(this.api.post(`/environments/${envId}/volumes`, options));}diff --git a/frontend/src/routes/(app)/containers/+page.svelte b/frontend/src/routes/(app)/containers/+page.svelteindex e69da3309..4738cb5ac 100644--- a/frontend/src/routes/(app)/containers/+page.svelte+++ b/frontend/src/routes/(app)/containers/+page.svelte@@ -24,10 +24,13 @@let selectedIds = $state<string[]>([]);let isCreateDialogOpen = $state(false);let containers = $state(untrack(() => data.containers));- let isRefreshing = $state(false);const envId = $derived(environmentStore.selected?.id || '0');+ let displayedEnvId = $state<string | null>(untrack(() => (data.envId === envId ? data.envId : null)));+ let isRefreshing = $state(false);+ let refreshGeneration = 0;let groupByProject = $state(false);let hasSeenEnvironmentSync = $state(false);+ const resourcesReady = $derived(displayedEnvId === envId);const countsFallback: ContainerStatusCounts = {runningContainers: 0,@@ -42,23 +45,38 @@};}- async function refreshContainers(options: ContainerListRequestOptions = buildRequestOptions()) {- isRefreshing = true;+ async function refreshContainers(options: ContainerListRequestOptions = buildRequestOptions(), requestedEnvId = envId) {+ const generation = ++refreshGeneration;+ if (requestedEnvId === envId) {+ isRefreshing = true;+ }try {- const next = await containerService.getContainersForEnvironment(envId, options);+ const next = await containerService.getContainersForEnvironment(requestedEnvId, options);+ if (requestedEnvId !== envId || generation !== refreshGeneration) {+ return containers;+ }containers = next;+ displayedEnvId = requestedEnvId;return next;} finally {- isRefreshing = false;+ if (requestedEnvId === envId && generation === refreshGeneration) {+ isRefreshing = false;+ }}}const checkUpdatesMutation = createMutation(() => ({mutationKey: queryKeys.containers.checkUpdates(envId),- mutationFn: () => imageService.runAutoUpdate(),- onSuccess: async (data) => {- toast.success(m.containers_check_updates_success(), activityToastOptions(extractActivityId(data)));- await refreshContainers();+ mutationFn: async () => {+ const requestedEnvId = envId;+ const result = await imageService.runAutoUpdate(undefined, requestedEnvId);+ return { requestedEnvId, result };+ },+ onSuccess: async ({ requestedEnvId, result }) => {+ toast.success(m.containers_check_updates_success(), activityToastOptions(extractActivityId(result)));+ if (requestedEnvId === envId) {+ await refreshContainers(buildRequestOptions(), requestedEnvId);+ }},onError: () => {toast.error(m.containers_check_updates_failed());@@ -67,11 +85,17 @@const createContainerMutation = createMutation(() => ({mutationKey: queryKeys.containers.create(envId),- mutationFn: (options: ContainerCreateRequest) => containerService.createContainer(options),- onSuccess: async () => {+ mutationFn: async (options: ContainerCreateRequest) => {+ const requestedEnvId = envId;+ const result = await containerService.createContainer(options, requestedEnvId);+ return { requestedEnvId, result };+ },+ onSuccess: async ({ requestedEnvId }) => {toast.success(m.common_create_success({ resource: m.resource_container() }));- await refreshContainers();- isCreateDialogOpen = false;+ if (requestedEnvId === envId) {+ await refreshContainers(buildRequestOptions(), requestedEnvId);+ isCreateDialogOpen = false;+ }},onError: () => {toast.error(m.containers_create_failed());@@ -81,9 +105,17 @@function handleEnvironmentChange() {if (!hasSeenEnvironmentSync) {hasSeenEnvironmentSync = true;- return;+ if (data.envId === envId) {+ return;+ }}+ refreshGeneration += 1;+ isRefreshing = false;+ displayedEnvId = null;+ selectedIds = [];+ isCreateDialogOpen = false;+const nextOptions: SearchPaginationSortRequest = {...requestOptions,pagination: {@@ -92,7 +124,7 @@}};requestOptions = nextOptions;- return refreshContainers(buildRequestOptions(nextOptions));+ return refreshContainers(buildRequestOptions(nextOptions), envId);}async function handleCheckForUpdates() {@@ -103,7 +135,7 @@await refreshContainers();}- const containerStatusCounts = $derived(containers.counts ?? countsFallback);+ const containerStatusCounts = $derived(resourcesReady ? (containers.counts ?? countsFallback) : countsFallback);const canAutoUpdate = $derived(hasPermission('containers:autoupdate', envId));@@ -115,7 +147,7 @@label: m.common_create_button({ resource: m.resource_container_cap() }),onclick: () => (isCreateDialogOpen = true),loading: createContainerMutation.isPending,- disabled: createContainerMutation.isPending+ disabled: !resourcesReady || createContainerMutation.isPending},canAutoUpdate? {@@ -124,7 +156,7 @@label: m.containers_check_updates(),onclick: handleCheckForUpdates,loading: checkUpdatesMutation.isPending,- disabled: checkUpdatesMutation.isPending+ disabled: !resourcesReady || checkUpdatesMutation.isPending}: null,{@@ -166,22 +198,26 @@<ResourcePageLayout title={m.containers_title()} subtitle={m.containers_subtitle()} {actionButtons} {statCards}>{#snippet mainContent()}- <ContainerTable- bind:containers- bind:selectedIds- bind:requestOptions- bind:groupByProject- onRefreshData={async (options) => {- requestOptions = {- search: options.search,- pagination: options.pagination,- sort: options.sort,- filters: options.filters,- includeInternal: options.includeInternal- };- return refreshContainers(options);- }}- />+ {#if resourcesReady}+ <ContainerTable+ environmentId={displayedEnvId!}+ bind:containers+ bind:selectedIds+ bind:requestOptions+ bind:groupByProject+ onRefreshData={async (options) => {+ const requestedEnvId = envId;+ requestOptions = {+ search: options.search,+ pagination: options.pagination,+ sort: options.sort,+ filters: options.filters,+ includeInternal: options.includeInternal+ };+ return refreshContainers(options, requestedEnvId);+ }}+ />+ {/if}{/snippet}{#snippet additionalContent()}diff --git a/frontend/src/routes/(app)/containers/+page.ts b/frontend/src/routes/(app)/containers/+page.tsindex 91b061903..36a1a12df 100644--- a/frontend/src/routes/(app)/containers/+page.ts+++ b/frontend/src/routes/(app)/containers/+page.ts@@ -35,6 +35,7 @@ export const load: PageLoad = async ({ parent }) => {}return {+ envId,containers,containerRequestOptions,settings,diff --git a/frontend/src/routes/(app)/containers/container-table.svelte b/frontend/src/routes/(app)/containers/container-table.svelteindex 1a9f2417b..e104ca724 100644--- a/frontend/src/routes/(app)/containers/container-table.svelte+++ b/frontend/src/routes/(app)/containers/container-table.svelte@@ -65,6 +65,7 @@type FieldVisibility = Record<string, boolean>;let {+ environmentId,containers = $bindable(),selectedIds = $bindable(),requestOptions = $bindable(),@@ -72,6 +73,7 @@withoutFilters = false,onRefreshData}: {+ environmentId: string;containers: ContainersPaginatedResponse;selectedIds: string[];requestOptions: SearchPaginationSortRequest;@@ -172,6 +174,9 @@);const shouldConnect = $derived.by(() => {+ if (!resourcesCurrent) {+ return new Set<string>();+ }const cpuVisible = columnVisibility['cpuUsage'] !== false;const memoryVisible = columnVisibility['memoryUsage'] !== false;const statsVisible = cpuVisible || memoryVisible;@@ -185,6 +190,7 @@});const currentEnvId = $derived(environmentStore.selected?.id || '0');+ const resourcesCurrent = $derived(environmentId === currentEnvId);const canUpdateContainers = $derived(hasPermission('containers:autoupdate', currentEnvId));const canKillContainers = $derived(hasPermission('containers:kill', currentEnvId));const canPauseContainers = $derived(hasPermission('containers:pause', currentEnvId));@@ -302,7 +308,7 @@action: 'start',onClick: handleBulkStart,loading: isBulkLoading.start,- disabled: isAnyLoading,+ disabled: !resourcesCurrent || isAnyLoading,icon: StartIcon},{@@ -311,7 +317,7 @@action: 'stop',onClick: handleBulkStop,loading: isBulkLoading.stop,- disabled: isAnyLoading,+ disabled: !resourcesCurrent || isAnyLoading,icon: StopIcon},{@@ -320,7 +326,7 @@action: 'restart',onClick: handleBulkRestart,loading: isBulkLoading.restart,- disabled: isAnyLoading,+ disabled: !resourcesCurrent || isAnyLoading,icon: RefreshIcon},{@@ -329,7 +335,7 @@action: 'remove',onClick: handleBulkRemove,loading: isBulkLoading.remove,- disabled: isAnyLoading,+ disabled: !resourcesCurrent || isAnyLoading,icon: TrashIcon}]);@@ -344,7 +350,9 @@}</script>-<ContainerStatsSync {statsManager} envId={currentEnvId} targetIds={shouldConnect} />+{#if resourcesCurrent}+ <ContainerStatsSync {statsManager} envId={environmentId} targetIds={shouldConnect} />+{/if}{#snippet IPAddressCell({ item }: { item: ContainerSummaryDto })}{@const ipAddresses = getContainerIpAddresses(item)}@@ -423,7 +431,7 @@size="sm"class="size-7 border-transparent bg-transparent p-0 text-green-600 shadow-none hover:bg-green-600/10 hover:text-green-500"onclick={() => performContainerAction('start', item.id)}- disabled={isAnyLoading}+ disabled={!resourcesCurrent || isAnyLoading}icon={StartIcon}title={m.common_start()}/>@@ -434,7 +442,7 @@size="sm"class="size-7 border-transparent bg-transparent p-0 text-red-600 shadow-none hover:bg-red-600/10 hover:text-red-500"onclick={() => performContainerAction('stop', item.id)}- disabled={isAnyLoading}+ disabled={!resourcesCurrent || isAnyLoading}title={m.common_stop()}icon={StopIcon}/>@@ -446,7 +454,7 @@size="sm"class="size-7 p-0"onclick={() => handleUpdateContainer(item)}- disabled={isAnyLoading}+ disabled={!resourcesCurrent || isAnyLoading}title={m.containers_update_container()}icon={UpdateIcon}/>@@ -614,117 +622,119 @@{/snippet}{#snippet RowActions({ item }: { item: ContainerSummaryDto })}- {@const status = actionStatus[item.id]}- <RowActionsMenu>- <DropdownMenu.Item onclick={() => goto(`/containers/${item.id}`)} disabled={isAnyLoading}>- <InspectIcon class="size-4" />- {m.common_inspect()}- </DropdownMenu.Item>-- <DropdownMenu.Separator />-- {#if item.updateInfo?.hasUpdate && canUpdateContainers}- <DropdownMenu.Item onclick={() => handleUpdateContainer(item)} disabled={status === 'updating' || isAnyLoading}>- {#if status === 'updating'}- <Spinner class="size-4" />- {:else}- <UpdateIcon class="size-4" />- {m.common_update()}- {/if}+ {#if resourcesCurrent}+ {@const status = actionStatus[item.id]}+ <RowActionsMenu>+ <DropdownMenu.Item onclick={() => goto(`/containers/${item.id}`)} disabled={isAnyLoading}>+ <InspectIcon class="size-4" />+ {m.common_inspect()}</DropdownMenu.Item>- {/if}- {#if item.state === 'paused'}- {#if canPauseContainers}- <DropdownMenu.Item- onclick={() => performContainerAction('unpause', item.id)}- disabled={status === 'unpausing' || isAnyLoading}- >- {#if status === 'unpausing'}++ <DropdownMenu.Separator />++ {#if item.updateInfo?.hasUpdate && canUpdateContainers}+ <DropdownMenu.Item onclick={() => handleUpdateContainer(item)} disabled={status === 'updating' || isAnyLoading}>+ {#if status === 'updating'}<Spinner class="size-4" />{:else}- <PlayIcon class="size-4" />+ <UpdateIcon class="size-4" />+ {m.common_update()}{/if}- {m.common_unpause()}</DropdownMenu.Item>{/if}- {:else if item.state !== 'running'}- <DropdownMenu.Item- onclick={() => performContainerAction('start', item.id)}- disabled={status === 'starting' || isAnyLoading}- >- {#if status === 'starting'}- <Spinner class="size-4" />- {:else}- <StartIcon class="size-4" />+ {#if item.state === 'paused'}+ {#if canPauseContainers}+ <DropdownMenu.Item+ onclick={() => performContainerAction('unpause', item.id)}+ disabled={status === 'unpausing' || isAnyLoading}+ >+ {#if status === 'unpausing'}+ <Spinner class="size-4" />+ {:else}+ <PlayIcon class="size-4" />+ {/if}+ {m.common_unpause()}+ </DropdownMenu.Item>{/if}- {m.common_start()}- </DropdownMenu.Item>- {:else}- <ContainerActionMenuItem- icon={StopIcon}- label={m.common_stop()}- onclick={() => performContainerAction('stop', item.id)}- loading={status === 'stopping'}- disabled={status === 'stopping' || isAnyLoading}- />-- <ContainerActionMenuItem- icon={RefreshIcon}- label={m.common_restart()}- onclick={() => performContainerAction('restart', item.id)}- loading={status === 'restarting'}- disabled={status === 'restarting' || isAnyLoading}- />-- {#if canPauseContainers}+ {:else if item.state !== 'running'}<DropdownMenu.Item- onclick={() => performContainerAction('pause', item.id)}- disabled={status === 'pausing' || isAnyLoading}+ onclick={() => performContainerAction('start', item.id)}+ disabled={status === 'starting' || isAnyLoading}>- {#if status === 'pausing'}+ {#if status === 'starting'}<Spinner class="size-4" />{:else}- <PauseIcon class="size-4" />+ <StartIcon class="size-4" />{/if}- {m.common_pause()}+ {m.common_start()}</DropdownMenu.Item>- {/if}- {/if}+ {:else}+ <ContainerActionMenuItem+ icon={StopIcon}+ label={m.common_stop()}+ onclick={() => performContainerAction('stop', item.id)}+ loading={status === 'stopping'}+ disabled={status === 'stopping' || isAnyLoading}+ />- {#if (item.state === 'running' || item.state === 'paused') && canKillContainers}- <DropdownMenu.Item onclick={() => openKillDialog(item)} disabled={isAnyLoading}>- <ZapIcon class="size-4" />- {m.common_kill()}- </DropdownMenu.Item>- {/if}+ <ContainerActionMenuItem+ icon={RefreshIcon}+ label={m.common_restart()}+ onclick={() => performContainerAction('restart', item.id)}+ loading={status === 'restarting'}+ disabled={status === 'restarting' || isAnyLoading}+ />- {#if item.redeployDisabled}- <DropdownMenu.Item disabled title={m.common_redeploy_disabled_arcane_self()}>- <RedeployIcon class="size-4 opacity-50" />- {m.common_redeploy()}- </DropdownMenu.Item>- {:else}- <DropdownMenu.Item onclick={() => handleRedeployContainer(item)} disabled={status === 'redeploying' || isAnyLoading}>- {#if status === 'redeploying'}- <Spinner class="size-4" />- {:else}- <RedeployIcon class="size-4" />+ {#if canPauseContainers}+ <DropdownMenu.Item+ onclick={() => performContainerAction('pause', item.id)}+ disabled={status === 'pausing' || isAnyLoading}+ >+ {#if status === 'pausing'}+ <Spinner class="size-4" />+ {:else}+ <PauseIcon class="size-4" />+ {/if}+ {m.common_pause()}+ </DropdownMenu.Item>{/if}- {m.common_redeploy()}- </DropdownMenu.Item>- {/if}+ {/if}++ {#if (item.state === 'running' || item.state === 'paused') && canKillContainers}+ <DropdownMenu.Item onclick={() => openKillDialog(item)} disabled={isAnyLoading}>+ <ZapIcon class="size-4" />+ {m.common_kill()}+ </DropdownMenu.Item>+ {/if}- <DropdownMenu.Separator />-- <ContainerActionMenuItem- icon={TrashIcon}- label={m.common_remove()}- onclick={() => handleRemoveContainer(item.id, getContainerDisplayName(item))}- loading={status === 'removing'}- disabled={status === 'removing' || isAnyLoading}- destructive- />- </RowActionsMenu>+ {#if item.redeployDisabled}+ <DropdownMenu.Item disabled title={m.common_redeploy_disabled_arcane_self()}>+ <RedeployIcon class="size-4 opacity-50" />+ {m.common_redeploy()}+ </DropdownMenu.Item>+ {:else}+ <DropdownMenu.Item onclick={() => handleRedeployContainer(item)} disabled={status === 'redeploying' || isAnyLoading}>+ {#if status === 'redeploying'}+ <Spinner class="size-4" />+ {:else}+ <RedeployIcon class="size-4" />+ {/if}+ {m.common_redeploy()}+ </DropdownMenu.Item>+ {/if}++ <DropdownMenu.Separator />++ <ContainerActionMenuItem+ icon={TrashIcon}+ label={m.common_remove()}+ onclick={() => handleRemoveContainer(item.id, getContainerDisplayName(item))}+ loading={status === 'removing'}+ disabled={status === 'removing' || isAnyLoading}+ destructive+ />+ </RowActionsMenu>+ {/if}{/snippet}<ArcaneTablediff --git a/frontend/src/routes/(app)/images/+page.svelte b/frontend/src/routes/(app)/images/+page.svelteindex 443dc5f88..4b0750425 100644--- a/frontend/src/routes/(app)/images/+page.svelte+++ b/frontend/src/routes/(app)/images/+page.svelte@@ -30,10 +30,12 @@let isRegistrySearchDialogOpen = $state(false);let isUploadDialogOpen = $state(false);let isConfirmPruneDialogOpen = $state(false);+ let isRefreshing = $state(false);let uploadedFiles = $state<File[]>([]);let imagePruneMode = $state<'dangling' | 'all' | 'olderThan'>('dangling');let imagePruneUntil = $state('');const envId = $derived(environmentStore.selected?.id || '0');+ let previousEnvId = untrack(() => envId);const imageUsageFallback: ImageUsageCounts = {imagesInuse: 0,imagesUnused: 0,@@ -41,31 +43,47 @@totalImageSize: 0};- const maxUploadSizeMB = $derived(parseInt(String(data.settings?.maxImageUploadSize || '500'), 10));+ const maxUploadSizeMB = $derived(+ parseInt(String((data.envId === envId ? data.settings?.maxImageUploadSize : undefined) || '500'), 10)+ );- const imagesQuery = createQuery(() => ({- queryKey: queryKeys.images.list(envId, requestOptions),- queryFn: () => imageService.getImagesForEnvironment(envId, requestOptions),- initialData: data.images- }));+ const imagesQuery = createQuery(() => {+ const queryEnvId = envId;+ return {+ queryKey: queryKeys.images.list(queryEnvId, requestOptions),+ queryFn: () => imageService.getImagesForEnvironment(queryEnvId, requestOptions),+ initialData: data.envId === queryEnvId ? data.images : undefined,+ select: (value) => ({ envId: queryEnvId, value })+ };+ });- const imageUsageCountsQuery = createQuery(() => ({- queryKey: queryKeys.images.usageCounts(envId),- queryFn: () => imageService.getImageUsageCountsForEnvironment(envId),- initialData: data.imageUsageCounts- }));+ const imageUsageCountsQuery = createQuery(() => {+ const queryEnvId = envId;+ return {+ queryKey: queryKeys.images.usageCounts(queryEnvId),+ queryFn: () => imageService.getImageUsageCountsForEnvironment(queryEnvId),+ initialData: data.envId === queryEnvId ? data.imageUsageCounts : undefined,+ select: (value) => ({ envId: queryEnvId, value })+ };+ });+ const resourcesReady = $derived(imagesQuery.data?.envId === envId);const pruneImagesMutation = createMutation(() => ({mutationKey: ['images', 'prune', envId],- mutationFn: () =>- imageService.pruneImages({- mode: imagePruneMode,- ...(imagePruneMode === 'olderThan' ? { until: imagePruneUntil } : {})- }),- onSuccess: async (data) => {+ mutationFn: (requestedEnvId: string) =>+ imageService.pruneImages(+ {+ mode: imagePruneMode,+ ...(imagePruneMode === 'olderThan' ? { until: imagePruneUntil } : {})+ },+ requestedEnvId+ ),+ onSuccess: async (data, requestedEnvId) => {toast.success(m.images_pruned_success(), activityToastOptions(extractActivityId(data)));- await Promise.all([imagesQuery.refetch(), imageUsageCountsQuery.refetch()]);- isConfirmPruneDialogOpen = false;+ if (requestedEnvId === envId) {+ await Promise.all([imagesQuery.refetch(), imageUsageCountsQuery.refetch()]);+ isConfirmPruneDialogOpen = false;+ }},onError: () => {toast.error(m.images_prune_failed());@@ -74,10 +92,12 @@const checkUpdatesMutation = createMutation(() => ({mutationKey: ['images', 'check-updates', envId],- mutationFn: () => imageService.checkAllImages(),- onSuccess: async (data) => {+ mutationFn: (requestedEnvId: string) => imageService.checkAllImages(requestedEnvId),+ onSuccess: async (data, requestedEnvId) => {toast.success(m.images_update_check_completed(), activityToastOptions(extractActivityId(data)));- await imagesQuery.refetch();+ if (requestedEnvId === envId) {+ await imagesQuery.refetch();+ }},onError: () => {toast.error(m.images_update_check_failed());@@ -86,36 +106,51 @@const uploadImagesMutation = createMutation(() => ({mutationKey: ['images', 'upload', envId],- mutationFn: async (files: File[]) => {+ mutationFn: async ({ files, requestedEnvId }: { files: File[]; requestedEnvId: string }) => {for (const file of files) {try {- await imageService.uploadImage(file);+ await imageService.uploadImage(file, requestedEnvId);toast.success(m.images_upload_success());} catch {toast.error(m.images_upload_failed());}}},- onSuccess: async () => {- await Promise.all([imagesQuery.refetch(), imageUsageCountsQuery.refetch()]);- uploadedFiles = [];- isUploadDialogOpen = false;+ onSuccess: async (_data, { requestedEnvId }) => {+ if (requestedEnvId === envId) {+ await Promise.all([imagesQuery.refetch(), imageUsageCountsQuery.refetch()]);+ uploadedFiles = [];+ isUploadDialogOpen = false;+ }}}));$effect(() => {- if (imagesQuery.data) {- images = imagesQuery.data;+ if (imagesQuery.data?.envId === envId) {+ images = imagesQuery.data.value;}});- const imageUsageCounts = $derived(imageUsageCountsQuery.data ?? imageUsageFallback);+ $effect(() => {+ if (envId === previousEnvId) return;+ previousEnvId = envId;+ selectedIds = [];+ isPullDialogOpen = false;+ isRegistrySearchDialogOpen = false;+ isUploadDialogOpen = false;+ isConfirmPruneDialogOpen = false;+ uploadedFiles = [];+ isRefreshing = false;+ });++ const imageUsageCounts = $derived(+ imageUsageCountsQuery.data?.envId === envId ? imageUsageCountsQuery.data.value : imageUsageFallback+ );// Intentionally a manual flag, not $derived(query.isFetching): these queries use// aggressive background refetching (staleTime: 0 + refetchOnMount/WindowFocus:// 'always'), so deriving from isFetching leaves the manual refresh button spinning// constantly. Mirrors the containers page — reflects only user-initiated refreshes.- let isRefreshing = $state(false);const isUploading = $derived(uploadImagesMutation.isPending);const isPruning = $derived(pruneImagesMutation.isPending);const isChecking = $derived(checkUpdatesMutation.isPending);@@ -133,15 +168,15 @@toast.error(m.images_upload_file_required());return;}- await uploadImagesMutation.mutateAsync(uploadedFiles);+ await uploadImagesMutation.mutateAsync({ files: uploadedFiles, requestedEnvId: envId });}async function handleTriggerBulkUpdateCheck() {- await checkUpdatesMutation.mutateAsync();+ await checkUpdatesMutation.mutateAsync(envId);}async function handlePruneImages() {- await pruneImagesMutation.mutateAsync();+ await pruneImagesMutation.mutateAsync(envId);}const imagePruneModes = [@@ -151,11 +186,14 @@];async function refresh() {+ const requestedEnvId = envId;isRefreshing = true;try {await Promise.all([imagesQuery.refetch(), imageUsageCountsQuery.refetch()]);} finally {- isRefreshing = false;+ if (requestedEnvId === envId) {+ isRefreshing = false;+ }}}@@ -166,13 +204,20 @@const actionButtons: ActionButton[] = $derived.by(() => {const buttons: ActionButton[] = [];if (canPullImage) {- buttons.push({ id: 'pull', action: 'pull', label: m.images_pull_image(), onclick: () => (isPullDialogOpen = true) });+ buttons.push({+ id: 'pull',+ action: 'pull',+ label: m.images_pull_image(),+ onclick: () => (isPullDialogOpen = true),+ disabled: !resourcesReady+ });buttons.push({id: 'registry-search',action: 'inspect',label: m.images_search_registry(),icon: SearchIcon,- onclick: () => (isRegistrySearchDialogOpen = true)+ onclick: () => (isRegistrySearchDialogOpen = true),+ disabled: !resourcesReady});}if (canUploadImage) {@@ -180,7 +225,8 @@id: 'upload',action: 'create',label: m.images_upload_image(),- onclick: () => (isUploadDialogOpen = true)+ onclick: () => (isUploadDialogOpen = true),+ disabled: !resourcesReady});}if (canPullImage) {@@ -191,7 +237,7 @@loadingLabel: m.common_action_checking(),onclick: handleTriggerBulkUpdateCheck,loading: isChecking,- disabled: isChecking+ disabled: !resourcesReady || isChecking});}buttons.push({@@ -210,7 +256,7 @@loadingLabel: m.common_action_pruning(),onclick: () => (isConfirmPruneDialogOpen = true),loading: isPruning,- disabled: isPruning+ disabled: !resourcesReady || isPruning});}return buttons;@@ -234,19 +280,25 @@<ResourcePageLayout title={m.images_title()} subtitle={m.images_subtitle()} {actionButtons} {statCards}>{#snippet mainContent()}- <ImageTable- bind:images- bind:selectedIds- bind:requestOptions- loading={imagesQuery.isLoading}- onRefreshData={async (options) => {- requestOptions = options;- await Promise.all([imagesQuery.refetch(), imageUsageCountsQuery.refetch()]);- }}- onImageUpdated={async () => {- await imagesQuery.refetch();- }}- />+ {#if resourcesReady}+ <ImageTable+ bind:images+ bind:selectedIds+ bind:requestOptions+ loading={imagesQuery.isLoading}+ onRefreshData={async (options) => {+ const requestedEnvId = envId;+ requestOptions = options;+ await imageUsageCountsQuery.refetch();+ if (requestedEnvId !== envId) {+ selectedIds = [];+ }+ }}+ onImageUpdated={async () => {+ await imagesQuery.refetch();+ }}+ />+ {/if}{/snippet}{#snippet additionalContent()}diff --git a/frontend/src/routes/(app)/images/+page.ts b/frontend/src/routes/(app)/images/+page.tsindex ece5b4e01..63fbb445f 100644--- a/frontend/src/routes/(app)/images/+page.ts+++ b/frontend/src/routes/(app)/images/+page.ts@@ -36,5 +36,5 @@ export const load: PageLoad = async ({ parent }) => {throwPageLoadError(err, 'Failed to load images');}- return { images, imageRequestOptions, settings, imageUsageCounts };+ return { envId, images, imageRequestOptions, settings, imageUsageCounts };};diff --git a/frontend/src/routes/(app)/networks/+page.svelte b/frontend/src/routes/(app)/networks/+page.svelteindex 98e33abe9..f7f45a1cc 100644--- a/frontend/src/routes/(app)/networks/+page.svelte+++ b/frontend/src/routes/(app)/networks/+page.svelte@@ -12,34 +12,44 @@import { queryKeys } from '$lib/query/query-keys';import { untrack } from 'svelte';import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';- import { createMutation, createQuery } from '@tanstack/svelte-query';+ import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';import { activityToastOptions, extractActivityId } from '$lib/utils/activity-toast';let { data } = $props();+ const queryClient = useQueryClient();const pageState = new ResourceListPageState(untrack(() => data.networks),untrack(() => data.networkRequestOptions));+ let previousEnvId = untrack(() => pageState.envId);const countsFallback: NetworkUsageCounts = { inuse: 0, unused: 0, total: 0 };- const networksQuery = createQuery(() => ({- queryKey: queryKeys.networks.list(pageState.envId, pageState.requestOptions),- queryFn: () => networkService.getNetworksForEnvironment(pageState.envId, pageState.requestOptions),- initialData: data.networks- }));+ const networksQuery = createQuery(() => {+ const queryEnvId = pageState.envId;+ return {+ queryKey: queryKeys.networks.list(queryEnvId, pageState.requestOptions),+ queryFn: () => networkService.getNetworksForEnvironment(queryEnvId, pageState.requestOptions),+ 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 createNetworkMutation = createMutation(() => ({mutationKey: ['networks', 'create', pageState.envId],- mutationFn: ({ name, options }: { name: string; options: NetworkCreateOptions }) =>- networkService.createNetwork(name, options),+ mutationFn: ({ name, options, requestedEnvId }: { name: string; options: NetworkCreateOptions; requestedEnvId: string }) =>+ networkService.createNetwork(name, options, requestedEnvId),onSuccess: async (data, variables) => {toast.success(m.common_create_success({ resource: `${m.resource_network()} "${variables.name}"` }),activityToastOptions(extractActivityId(data)));- await networksQuery.refetch();- pageState.isCreateDialogOpen = false;+ if (variables.requestedEnvId === pageState.envId) {+ await loadNetworks(pageState.requestOptions, variables.requestedEnvId);+ pageState.isCreateDialogOpen = false;+ }},onError: (_error, variables) => {toast.error(m.common_create_failed({ resource: `${m.resource_network()} "${variables.name}"` }));@@ -47,21 +57,43 @@}));$effect(() => {- if (networksQuery.data) {- pageState.items = networksQuery.data;+ 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;+ pageState.selectedIds = [];+ pageState.isCreateDialogOpen = false;+ });+async function handleCreate(name: string, options: NetworkCreateOptions) {- await createNetworkMutation.mutateAsync({ name, options });+ await createNetworkMutation.mutateAsync({ name, options, requestedEnvId: pageState.envId });+ }++ async function loadNetworks(options = pageState.requestOptions, requestedEnvId = pageState.envId) {+ pageState.requestOptions = options;+ const next = await queryClient.fetchQuery({+ queryKey: queryKeys.networks.list(requestedEnvId, options),+ queryFn: () => networkService.getNetworksForEnvironment(requestedEnvId, options)+ });+ if (requestedEnvId !== pageState.envId) {+ return;+ }+ pageState.items = next;+ displayedEnvId = requestedEnvId;}async function refresh() {- await networksQuery.refetch();+ await loadNetworks();}const isRefreshing = $derived(networksQuery.isFetching && !networksQuery.isPending);- const networkUsageCounts = $derived(pageState.items.counts ?? countsFallback);+ const networkUsageCounts = $derived(resourcesReady ? (pageState.items.counts ?? countsFallback) : countsFallback);const actionButtons: ActionButton[] = $derived([{@@ -70,7 +102,7 @@label: m.common_create_button({ resource: m.resource_network_cap() }),onclick: () => (pageState.isCreateDialogOpen = true),loading: createNetworkMutation.isPending,- disabled: createNetworkMutation.isPending+ disabled: !resourcesReady || createNetworkMutation.isPending},{id: 'refresh',@@ -78,14 +110,15 @@label: m.common_refresh(),onclick: refresh,loading: isRefreshing,- disabled: isRefreshing+ disabled: networksQuery.isFetching},{id: 'topology',action: 'inspect',label: m.networks_topology_button(),icon: GitBranchIcon,- onclick: () => void goto('/networks/topology')+ onclick: () => void goto('/networks/topology'),+ disabled: !resourcesReady}]);@@ -107,15 +140,14 @@<ResourcePageLayout title={m.networks_title()} subtitle={m.networks_subtitle()} {actionButtons} {statCards}>{#snippet mainContent()}- <NetworkTable- bind:networks={pageState.items}- bind:selectedIds={pageState.selectedIds}- bind:requestOptions={pageState.requestOptions}- onRefreshData={async (options) => {- pageState.requestOptions = options;- await networksQuery.refetch();- }}- />+ {#if resourcesReady}+ <NetworkTable+ bind:networks={pageState.items}+ bind:selectedIds={pageState.selectedIds}+ bind:requestOptions={pageState.requestOptions}+ onRefreshData={loadNetworks}+ />+ {/if}{/snippet}{#snippet additionalContent()}diff --git a/frontend/src/routes/(app)/networks/+page.ts b/frontend/src/routes/(app)/networks/+page.tsindex 9bfa54909..ebd47f643 100644--- a/frontend/src/routes/(app)/networks/+page.ts+++ b/frontend/src/routes/(app)/networks/+page.ts@@ -26,6 +26,7 @@ export const load: PageLoad = async ({ parent }) => {}return {+ envId,networks,networkRequestOptions,// Use counts from the networks responsediff --git a/frontend/src/routes/(app)/networks/topology/+page.svelte b/frontend/src/routes/(app)/networks/topology/+page.svelteindex e99844411..bd7f819c4 100644--- a/frontend/src/routes/(app)/networks/topology/+page.svelte+++ b/frontend/src/routes/(app)/networks/topology/+page.svelte@@ -11,12 +11,16 @@const envId = $derived(environmentStore.selected?.id || '0');- const topologyQuery = createQuery(() => ({- queryKey: queryKeys.networks.topology(envId),- queryFn: () => networkService.getNetworkTopology(envId),- initialData: data.topology- }));- const topology = $derived(topologyQuery.data!);+ const topologyQuery = createQuery(() => {+ const queryEnvId = envId;+ return {+ queryKey: queryKeys.networks.topology(queryEnvId),+ queryFn: () => networkService.getNetworkTopology(queryEnvId),+ initialData: data.envId === queryEnvId ? data.topology : undefined,+ select: (value) => ({ envId: queryEnvId, value })+ };+ });+ const topology = $derived(topologyQuery.data?.envId === envId ? topologyQuery.data.value : null);async function refresh() {await topologyQuery.refetch();@@ -31,13 +35,15 @@label: m.common_refresh(),onclick: refresh,loading: isRefreshing,- disabled: isRefreshing+ disabled: topologyQuery.isFetching}]);</script><ResourcePageLayout title={m.networks_topology_title()} subtitle={m.networks_topology_subtitle()} {actionButtons}>{#snippet mainContent()}- <NetworkDiagram {topology} />+ {#if topology}+ <NetworkDiagram {topology} />+ {/if}{/snippet}</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/networks/topology/+page.ts b/frontend/src/routes/(app)/networks/topology/+page.tsindex c66ac7ce9..0118f2035 100644--- a/frontend/src/routes/(app)/networks/topology/+page.ts+++ b/frontend/src/routes/(app)/networks/topology/+page.ts@@ -19,6 +19,7 @@ export const load: PageLoad = async ({ parent }) => {}return {+ envId,topology};};diff --git a/frontend/src/routes/(app)/ports/+page.svelte b/frontend/src/routes/(app)/ports/+page.svelteindex a50ad9e73..94aeab971 100644--- a/frontend/src/routes/(app)/ports/+page.svelte+++ b/frontend/src/routes/(app)/ports/+page.svelte@@ -14,13 +14,24 @@let selectedIds = $state<string[]>([]);const envId = $derived(environmentStore.selected?.id || '0');+ let previousEnvId = untrack(() => envId);- const portsQuery = createQuery(() => ({- queryKey: queryKeys.ports.list(envId, requestOptions),- queryFn: () => portService.getPortsForEnvironment(envId, requestOptions),- initialData: data.ports- }));- const ports = $derived(portsQuery.data!);+ const portsQuery = createQuery(() => {+ const queryEnvId = envId;+ return {+ queryKey: queryKeys.ports.list(queryEnvId, requestOptions),+ queryFn: () => portService.getPortsForEnvironment(queryEnvId, requestOptions),+ initialData: data.envId === queryEnvId ? data.ports : undefined,+ select: (value) => ({ envId: queryEnvId, value })+ };+ });+ const ports = $derived(portsQuery.data?.envId === envId ? portsQuery.data.value : null);++ $effect(() => {+ if (envId === previousEnvId) return;+ previousEnvId = envId;+ selectedIds = [];+ });async function refresh() {await portsQuery.refetch();@@ -35,21 +46,22 @@label: m.common_refresh(),onclick: refresh,loading: isRefreshing,- disabled: isRefreshing+ disabled: portsQuery.isFetching}]);</script><ResourcePageLayout title={m.ports_title()} subtitle={m.ports_subtitle()} {actionButtons}>{#snippet mainContent()}- <PortTable- {ports}- bind:selectedIds- bind:requestOptions- onRefreshData={async (options) => {- requestOptions = options;- await portsQuery.refetch();- }}- />+ {#if ports}+ <PortTable+ {ports}+ bind:selectedIds+ bind:requestOptions+ onRefreshData={async (options) => {+ requestOptions = options;+ }}+ />+ {/if}{/snippet}</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/ports/+page.ts b/frontend/src/routes/(app)/ports/+page.tsindex ddd0a62c3..2d6647536 100644--- a/frontend/src/routes/(app)/ports/+page.ts+++ b/frontend/src/routes/(app)/ports/+page.ts@@ -25,6 +25,7 @@ export const load: PageLoad = async ({ parent }) => {}return {+ envId,ports,portRequestOptions};diff --git a/frontend/src/routes/(app)/projects/+page.svelte b/frontend/src/routes/(app)/projects/+page.svelteindex 762edcc2b..d3b7be9c2 100644--- a/frontend/src/routes/(app)/projects/+page.svelte+++ b/frontend/src/routes/(app)/projects/+page.svelte@@ -35,7 +35,9 @@let baseProjectRequestOptions = $state(untrack(() => withArchivedFilter(data.projectRequestOptions, data.showArchived)));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 = {@@ -45,31 +47,49 @@archivedProjects: 0};- const projectsQuery = createQuery(() => ({- queryKey: queryKeys.projects.list(envId, projectRequestOptions),- queryFn: () => projectService.getProjectsForEnvironment(envId, projectRequestOptions),- initialData: data.projects,- refetchOnMount: false- }));- let projects = $derived(projectsQuery.data ?? untrack(() => data.projects));+ const projectsQuery = createQuery(() => {+ const queryEnvId = envId;+ return {+ queryKey: queryKeys.projects.list(queryEnvId, projectRequestOptions),+ queryFn: () => projectService.getProjectsForEnvironment(queryEnvId, projectRequestOptions),+ initialData: data.envId === queryEnvId ? data.projects : undefined,+ select: (value) => ({ envId: queryEnvId, value }),+ refetchOnMount: false+ };+ });+ let projects = $derived(projectsQuery.data?.envId === envId ? projectsQuery.data.value : null);- const projectStatusCountsQuery = createQuery(() => ({- queryKey: queryKeys.projects.statusCounts(envId),- queryFn: () => projectService.getProjectStatusCountsForEnvironment(envId),- initialData: data.projectStatusCounts,- refetchOnMount: false- }));+ const projectStatusCountsQuery = createQuery(() => {+ const queryEnvId = envId;+ return {+ queryKey: queryKeys.projects.statusCounts(queryEnvId),+ queryFn: () => projectService.getProjectStatusCountsForEnvironment(queryEnvId),+ initialData: data.envId === queryEnvId ? data.projectStatusCounts : undefined,+ select: (value) => ({ envId: queryEnvId, value }),+ refetchOnMount: false+ };+ });+ const resourcesReady = $derived(projects !== null);++ $effect(() => {+ if (envId === previousEnvId) return;+ previousEnvId = envId;+ selectedIds = [];+ isManualRefreshing = false;+ });const checkUpdatesMutation = createMutation(() => ({mutationKey: queryKeys.projects.checkUpdates(envId),- mutationFn: async () => {+ mutationFn: async (requestedEnvId: string) => {// Refresh update info for all images, then use the image->project usage// map to narrow the redeploy to projects that actually have updates.// This avoids hitting every project (and its registry) when nothing has// changed, which is especially expensive on instances with many projects.- const imageCheckResults = await imageService.checkAllImages();+ const imageCheckResults = await imageService.checkAllImages(requestedEnvId);- const images = await imageService.getImagesForEnvironment(envId, { pagination: { page: 1, limit: 10000 } });+ const images = await imageService.getImagesForEnvironment(requestedEnvId, {+ pagination: { page: 1, limit: 10000 }+ });const projectIdsWithUpdates = new Set<string>();for (const img of images.data) {if (!img.updateInfo?.hasUpdate) continue;@@ -84,7 +104,9 @@return { updated: 0, activityId: extractActivityId(imageCheckResults) };}- const allProjects = await projectService.getProjectsForEnvironment(envId, { pagination: { page: 1, limit: 1000 } });+ const allProjects = await projectService.getProjectsForEnvironment(requestedEnvId, {+ pagination: { page: 1, limit: 1000 }+ });const projectsToUpdate = allProjects.data.filter((p) => projectIdsWithUpdates.has(p.id));const results = await Promise.allSettled(@@ -103,43 +125,48 @@return { updated: results.length, activityId: extractActivityId(imageCheckResults) };},- onSuccess: async (result) => {+ onSuccess: async (result, requestedEnvId) => {const toastOptions = activityToastOptions(result.activityId);if (result && result.updated === 0) {toast.success(m.image_update_up_to_date_title(), toastOptions);} else {toast.success(m.compose_update_success(), toastOptions);}- await Promise.all([projectsQuery.refetch(), projectStatusCountsQuery.refetch()]);+ if (requestedEnvId === envId) {+ await Promise.all([projectsQuery.refetch(), projectStatusCountsQuery.refetch()]);+ }},- onError: (error) => {+ onError: (error, requestedEnvId) => {toast.error(error instanceof Error ? error.message : m.containers_check_updates_failed());- void Promise.all([projectsQuery.refetch(), projectStatusCountsQuery.refetch()]);+ if (requestedEnvId === envId) {+ void Promise.all([projectsQuery.refetch(), projectStatusCountsQuery.refetch()]);+ }}}));- const projectStatusCounts = $derived(projectStatusCountsQuery.data ?? countsFallback);+ const projectStatusCounts = $derived(+ projectStatusCountsQuery.data?.envId === envId ? projectStatusCountsQuery.data.value : countsFallback+ );const totalCompose = $derived(projectStatusCounts.totalProjects);const runningCompose = $derived(projectStatusCounts.runningProjects);const stoppedCompose = $derived(projectStatusCounts.stoppedProjects);const archivedCompose = $derived(projectStatusCounts.archivedProjects);- let isManualRefreshing = $state(false);- const isProjectsQueryRefreshing = $derived(projectsQuery.isFetching && !projectsQuery.isPending);- const isStatusCountsQueryRefreshing = $derived(projectStatusCountsQuery.isFetching && !projectStatusCountsQuery.isPending);- const isQueryRefreshing = $derived(isProjectsQueryRefreshing || isStatusCountsQueryRefreshing);- const isRefreshBlocked = $derived(isManualRefreshing || isQueryRefreshing);+ const isRefreshBlocked = $derived(isManualRefreshing || projectsQuery.isFetching || projectStatusCountsQuery.isFetching);async function handleCheckForUpdates() {- await checkUpdatesMutation.mutateAsync();+ await checkUpdatesMutation.mutateAsync(envId);}async function refreshCompose() {if (isRefreshBlocked) return;+ const requestedEnvId = envId;isManualRefreshing = true;try {await Promise.all([projectsQuery.refetch(), projectStatusCountsQuery.refetch()]);} finally {- isManualRefreshing = false;+ if (requestedEnvId === envId) {+ isManualRefreshing = false;+ }}}@@ -173,7 +200,7 @@label: m.compose_update_projects(),onclick: handleCheckForUpdates,loading: checkUpdatesMutation.isPending,- disabled: checkUpdatesMutation.isPending+ disabled: !resourcesReady || checkUpdatesMutation.isPending});}buttons.push({@@ -217,16 +244,22 @@<ResourcePageLayout title={m.projects_title()} subtitle={m.compose_subtitle()} {actionButtons} {statCards}>{#snippet mainContent()}- <ProjectsTable- {projects}- bind:selectedIds- requestOptions={projectRequestOptions}- {showArchived}- onToggleArchived={toggleArchived}- onRefreshData={async (options) => {- baseProjectRequestOptions = withArchivedFilter(options, showArchived);- await Promise.all([projectsQuery.refetch(), projectStatusCountsQuery.refetch()]);- }}- />+ {#if projects}+ <ProjectsTable+ {projects}+ bind:selectedIds+ requestOptions={projectRequestOptions}+ {showArchived}+ onToggleArchived={toggleArchived}+ onRefreshData={async (options) => {+ const requestedEnvId = envId;+ baseProjectRequestOptions = withArchivedFilter(options, showArchived);+ await Promise.all([projectsQuery.refetch(), projectStatusCountsQuery.refetch()]);+ if (requestedEnvId !== envId) {+ selectedIds = [];+ }+ }}+ />+ {/if}{/snippet}</ResourcePageLayout>diff --git a/frontend/src/routes/(app)/projects/+page.ts b/frontend/src/routes/(app)/projects/+page.tsindex c6369bff1..fe9279567 100644--- a/frontend/src/routes/(app)/projects/+page.ts+++ b/frontend/src/routes/(app)/projects/+page.ts@@ -46,5 +46,5 @@ export const load: PageLoad = async ({ parent, url }) => {throwPageLoadError(err, 'Failed to load projects');}- return { projects, projectRequestOptions, projectStatusCounts, showArchived };+ return { envId, projects, projectRequestOptions, projectStatusCounts, showArchived };};diff --git a/frontend/src/routes/(app)/volumes/+page.svelte b/frontend/src/routes/(app)/volumes/+page.svelteindex e69129887..7cbb3ec37 100644--- a/frontend/src/routes/(app)/volumes/+page.svelte+++ b/frontend/src/routes/(app)/volumes/+page.svelte@@ -21,48 +21,72 @@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 countsFallback: VolumeUsageCounts = { inuse: 0, unused: 0, total: 0 };- const volumesQuery = createQuery(() => ({- queryKey: queryKeys.volumes.table(pageState.envId, pageState.requestOptions),- queryFn: () => volumeService.getVolumesForEnvironment(pageState.envId, pageState.requestOptions),- initialData: data.volumes- }));+ const volumesQuery = createQuery(() => {+ const queryEnvId = pageState.envId;+ return {+ queryKey: queryKeys.volumes.table(queryEnvId, pageState.requestOptions),+ queryFn: () => volumeService.getVolumesForEnvironment(queryEnvId, pageState.requestOptions),+ initialData: data.envId === queryEnvId ? data.volumes : undefined,+ select: (value) => ({ envId: queryEnvId, value })+ };+ });const createVolumeMutation = createMutation(() => ({mutationKey: ['volumes', 'create', pageState.envId],- mutationFn: (options: VolumeCreateRequest) => volumeService.createVolume(options),+ mutationFn: ({ options, requestedEnvId }: { options: VolumeCreateRequest; requestedEnvId: string }) =>+ volumeService.createVolume(options, requestedEnvId),onSuccess: async (data, options) => {- const name = options.name?.trim() || m.common_unknown();+ const name = options.options.name?.trim() || m.common_unknown();toast.success(m.common_create_success({ resource: `${m.resource_volume()} "${name}"` }),activityToastOptions(extractActivityId(data)));- await loadVolumes();- pageState.isCreateDialogOpen = false;+ if (options.requestedEnvId === pageState.envId) {+ await loadVolumes(pageState.requestOptions, options.requestedEnvId);+ pageState.isCreateDialogOpen = false;+ }},onError: (_error, options) => {- const name = options.name?.trim() || m.common_unknown();+ const name = options.options.name?.trim() || m.common_unknown();toast.error(m.common_create_failed({ resource: `${m.resource_volume()} "${name}"` }));}}));$effect(() => {- if (volumesQuery.data) {- pageState.items = volumesQuery.data;+ 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;+ pageState.selectedIds = [];+ pageState.isCreateDialogOpen = false;+ });+async function handleCreate(options: VolumeCreateRequest) {- await createVolumeMutation.mutateAsync(options);+ await createVolumeMutation.mutateAsync({ options, requestedEnvId: pageState.envId });}- async function loadVolumes(options = pageState.requestOptions) {+ async function loadVolumes(options = pageState.requestOptions, requestedEnvId = pageState.envId) {pageState.requestOptions = options;- pageState.items = await queryClient.fetchQuery({- queryKey: queryKeys.volumes.table(pageState.envId, options),- queryFn: () => volumeService.getVolumesForEnvironment(pageState.envId, options)+ const next = await queryClient.fetchQuery({+ queryKey: queryKeys.volumes.table(requestedEnvId, options),+ queryFn: () => volumeService.getVolumesForEnvironment(requestedEnvId, options)});+ if (requestedEnvId !== pageState.envId) {+ return;+ }+ pageState.items = next;+ displayedEnvId = requestedEnvId;}async function refresh() {@@ -70,7 +94,7 @@}const isRefreshing = $derived(volumesQuery.isFetching && !volumesQuery.isPending);- const volumeUsageCounts = $derived(pageState.items.counts ?? countsFallback);+ const volumeUsageCounts = $derived(resourcesReady ? (pageState.items.counts ?? countsFallback) : countsFallback);const canCreateVolume = $derived(hasPermission('volumes:create', pageState.envId));@@ -83,7 +107,7 @@label: m.common_create_button({ resource: m.resource_volume_cap() }),onclick: () => (pageState.isCreateDialogOpen = true),loading: createVolumeMutation.isPending,- disabled: createVolumeMutation.isPending+ disabled: !resourcesReady || createVolumeMutation.isPending});}buttons.push({@@ -92,7 +116,7 @@label: m.common_refresh(),onclick: refresh,loading: isRefreshing,- disabled: isRefreshing+ disabled: volumesQuery.isFetching});return buttons;});@@ -115,12 +139,14 @@<ResourcePageLayout title={m.volumes_title()} subtitle={m.volumes_subtitle()} {actionButtons} {statCards}>{#snippet mainContent()}- <VolumeTable- bind:volumes={pageState.items}- bind:selectedIds={pageState.selectedIds}- bind:requestOptions={pageState.requestOptions}- onRefreshData={loadVolumes}- />+ {#if resourcesReady}+ <VolumeTable+ bind:volumes={pageState.items}+ bind:selectedIds={pageState.selectedIds}+ bind:requestOptions={pageState.requestOptions}+ onRefreshData={loadVolumes}+ />+ {/if}{/snippet}{#snippet additionalContent()}diff --git a/frontend/src/routes/(app)/volumes/+page.ts b/frontend/src/routes/(app)/volumes/+page.tsindex f0f820e5d..47d920f86 100644--- a/frontend/src/routes/(app)/volumes/+page.ts+++ b/frontend/src/routes/(app)/volumes/+page.ts@@ -27,6 +27,7 @@ export const load: PageLoad = async ({ parent }) => {});return {+ envId,volumes,volumeRequestOptions,// Use counts from the volumes responsediff --git a/tests/spec/environment-switch-isolation.spec.ts b/tests/spec/environment-switch-isolation.spec.tsnew file mode 100644index 000000000..67815f0d9--- /dev/null+++ b/tests/spec/environment-switch-isolation.spec.ts@@ -0,0 +1,267 @@+import { expect, test, type Page, type Route } from '@playwright/test';++const localEnvironment = {+ id: '0',+ name: 'Local Test',+ apiUrl: 'unix:///var/run/docker.sock',+ status: 'online',+ enabled: true,+ isEdge: false+};++const remoteEnvironment = {+ id: 'remote-switch-test',+ name: 'Remote Test',+ apiUrl: 'https://remote.example.invalid',+ status: 'online',+ enabled: true,+ isEdge: false+};++function paginated<T>(data: T[]) {+ return {+ success: true,+ data,+ counts: {+ runningContainers: data.length,+ stoppedContainers: 0,+ totalContainers: data.length+ },+ pagination: {+ totalPages: 1,+ totalItems: data.length,+ currentPage: 1,+ itemsPerPage: 20,+ grandTotalItems: data.length+ }+ };+}++function containerSummary(id: string, name: string) {+ return {+ id,+ names: [`/${name}`],+ image: 'nginx:latest',+ imageId: `sha256:${id}`,+ command: 'nginx',+ created: 1_700_000_000,+ labels: {},+ state: 'running',+ status: 'Up 5 minutes',+ ports: [],+ hostConfig: { networkMode: 'default' },+ networkSettings: { networks: {} },+ mounts: []+ };+}++function containerDetails(id: string, name: string) {+ return {+ id,+ name,+ image: 'nginx:latest',+ imageId: `sha256:${id}`,+ created: '2026-01-01T00:00:00Z',+ state: {+ status: 'running',+ running: true,+ startedAt: '2026-01-01T00:00:00Z',+ finishedAt: ''+ },+ config: {},+ hostConfig: { networkMode: 'default' },+ networkSettings: { networks: {} },+ ports: [],+ mounts: [],+ labels: {},+ redeployDisabled: false+ };+}++async function mockEnvironmentCatalog(page: Page) {+ await page.addInitScript(() => {+ localStorage.removeItem('selectedEnvironmentId');+ localStorage.removeItem('arcane-container-table');+ });+ await page.context().route(/\/api\/environments(?:\?.*)?$/, async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(paginated([localEnvironment, remoteEnvironment]))+ });+ });+ await page+ .context()+ .route(/\/api\/environments\/(?:0|remote-switch-test)\/settings$/, async (route) => {+ if (route.request().method() !== 'GET') {+ await route.continue();+ return;+ }+ await route.fulfill({ status: 200, contentType: 'application/json', body: '{}' });+ });+}++async function selectRemoteEnvironment(page: Page) {+ await page.getByRole('button').filter({ hasText: localEnvironment.name }).first().click();+ const dialog = page.getByRole('dialog', { name: 'Select Environment' });+ await expect(dialog).toBeVisible();+ await dialog.getByRole('button').filter({ hasText: remoteEnvironment.name }).first().click();+}++test.describe('Environment switch isolation', () => {+ test('clears local rows and stats targets while the remote response is delayed', async ({+ page+ }) => {+ let releaseRemote!: () => void;+ const remoteGate = new Promise<void>((resolve) => {+ releaseRemote = resolve;+ });+ let markRemoteStarted!: () => void;+ const remoteStarted = new Promise<void>((resolve) => {+ markRemoteStarted = resolve;+ });+ let remoteMarked = false;+ const websocketPaths: string[] = [];++ await mockEnvironmentCatalog(page);+ await page+ .context()+ .route(/\/api\/environments\/[^/]+\/containers(?:\?.*)?$/, async (route: Route) => {+ const pathname = new URL(route.request().url()).pathname;+ if (pathname === '/api/environments/remote-switch-test/containers') {+ if (!remoteMarked) {+ remoteMarked = true;+ markRemoteStarted();+ }+ await remoteGate;+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(paginated([containerSummary('remote-b-id', 'remote-b-container')]))+ });+ return;+ }+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(paginated([containerSummary('local-a-id', 'local-a-container')]))+ });+ });+ page.on('websocket', (socket) => websocketPaths.push(new URL(socket.url()).pathname));++ await page.goto('/containers');+ await expect(page.getByRole('link', { name: 'local-a-container', exact: true })).toBeVisible();++ try {+ await selectRemoteEnvironment(page);+ await remoteStarted;+ await expect(page.getByRole('link', { name: 'local-a-container', exact: true })).toHaveCount(+ 0+ );+ await page.waitForTimeout(200);+ expect(websocketPaths).not.toContain(+ '/api/environments/remote-switch-test/ws/containers/local-a-id/stats'+ );+ } finally {+ releaseRemote();+ }++ await expect(page.getByRole('link', { name: 'remote-b-container', exact: true })).toBeVisible();+ await expect(page.getByRole('link', { name: 'local-a-container', exact: true })).toHaveCount(0);+ });++ test('does not restore local rows when the remote request fails', async ({ page }) => {+ await mockEnvironmentCatalog(page);+ await page+ .context()+ .route(/\/api\/environments\/[^/]+\/containers(?:\?.*)?$/, async (route: Route) => {+ const pathname = new URL(route.request().url()).pathname;+ if (pathname === '/api/environments/remote-switch-test/containers') {+ await route.fulfill({+ status: 503,+ contentType: 'application/json',+ body: JSON.stringify({ success: false, message: 'remote unavailable' })+ });+ return;+ }+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(paginated([containerSummary('local-a-id', 'local-a-container')]))+ });+ });++ await page.goto('/containers');+ await expect(page.getByRole('link', { name: 'local-a-container', exact: true })).toBeVisible();+ const failedRemoteRequest = page.waitForResponse((response) => {+ return (+ new URL(response.url()).pathname === '/api/environments/remote-switch-test/containers' &&+ response.status() === 503+ );+ });+ await selectRemoteEnvironment(page);+ await failedRemoteRequest;+ await expect(page.getByRole('link', { name: 'local-a-container', exact: true })).toHaveCount(0);+ });++ test('remounts same-route details and navigates to the unwrapped redeployed container id', async ({+ page+ }) => {+ await page.addInitScript(() => localStorage.removeItem('selectedEnvironmentId'));+ const detailsById = {+ 'route-a': containerDetails('route-a', 'Route A Container'),+ 'route-b': containerDetails('route-b', 'Route B Container'),+ 'route-redeployed': containerDetails('route-redeployed', 'Redeployed Container')+ };++ await page.context().route(/\/api\/environments\/0\/settings$/, async (route) => {+ await route.fulfill({ status: 200, contentType: 'application/json', body: '{}' });+ });+ await page.context().route(/\/api\/environments\/0\/containers\/([^/?]+)$/, async (route) => {+ const id = decodeURIComponent(new URL(route.request().url()).pathname.split('/').pop() ?? '');+ const details = detailsById[id as keyof typeof detailsById];+ await route.fulfill({+ status: details ? 200 : 404,+ contentType: 'application/json',+ body: JSON.stringify(+ details ? { success: true, data: details } : { success: false, message: 'not found' }+ )+ });+ });+ await page+ .context()+ .route(/\/api\/environments\/0\/containers\/route-b\/redeploy$/, async (route) => {+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({ success: true, data: detailsById['route-redeployed'] })+ });+ });++ await page.goto('/containers/route-a');+ await expect(page.getByRole('heading', { name: 'Route A Container' })).toBeVisible();+ await page.getByRole('tab', { name: 'Logs' }).click();+ await expect(page.getByRole('tab', { name: 'Logs' })).toHaveAttribute('aria-selected', 'true');++ await page.evaluate(() => {+ const link = document.createElement('a');+ link.id = 'same-route-navigation';+ link.href = '/containers/route-b';+ link.textContent = 'navigate';+ document.body.append(link);+ });+ await page.locator('#same-route-navigation').click();+ await expect(page).toHaveURL('/containers/route-b');+ await expect(page.getByRole('heading', { name: 'Route B Container' })).toBeVisible();+ await expect(page.getByRole('tab', { name: 'Overview' })).toHaveAttribute(+ 'aria-selected',+ 'true'+ );++ await page.getByRole('button', { name: 'Redeploy', exact: true }).click();+ const dialog = page.getByRole('dialog');+ await dialog.getByRole('button', { name: 'Redeploy', exact: true }).click();+ await expect(page).toHaveURL('/containers/route-redeployed');+ await expect(page.getByRole('heading', { name: 'Redeployed Container' })).toBeVisible();+ });+});diff --git a/tests/spec/project.spec.ts b/tests/spec/project.spec.tsindex 4074d58d7..7ff5b9018 100644--- a/tests/spec/project.spec.ts+++ b/tests/spec/project.spec.ts@@ -725,15 +725,7 @@ test.describe('New Compose Project Page', () => {});expect(projectPullRequestCount).toBe(0);- const projectReloadResponse = page.waitForResponse(- (response) =>- response.request().method() === 'GET' &&- getPathname(response.url()) === `/api/environments/0/projects/${projectId}` &&- response.ok(),- { timeout: 30000 }- );await page.reload();- await projectReloadResponse;await expect(page).toHaveURL(new RegExp(`/projects/${projectId}`));await expect.poll(async () => (await fetchProjectDetail(page, projectId))?.status, {